дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Порівняти коміти
133
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
b5521c2605 | ||
|
|
26992ec4ce | ||
|
|
2c22574be0 | ||
|
|
93368d4379 | ||
|
|
14741101bd | ||
|
|
db60deede5 | ||
|
|
ab2a7767c7 | ||
|
|
49c917880d | ||
|
|
f0db09aca5 | ||
|
|
979cce1175 | ||
|
|
faa7571038 | ||
|
|
264bf6969f | ||
|
|
66e17df216 | ||
|
|
4ff5739854 | ||
|
|
a0c03447a0 | ||
|
|
c4e0900485 | ||
|
|
a42f13edc2 | ||
|
|
18d6041f2f | ||
|
|
15c5e921df | ||
|
|
bc64188c38 | ||
|
|
a3c819e064 | ||
|
|
1f2e92b433 | ||
|
|
8dfca955a5 | ||
|
|
91aba61c97 | ||
|
|
1fb4135b5b | ||
|
|
24598e0dae | ||
|
|
2436ad6fe9 | ||
|
|
c2c6931f0e | ||
|
|
2e0c8dd527 | ||
|
|
f4be752dda | ||
|
|
a52a639b8e | ||
|
|
1b0bf4d741 | ||
|
|
13597e40a1 | ||
|
|
aa1aa91b0d | ||
|
|
032a3b0453 | ||
|
|
07750ad984 | ||
|
|
ba38f070d9 | ||
|
|
c77f4db777 | ||
|
|
d3067c8d3a | ||
|
|
7bf2702565 | ||
|
|
65c45ffe05 | ||
|
|
84b528f0cd | ||
|
|
8621764813 | ||
|
|
22e1c4b927 | ||
|
|
e2817656e8 | ||
|
|
306c71290c | ||
|
|
51ccb68b72 | ||
|
|
2e965810e9 | ||
|
|
31b70cf0ac | ||
|
|
d0989e2a4b | ||
|
|
d96ed8d154 | ||
|
|
6b41870368 | ||
|
|
660becbaa4 | ||
|
|
a0afc478c1 | ||
|
|
07a88c6fa4 | ||
|
|
46bd6fad3c | ||
|
|
f64dbe65b4 | ||
|
|
e2a5a5db81 | ||
|
|
6eb7abff9f | ||
|
|
b46112fe0b | ||
|
|
4507dc172d | ||
|
|
8442c0c339 | ||
|
|
8ffe3bd230 | ||
|
|
1babff55fc | ||
|
|
2ad95150eb | ||
|
|
fe3e647abb | ||
|
|
62cc6768fe | ||
|
|
2e93422270 | ||
|
|
3a1353cc0e | ||
|
|
c5eab0a4a3 | ||
|
|
581c8cf025 | ||
|
|
807c447792 | ||
|
|
217693a56f | ||
|
|
557295b1df | ||
|
|
7c674e70e5 | ||
|
|
1602a5d010 | ||
|
|
a6d135d66f | ||
|
|
924bf6d3b9 | ||
|
|
318c227b0c | ||
|
|
2ce7621abb | ||
|
|
7ecccb3b75 | ||
|
|
7cbf17b10e | ||
|
|
cb0d02620d | ||
|
|
d6ca43cba4 | ||
|
|
165d4f7d76 | ||
|
|
5785ebadd8 | ||
|
|
0c67a4eea2 | ||
|
|
5e2deed81e | ||
|
|
cae7c05fb1 | ||
|
|
be83458161 | ||
|
|
661124d0d4 | ||
|
|
0dae111b2d | ||
|
|
61d269045b | ||
|
|
266d85fa1a | ||
|
|
f964d79e10 | ||
|
|
4a3eacff62 | ||
|
|
aebc2fe02d | ||
|
|
9b63aa9526 | ||
|
|
df07073886 | ||
|
|
3433ee951b | ||
|
|
8f5b281486 | ||
|
|
43aee8058c | ||
|
|
4016c3c905 | ||
|
|
e6cb7df653 | ||
|
|
2a26c82357 | ||
|
|
66f0bce92f | ||
|
|
dfbd13e2af | ||
|
|
944b57dead | ||
|
|
5bcb37492f | ||
|
|
d5bde9af67 | ||
|
|
5b3e2b7a3d | ||
|
|
dbb6fa51c3 | ||
|
|
3d1769ef00 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a | ||
|
|
3240164840 | ||
|
|
f70f362a3d | ||
|
|
806bb4c78d | ||
|
|
57094bc285 | ||
|
|
a5e0c41663 |
No files matched your search
@@ -3,7 +3,8 @@ name: Homebrew
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
|
||||
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
|
||||
# l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -27,17 +28,17 @@ jobs:
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and token
|
||||
- name: Check tag and deploy key
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
|
||||
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
@@ -47,7 +48,7 @@ jobs:
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
|
||||
@@ -39,6 +39,7 @@ on:
|
||||
- "src/editor/lsp/hint.ts"
|
||||
- "src/editor/lsp/lsp.ts"
|
||||
- "src/editor/lsp/positions.ts"
|
||||
- "src/editor/lsp/snippet.ts"
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
@@ -106,7 +107,7 @@ jobs:
|
||||
# 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-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
@@ -179,7 +179,7 @@ jobs:
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
|
||||
Створено
+50
-48
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4182,7 +4182,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4205,7 +4205,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4223,7 +4223,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4248,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4259,7 +4259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4281,7 +4281,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4294,7 +4294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4323,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4362,7 +4362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4375,7 +4375,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4389,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4409,7 +4409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4420,7 +4420,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4432,7 +4432,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4444,7 +4444,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4463,7 +4463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4519,6 +4519,7 @@ dependencies = [
|
||||
"ide-workspace",
|
||||
"ignore",
|
||||
"jsonschema",
|
||||
"notify",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"regex-lite",
|
||||
@@ -4544,7 +4545,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4563,7 +4564,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4586,7 +4587,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4598,7 +4599,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4614,7 +4615,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4623,7 +4624,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4634,7 +4635,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4693,7 +4694,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4704,6 +4705,7 @@ dependencies = [
|
||||
"ide-jsonrpc",
|
||||
"ide-jvm-inspect",
|
||||
"ide-language",
|
||||
"ide-sdk",
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
@@ -4722,7 +4724,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4741,7 +4743,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4762,7 +4764,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4784,7 +4786,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4798,7 +4800,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4818,7 +4820,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4843,7 +4845,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4859,7 +4861,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4885,7 +4887,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4906,7 +4908,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4919,7 +4921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4944,7 +4946,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4957,7 +4959,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4972,7 +4974,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4986,7 +4988,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4999,7 +5001,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -5022,7 +5024,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5044,7 +5046,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5071,7 +5073,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5087,7 +5089,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6726,7 +6728,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
let retry = run_once(shared, spec, true, model).await;
|
||||
|
||||
@@ -627,6 +627,40 @@ impl crate::AgentManager {
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
let account = account.trim();
|
||||
if !account.is_empty() {
|
||||
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
|
||||
}
|
||||
match discover(&self.shared, spec, model).await {
|
||||
Ok(found) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: self.shared.config_for_new_task(found.config, "copilot"),
|
||||
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
|
||||
retry_at_ms: None,
|
||||
error: None,
|
||||
}),
|
||||
Err(error) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: Vec::new(),
|
||||
thought_levels: BTreeMap::new(),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: None,
|
||||
retry_at_ms: None,
|
||||
error: Some(error),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
|
||||
@@ -505,6 +505,84 @@ struct TaskFile {
|
||||
pending_native_fork: Option<ForkStart>,
|
||||
}
|
||||
|
||||
/// A task file with its history left unread: what is decoded for every task at startup.
|
||||
#[derive(Deserialize)]
|
||||
struct SavedHead {
|
||||
entries: Counted,
|
||||
#[serde(default, rename = "subagents")]
|
||||
_subagents: serde::de::IgnoredAny,
|
||||
#[serde(default, rename = "turn")]
|
||||
_turn: serde::de::IgnoredAny,
|
||||
#[serde(default, rename = "turns")]
|
||||
_turns: serde::de::IgnoredAny,
|
||||
#[serde(flatten)]
|
||||
rest: serde_json::Map<String, Value>,
|
||||
}
|
||||
|
||||
/// The history in a task file, the rest left unread.
|
||||
#[derive(Deserialize)]
|
||||
struct SavedBody {
|
||||
entries: Vec<Value>,
|
||||
#[serde(default)]
|
||||
subagents: Vec<SavedSubagent>,
|
||||
#[serde(default)]
|
||||
turn: Option<worktree::TurnStart>,
|
||||
#[serde(default)]
|
||||
turns: Vec<Option<worktree::TurnStart>>,
|
||||
}
|
||||
|
||||
/// The length of a JSON array, its items skipped.
|
||||
struct Counted(usize);
|
||||
|
||||
impl<'de> Deserialize<'de> for Counted {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct Visitor;
|
||||
impl<'de> serde::de::Visitor<'de> for Visitor {
|
||||
type Value = Counted;
|
||||
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("an array")
|
||||
}
|
||||
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Counted, A::Error> {
|
||||
let mut n = 0;
|
||||
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
|
||||
n += 1;
|
||||
}
|
||||
Ok(Counted(n))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_seq(Visitor)
|
||||
}
|
||||
}
|
||||
|
||||
/// A task file without its history (empty in the result), and how many entries its
|
||||
/// conversation has.
|
||||
fn read_head(bytes: &[u8]) -> Result<(TaskFile, usize), String> {
|
||||
let head: SavedHead = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
|
||||
let mut rest = head.rest;
|
||||
rest.insert("entries".into(), json!([]));
|
||||
let file = serde_json::from_value::<TaskFile>(upgrade(Value::Object(rest))).map_err(|e| e.to_string())?;
|
||||
Ok((file, head.entries.0))
|
||||
}
|
||||
|
||||
/// The history saved in the task file at `path`.
|
||||
fn read_body(path: &Path) -> Result<History, String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
|
||||
let body: SavedBody = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
|
||||
drop(bytes);
|
||||
let entries = body
|
||||
.entries
|
||||
.into_iter()
|
||||
.map(|mut entry| {
|
||||
upgrade_entry(&mut entry);
|
||||
serde_json::from_value::<AgentEntry>(entry)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(History::new(entries, body.subagents, body.turn, body.turns))
|
||||
}
|
||||
|
||||
/// A session to start as a fork of the recorded one: its source, and the id the host
|
||||
/// chooses for the fork (claude); codex assigns its own.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -568,10 +646,97 @@ impl Drop for BusyGuard {
|
||||
}
|
||||
}
|
||||
|
||||
/// A task's conversation and the checkout as each of its turns started.
|
||||
#[derive(Default)]
|
||||
struct History {
|
||||
conversation: Conversation,
|
||||
/// See `TaskFile::turns`.
|
||||
turns: Vec<Option<Arc<worktree::TurnStart>>>,
|
||||
/// The task file's conversation couldn't be read: the task shows an empty one, and saving
|
||||
/// it is refused so the file keeps what it has.
|
||||
unreadable: bool,
|
||||
}
|
||||
|
||||
impl History {
|
||||
fn new(
|
||||
entries: Vec<AgentEntry>,
|
||||
subagents: Vec<SavedSubagent>,
|
||||
turn: Option<worktree::TurnStart>,
|
||||
turns: Vec<Option<worktree::TurnStart>>,
|
||||
) -> Self {
|
||||
let conversation = Conversation::restore(entries, subagents);
|
||||
let mut turns: Vec<_> = turns.into_iter().map(|t| t.map(Arc::new)).collect();
|
||||
// Saved with the last turn's only: the turns before it have none.
|
||||
if turns.is_empty()
|
||||
&& let Some(last) = turn
|
||||
{
|
||||
turns.resize(turn_starts(&conversation.main.entries).len().saturating_sub(1), None);
|
||||
turns.push(Some(Arc::new(last)));
|
||||
}
|
||||
Self { conversation, turns, unreadable: false }
|
||||
}
|
||||
|
||||
/// The history saved in the task file at `path`, settled: the agent that was running
|
||||
/// when it was saved did not survive the restart.
|
||||
fn read(path: &Path) -> Self {
|
||||
match read_body(path) {
|
||||
Ok(mut history) => {
|
||||
history.conversation.settle(now_ms());
|
||||
history
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("reading the conversation of agent task {}: {e}", path.display());
|
||||
Self { unreadable: true, ..Self::default() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A task's [`History`], read from its file the first time anything needs it: most tasks of
|
||||
/// a project aren't opened between two starts, and their conversations are most of what the
|
||||
/// task store holds.
|
||||
struct StoredHistory {
|
||||
/// The task file, for a history not read yet.
|
||||
file: Option<PathBuf>,
|
||||
history: std::cell::OnceCell<History>,
|
||||
}
|
||||
|
||||
impl StoredHistory {
|
||||
fn loaded(history: History) -> Self {
|
||||
Self { file: None, history: std::cell::OnceCell::from(history) }
|
||||
}
|
||||
|
||||
fn on_disk(file: PathBuf) -> Self {
|
||||
Self { file: Some(file), history: std::cell::OnceCell::new() }
|
||||
}
|
||||
|
||||
/// Whether the history is in memory (tests).
|
||||
#[cfg(test)]
|
||||
fn is_loaded(&self) -> bool {
|
||||
self.history.get().is_some()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for StoredHistory {
|
||||
type Target = History;
|
||||
|
||||
fn deref(&self) -> &History {
|
||||
self.history.get_or_init(|| self.file.as_deref().map(History::read).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for StoredHistory {
|
||||
fn deref_mut(&mut self) -> &mut History {
|
||||
let _ = &**self;
|
||||
self.history.get_mut().expect("the history was just read")
|
||||
}
|
||||
}
|
||||
|
||||
struct TaskState {
|
||||
task: AgentTask,
|
||||
session_id: Option<String>,
|
||||
conversation: Conversation,
|
||||
/// The conversation and its turns' checkouts, read from the task file on first use.
|
||||
history: StoredHistory,
|
||||
wanted: Vec<AgentConfigChoice>,
|
||||
pending_model: Option<PendingModel>,
|
||||
model_choice: u64,
|
||||
@@ -580,8 +745,6 @@ struct TaskState {
|
||||
saved: Option<String>,
|
||||
/// See `TaskFile::touched`.
|
||||
touched: Option<Arc<BTreeSet<String>>>,
|
||||
/// See `TaskFile::turns`.
|
||||
turns: Vec<Option<Arc<worktree::TurnStart>>>,
|
||||
pending_rollback: u32,
|
||||
/// The user named the task; see `TaskFile::title_renamed`.
|
||||
title_renamed: bool,
|
||||
@@ -767,20 +930,21 @@ impl AgentManager {
|
||||
if path.extension().is_none_or(|e| e != "json") {
|
||||
continue;
|
||||
}
|
||||
match std::fs::read(&path)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|b| serde_json::from_slice::<Value>(&b).map_err(|e| e.to_string()))
|
||||
.and_then(|v| serde_json::from_value::<TaskFile>(upgrade(v)).map_err(|e| e.to_string()))
|
||||
{
|
||||
Ok(mut f) => {
|
||||
// Only the task's own fields: its conversation is read when something needs it.
|
||||
match std::fs::read(&path).map_err(|e| e.to_string()).and_then(|b| read_head(&b)) {
|
||||
Ok((mut f, entries)) => {
|
||||
// The agent process did not survive the restart: whatever was in flight is over.
|
||||
if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) {
|
||||
f.task.status = AgentStatus::Ready;
|
||||
}
|
||||
f.task.retry = None;
|
||||
f.task.background.clear();
|
||||
let task = Task::restore(f, shared.clone());
|
||||
task.state.lock().conversation.settle(now_ms());
|
||||
// What an archived task's agent offered is only a cache, and a long list
|
||||
// repeated in every archived task: its next session reports its own.
|
||||
if f.task.status == AgentStatus::Archived {
|
||||
f.task.commands = Vec::new();
|
||||
}
|
||||
let task = Task::restore_saved(f, entries, path, shared.clone());
|
||||
tasks.insert(task.id.clone(), task);
|
||||
}
|
||||
Err(e) => tracing::warn!("skipping agent task {}: {e}", path.display()),
|
||||
@@ -832,6 +996,11 @@ impl AgentManager {
|
||||
*self.shared.git_executable.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// Directory holding linked Git worktrees created for agent tasks of this project.
|
||||
pub fn worktrees_dir(&self) -> &Path {
|
||||
&self.shared.paths.worktrees_dir
|
||||
}
|
||||
|
||||
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
|
||||
pub fn providers(&self) -> Vec<AgentProvider> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
@@ -979,7 +1148,14 @@ impl AgentManager {
|
||||
Some(id) => {
|
||||
let task = self.task(id)?;
|
||||
let s = task.state.lock();
|
||||
(s.task.provider.clone(), s.task.commands.clone(), s.task.cwd.0.clone())
|
||||
// A task without a session's list yet (archived, or just unarchived) offers
|
||||
// what its agent offered last time in the project.
|
||||
let offered = if s.task.commands.is_empty() {
|
||||
self.shared.known_commands(&s.task.provider)
|
||||
} else {
|
||||
s.task.commands.clone()
|
||||
};
|
||||
(s.task.provider.clone(), offered, s.task.cwd.0.clone())
|
||||
}
|
||||
None => (provider.to_owned(), self.shared.known_commands(provider), self.shared.paths.project_root.clone()),
|
||||
};
|
||||
@@ -1068,7 +1244,8 @@ impl AgentManager {
|
||||
pub fn entries(&self, id: &str, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
let task = self.task(id)?;
|
||||
let s = task.state.lock();
|
||||
let timeline = s.conversation.timeline(&subagent).ok_or_else(|| IdeError::not_found("no such subagent"))?;
|
||||
let timeline =
|
||||
s.history.conversation.timeline(&subagent).ok_or_else(|| IdeError::not_found("no such subagent"))?;
|
||||
Ok(timeline.entries.clone())
|
||||
}
|
||||
|
||||
@@ -1673,7 +1850,7 @@ impl AgentManager {
|
||||
return Err(IdeError::invalid("wait until the agent is done"));
|
||||
}
|
||||
let live = source.ensure_session().await.map_err(IdeError::internal)?;
|
||||
let total = turn_starts(&source.state.lock().conversation.main.entries).len() as u32;
|
||||
let total = turn_starts(&source.state.lock().history.conversation.main.entries).len() as u32;
|
||||
let keep = turns.unwrap_or(total).min(total);
|
||||
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
|
||||
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
|
||||
@@ -1707,7 +1884,7 @@ impl AgentManager {
|
||||
.to_owned();
|
||||
let file = {
|
||||
let s = source.state.lock();
|
||||
let mut entries = s.conversation.main.entries.clone();
|
||||
let mut entries = s.history.conversation.main.entries.clone();
|
||||
if let Some(&cut) = turn_starts(&entries).get(keep as usize) {
|
||||
entries.truncate(cut);
|
||||
}
|
||||
@@ -1739,7 +1916,7 @@ impl AgentManager {
|
||||
// The copies are the source's: the fork's turns are recorded as it runs them.
|
||||
turn: None,
|
||||
turns: Vec::new(),
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
subagents: s.history.conversation.saved_subagents(),
|
||||
pending_rollback: total - keep,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
@@ -1767,7 +1944,7 @@ impl AgentManager {
|
||||
if s.busy {
|
||||
return Err(IdeError::invalid("wait until the agent is done"));
|
||||
}
|
||||
let starts = turn_starts(&s.conversation.main.entries);
|
||||
let starts = turn_starts(&s.history.conversation.main.entries);
|
||||
let Some(&cut) = starts.get(turns as usize) else { return Ok(None) };
|
||||
s.busy = true;
|
||||
(starts, cut)
|
||||
@@ -1783,7 +1960,7 @@ impl AgentManager {
|
||||
let restamped = self.write_rewind(&task, planned).await?;
|
||||
let (first, dir, kept) = {
|
||||
let mut s = task.state.lock();
|
||||
let first = match s.conversation.main.entries.get(cut) {
|
||||
let first = match s.history.conversation.main.entries.get(cut) {
|
||||
Some(AgentEntry::User { text, .. }) => {
|
||||
Some(AgentPrompt { text: text.clone(), ..Default::default() })
|
||||
}
|
||||
@@ -1793,13 +1970,13 @@ impl AgentManager {
|
||||
s.pending_model = None;
|
||||
s.model_choice += 1;
|
||||
s.discovering_model = None;
|
||||
s.conversation = Conversation::default();
|
||||
s.history.conversation = Conversation::default();
|
||||
// The fresh session reports its own usage; nothing carries over.
|
||||
s.task.usage = None;
|
||||
s.pending_rollback = 0;
|
||||
s.task.updated_ms = now_ms();
|
||||
Self::finish_rewind(&mut s, 0, restamped);
|
||||
(first, task.turn_dir(), s.turns.clone())
|
||||
(first, task.turn_dir(), s.history.turns.clone())
|
||||
};
|
||||
drop(guard);
|
||||
task.streamed.lock().clear();
|
||||
@@ -1822,14 +1999,14 @@ impl AgentManager {
|
||||
let restamped = self.write_rewind(&task, planned).await?;
|
||||
let (first, dir, kept) = {
|
||||
let mut s = task.state.lock();
|
||||
let first = match s.conversation.main.entries.get(cut) {
|
||||
let first = match s.history.conversation.main.entries.get(cut) {
|
||||
Some(AgentEntry::User { text, .. }) => Some(AgentPrompt { text: text.clone(), ..Default::default() }),
|
||||
_ => None,
|
||||
};
|
||||
s.conversation.truncate(cut);
|
||||
s.history.conversation.truncate(cut);
|
||||
s.task.updated_ms = now_ms();
|
||||
Self::finish_rewind(&mut s, turns as usize, restamped);
|
||||
(first, task.turn_dir(), s.turns.clone())
|
||||
(first, task.turn_dir(), s.history.turns.clone())
|
||||
};
|
||||
drop(guard);
|
||||
task.streamed.lock().clear();
|
||||
@@ -2004,7 +2181,8 @@ impl AgentManager {
|
||||
let _answering = task.answering_questions.lock().await;
|
||||
let questions = {
|
||||
let s = task.state.lock();
|
||||
s.conversation
|
||||
s.history
|
||||
.conversation
|
||||
.main
|
||||
.entries
|
||||
.iter()
|
||||
@@ -2032,7 +2210,7 @@ impl AgentManager {
|
||||
};
|
||||
let changed = {
|
||||
let mut s = task.state.lock();
|
||||
s.conversation.main.entries.iter_mut().enumerate().find_map(|(index, entry)| match entry {
|
||||
s.history.conversation.main.entries.iter_mut().enumerate().find_map(|(index, entry)| match entry {
|
||||
AgentEntry::Question { id, chosen: current, .. } if id == question => {
|
||||
*current = Some(chosen.clone());
|
||||
Some((None, index))
|
||||
@@ -2049,6 +2227,8 @@ impl AgentManager {
|
||||
pub fn archive(&self, id: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
task.kill();
|
||||
// Not kept while archived; see `AgentManager::new`.
|
||||
task.state.lock().task.commands = Vec::new();
|
||||
task.set_status(AgentStatus::Archived, None);
|
||||
Ok(())
|
||||
}
|
||||
@@ -2203,8 +2383,8 @@ impl AgentManager {
|
||||
) -> IdeResult<Vec<worktree::PutBack>> {
|
||||
let (cwd, start, before, saved, touched, dropped_changed) = {
|
||||
let s = task.state.lock();
|
||||
let start = s.turns.get(turn).cloned().flatten();
|
||||
let dropped = s.turns.get(turn..).unwrap_or(&[]);
|
||||
let start = s.history.turns.get(turn).cloned().flatten();
|
||||
let dropped = s.history.turns.get(turn..).unwrap_or(&[]);
|
||||
let dropped_changed = (dropped.len() == total_turns - turn
|
||||
&& dropped.iter().all(|t| t.as_ref().is_some_and(|t| t.changed.is_some())))
|
||||
.then(|| {
|
||||
@@ -2270,7 +2450,7 @@ impl AgentManager {
|
||||
|
||||
/// Drops the records of the turns from `turn` on and applies any restamps to `before`.
|
||||
fn finish_rewind(s: &mut TaskState, turn: usize, restamped: Vec<(String, worktree::Stamp)>) {
|
||||
s.turns.truncate(turn);
|
||||
s.history.turns.truncate(turn);
|
||||
if !restamped.is_empty() {
|
||||
let mut before = (*s.before).clone();
|
||||
before.extend(restamped);
|
||||
@@ -2342,7 +2522,7 @@ impl AgentManager {
|
||||
s.before = Arc::new(before);
|
||||
}
|
||||
// Rolled back further than the last turn: what it changed there is gone, not the turn's to list.
|
||||
if let Some(Some(turn)) = s.turns.last_mut()
|
||||
if let Some(Some(turn)) = s.history.turns.last_mut()
|
||||
&& let Some(changed) = &turn.changed
|
||||
&& restored.iter().any(|rel| changed.contains(rel))
|
||||
{
|
||||
@@ -2600,19 +2780,29 @@ impl Task {
|
||||
}
|
||||
}
|
||||
|
||||
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
|
||||
/// A task whose conversation is at hand (a new task, a copy).
|
||||
fn restore(mut file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let adopt = file.entries.is_empty() && file.session_id.is_some();
|
||||
let history = History::new(
|
||||
std::mem::take(&mut file.entries),
|
||||
std::mem::take(&mut file.subagents),
|
||||
file.turn.take(),
|
||||
std::mem::take(&mut file.turns),
|
||||
);
|
||||
Self::assemble(file, StoredHistory::loaded(history), adopt, shared)
|
||||
}
|
||||
|
||||
/// A task read from the store without its conversation (`head`, see [`read_head`]): the
|
||||
/// conversation is read from `path` once something needs it.
|
||||
fn restore_saved(head: TaskFile, entries: usize, path: PathBuf, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let adopt = entries == 0 && head.session_id.is_some();
|
||||
Self::assemble(head, StoredHistory::on_disk(path), adopt, shared)
|
||||
}
|
||||
|
||||
/// The task from the parts of `file` other than its history, which `history` holds.
|
||||
fn assemble(file: TaskFile, history: StoredHistory, adopt: bool, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let mut task = file.task;
|
||||
config::add_client_options(&task.provider, &mut task.config);
|
||||
let adopt = file.entries.is_empty() && file.session_id.is_some();
|
||||
let conversation = Conversation::restore(file.entries, file.subagents);
|
||||
let mut turns: Vec<_> = file.turns.into_iter().map(|t| t.map(Arc::new)).collect();
|
||||
// Saved with the last turn's only: the turns before it have none.
|
||||
if turns.is_empty()
|
||||
&& let Some(last) = file.turn
|
||||
{
|
||||
turns.resize(turn_starts(&conversation.main.entries).len().saturating_sub(1), None);
|
||||
turns.push(Some(Arc::new(last)));
|
||||
}
|
||||
let mut wanted = file.wanted;
|
||||
let mut pending_model = file.pending_switch.or_else(|| {
|
||||
let id = file.pending_model?;
|
||||
@@ -2643,7 +2833,7 @@ impl Task {
|
||||
state: Mutex::new(TaskState {
|
||||
task,
|
||||
session_id: file.session_id,
|
||||
conversation,
|
||||
history,
|
||||
wanted,
|
||||
pending_model,
|
||||
model_choice: 0,
|
||||
@@ -2651,7 +2841,6 @@ impl Task {
|
||||
before: Arc::new(file.before),
|
||||
saved: file.saved,
|
||||
touched: file.touched.map(Arc::new),
|
||||
turns,
|
||||
pending_rollback: file.pending_rollback,
|
||||
title_renamed: file.title_renamed,
|
||||
ephemeral: file.ephemeral,
|
||||
@@ -2700,7 +2889,7 @@ impl Task {
|
||||
/// The checkout as the last turn started, with the folder of its copies.
|
||||
fn last_turn(&self) -> (PathBuf, Option<Arc<worktree::TurnStart>>, PathBuf) {
|
||||
let s = self.state.lock();
|
||||
(s.task.cwd.0.clone(), s.turns.last().cloned().flatten(), self.turn_dir())
|
||||
(s.task.cwd.0.clone(), s.history.turns.last().cloned().flatten(), self.turn_dir())
|
||||
}
|
||||
|
||||
/// Records the checkout as a turn starts (its message shown): what the turn's changes are
|
||||
@@ -2708,8 +2897,8 @@ impl Task {
|
||||
async fn checkout_before_turn(self: &Arc<Self>) {
|
||||
let (cwd, dir, index, earlier) = {
|
||||
let s = self.state.lock();
|
||||
let index = turn_starts(&s.conversation.main.entries).len().saturating_sub(1);
|
||||
let earlier: Vec<_> = s.turns.iter().take(index).cloned().collect();
|
||||
let index = turn_starts(&s.history.conversation.main.entries).len().saturating_sub(1);
|
||||
let earlier: Vec<_> = s.history.turns.iter().take(index).cloned().collect();
|
||||
(s.task.cwd.0.clone(), self.turn_dir(), index, earlier)
|
||||
};
|
||||
let kept = earlier.clone();
|
||||
@@ -2728,9 +2917,9 @@ impl Task {
|
||||
};
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
s.turns = earlier;
|
||||
s.turns.resize(index, None);
|
||||
s.turns.push(turn);
|
||||
s.history.turns = earlier;
|
||||
s.history.turns.resize(index, None);
|
||||
s.history.turns.push(turn);
|
||||
}
|
||||
self.persist_soon();
|
||||
}
|
||||
@@ -2753,7 +2942,7 @@ impl Task {
|
||||
touched.extend(in_worktree);
|
||||
s.touched = Some(Arc::new(touched));
|
||||
}
|
||||
if let Some(last) = s.turns.last_mut() {
|
||||
if let Some(last) = s.history.turns.last_mut() {
|
||||
*last = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
|
||||
}
|
||||
}
|
||||
@@ -2918,10 +3107,14 @@ impl Task {
|
||||
}
|
||||
let copy = {
|
||||
let s = self.state.lock();
|
||||
if s.history.unreadable {
|
||||
tracing::warn!("not saving agent task {}: its conversation couldn't be read", self.id);
|
||||
return;
|
||||
}
|
||||
TaskFile {
|
||||
task: s.task.clone(),
|
||||
session_id: s.session_id.clone(),
|
||||
entries: s.conversation.main.entries.clone(),
|
||||
entries: s.history.conversation.main.entries.clone(),
|
||||
wanted: s.wanted.clone(),
|
||||
pending_model: None,
|
||||
pending_switch: s.pending_model.clone(),
|
||||
@@ -2929,8 +3122,8 @@ impl Task {
|
||||
saved: s.saved.clone(),
|
||||
touched: s.touched.as_deref().cloned(),
|
||||
turn: None,
|
||||
turns: s.turns.iter().map(|t| t.as_deref().cloned()).collect(),
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
turns: s.history.turns.iter().map(|t| t.as_deref().cloned()).collect(),
|
||||
subagents: s.history.conversation.saved_subagents(),
|
||||
pending_rollback: s.pending_rollback,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
@@ -2966,7 +3159,7 @@ impl Task {
|
||||
indices
|
||||
.into_iter()
|
||||
.filter_map(|(subagent, i)| {
|
||||
let entry = s.conversation.timeline(&subagent)?.entries.get(i)?;
|
||||
let entry = s.history.conversation.timeline(&subagent)?.entries.get(i)?;
|
||||
entry_event(&self.id, &mut streamed, subagent, i, entry)
|
||||
})
|
||||
.collect()
|
||||
@@ -2978,7 +3171,7 @@ impl Task {
|
||||
|
||||
/// Folds an update made here (not by the agent) into the main conversation.
|
||||
fn apply_local(self: &Arc<Self>, update: &Value) {
|
||||
let changed = self.state.lock().conversation.apply(None, update, now_ms());
|
||||
let changed = self.state.lock().history.conversation.apply(None, update, now_ms());
|
||||
self.mark_dirty(changed);
|
||||
}
|
||||
|
||||
@@ -3007,8 +3200,8 @@ impl Task {
|
||||
fn take_entries(self: &Arc<Self>) -> Vec<AgentEntry> {
|
||||
let entries = {
|
||||
let mut s = self.state.lock();
|
||||
let entries = s.conversation.main.entries.clone();
|
||||
s.conversation.truncate(0);
|
||||
let entries = s.history.conversation.main.entries.clone();
|
||||
s.history.conversation.truncate(0);
|
||||
entries
|
||||
};
|
||||
self.streamed.lock().clear();
|
||||
@@ -3017,7 +3210,7 @@ impl Task {
|
||||
}
|
||||
|
||||
fn push_entry(self: &Arc<Self>, entry: AgentEntry) -> usize {
|
||||
let i = self.state.lock().conversation.main.push(entry);
|
||||
let i = self.state.lock().history.conversation.main.push(entry);
|
||||
self.mark_dirty([(None, i)]);
|
||||
i
|
||||
}
|
||||
@@ -3033,7 +3226,7 @@ impl Task {
|
||||
self.cancel_pending.store(false, Ordering::Release);
|
||||
tokio::time::sleep(TURN_GRACE).await;
|
||||
self.record_turn_changes().await;
|
||||
let changed = self.state.lock().conversation.end_turn(Some(now_ms()));
|
||||
let changed = self.state.lock().history.conversation.end_turn(Some(now_ms()));
|
||||
self.mark_dirty(changed);
|
||||
let send_now = self.send_now.swap(false, Ordering::AcqRel);
|
||||
let next = {
|
||||
@@ -3280,7 +3473,7 @@ impl Task {
|
||||
self.cancel_permissions();
|
||||
let gone = self.live.lock().as_ref().is_none_or(|l| l.peer.is_closed());
|
||||
if gone {
|
||||
let changed = self.state.lock().conversation.settle(now_ms());
|
||||
let changed = self.state.lock().history.conversation.settle(now_ms());
|
||||
self.mark_dirty(changed);
|
||||
}
|
||||
self.push_entry(AgentEntry::Error { message: failure.message.clone() });
|
||||
@@ -3682,7 +3875,7 @@ impl Task {
|
||||
if let Some(shown) = shown {
|
||||
if loaded.is_ok() {
|
||||
self.adopting_replay.store(false, Ordering::Release);
|
||||
let changed = self.state.lock().conversation.end_turn(None);
|
||||
let changed = self.state.lock().history.conversation.end_turn(None);
|
||||
self.mark_dirty(changed);
|
||||
} else {
|
||||
// A failed load may still have replayed part of it.
|
||||
@@ -4017,7 +4210,7 @@ impl Task {
|
||||
fn on_update(self: &Arc<Self>, session: Option<&str>, update: &Value) {
|
||||
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
|
||||
// A subagent's title, settings and usage are its own, not the task's.
|
||||
if self.state.lock().conversation.owner(session).is_some() {
|
||||
if self.state.lock().history.conversation.owner(session).is_some() {
|
||||
if !SESSION_STATE.contains(&kind) && (!self.replaying.load(Ordering::Acquire) || self.adopts_replay()) {
|
||||
self.apply(session, kind, update);
|
||||
}
|
||||
@@ -4167,14 +4360,14 @@ impl Task {
|
||||
}
|
||||
let changed = {
|
||||
let mut s = self.state.lock();
|
||||
let entries = &mut s.conversation.main.entries;
|
||||
let entries = &mut s.history.conversation.main.entries;
|
||||
// The chunks of one message arrive in a row.
|
||||
if let Some(AgentEntry::User { text: shown, images, .. }) = entries.last_mut() {
|
||||
shown.push_str(&text);
|
||||
images.extend(image);
|
||||
entries.len() - 1
|
||||
} else {
|
||||
s.conversation.main.push(AgentEntry::User {
|
||||
s.history.conversation.main.push(AgentEntry::User {
|
||||
text,
|
||||
attachments: Vec::new(),
|
||||
images: image.into_iter().collect(),
|
||||
@@ -4190,7 +4383,7 @@ impl Task {
|
||||
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
|
||||
// Output again: the retried request went through.
|
||||
self.set_retry(None);
|
||||
let applied = self.state.lock().conversation.apply(session, update, now_ms());
|
||||
let applied = self.state.lock().history.conversation.apply(session, update, now_ms());
|
||||
self.mark_dirty(applied);
|
||||
// A subagent can start or finish after the turn that started it: nothing else saves it then.
|
||||
if matches!(kind, "subagent_update" | "user_question") {
|
||||
@@ -4342,7 +4535,7 @@ impl Task {
|
||||
/// A request from a subagent is answered in the task's conversation, named after the subagent.
|
||||
fn labelled(&self, params: &Value, title: String) -> String {
|
||||
let session = params.get("sessionId").and_then(Value::as_str);
|
||||
match session.and_then(|s| self.state.lock().conversation.label(s)) {
|
||||
match session.and_then(|s| self.state.lock().history.conversation.label(s)) {
|
||||
Some(label) => format!("{label}: {title}"),
|
||||
None => title,
|
||||
}
|
||||
@@ -4381,7 +4574,9 @@ impl Task {
|
||||
fn settle(self: &Arc<Self>, entry: usize, chosen: String) {
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
if let Some(AgentEntry::Permission { chosen: answer, .. }) = s.conversation.main.entries.get_mut(entry) {
|
||||
if let Some(AgentEntry::Permission { chosen: answer, .. }) =
|
||||
s.history.conversation.main.entries.get_mut(entry)
|
||||
{
|
||||
*answer = Some(chosen);
|
||||
}
|
||||
}
|
||||
@@ -4403,7 +4598,7 @@ impl Task {
|
||||
return;
|
||||
}
|
||||
let mut pending = self.permissions.lock();
|
||||
for entry in s.conversation.main.entries.iter().rev() {
|
||||
for entry in s.history.conversation.main.entries.iter().rev() {
|
||||
// A request with questions is never satisfied by a bypass: its Submit option
|
||||
// would answer with no answers.
|
||||
if let AgentEntry::Permission { id, options, questions, chosen: None, .. } = entry
|
||||
@@ -4644,15 +4839,20 @@ fn upgrade(mut file: Value) -> Value {
|
||||
}
|
||||
}
|
||||
for entry in file.get_mut("entries").and_then(Value::as_array_mut).into_iter().flatten() {
|
||||
if entry.get("type").and_then(Value::as_str) == Some("user")
|
||||
&& let Some(e) = entry.as_object_mut()
|
||||
{
|
||||
e.entry("attachments").or_insert(json!([]));
|
||||
}
|
||||
upgrade_entry(entry);
|
||||
}
|
||||
file
|
||||
}
|
||||
|
||||
/// Fills in what an entry saved by an earlier version leaves out.
|
||||
fn upgrade_entry(entry: &mut Value) {
|
||||
if entry.get("type").and_then(Value::as_str) == Some("user")
|
||||
&& let Some(e) = entry.as_object_mut()
|
||||
{
|
||||
e.entry("attachments").or_insert(json!([]));
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a turn failed.
|
||||
struct Failure {
|
||||
message: String,
|
||||
@@ -5100,7 +5300,8 @@ fn tool_event(
|
||||
i: usize,
|
||||
entry: &AgentEntry,
|
||||
) -> Option<AgentEvent> {
|
||||
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms } = entry
|
||||
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms, command } =
|
||||
entry
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
@@ -5115,6 +5316,7 @@ fn tool_event(
|
||||
diffs: diffs.clone(),
|
||||
started_ms: *started_ms,
|
||||
ended_ms: *ended_ms,
|
||||
command: command.clone(),
|
||||
};
|
||||
let text = output.as_deref().unwrap_or_default();
|
||||
let key = (subagent, i);
|
||||
|
||||
@@ -547,6 +547,9 @@ pub enum AgentEntry {
|
||||
started_ms: Option<f64>,
|
||||
#[serde(default)]
|
||||
ended_ms: Option<f64>,
|
||||
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
|
||||
#[serde(default)]
|
||||
command: Option<String>,
|
||||
},
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
|
||||
@@ -1481,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
|
||||
let message = translate::error_message(&e);
|
||||
return match translate::classify(&e, rate_limits) {
|
||||
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
|
||||
Failure::UsageLimit(resets) => Err(ResponseError {
|
||||
code: codes::INTERNAL_ERROR,
|
||||
message,
|
||||
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
|
||||
}),
|
||||
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
|
||||
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
};
|
||||
}
|
||||
_ => "end_turn",
|
||||
|
||||
@@ -455,6 +455,90 @@ fn failures_are_classified() {
|
||||
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turns_preserve_codex_error_diagnostics() {
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
|
||||
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
|
||||
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
|
||||
assert_eq!(failure.code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
// A completed turn's own error wins over an older error notification.
|
||||
let failure = stop_reason(
|
||||
&json!({ "status": "failed", "error": policy }),
|
||||
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
|
||||
for (value, expected) in [
|
||||
(
|
||||
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
|
||||
"Context is full.\nCodex error: contextWindowExceeded",
|
||||
),
|
||||
(
|
||||
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
|
||||
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
|
||||
),
|
||||
(
|
||||
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
|
||||
"Failed\nbecause",
|
||||
),
|
||||
(
|
||||
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
|
||||
"Codex failed\nDetails\nCodex error: cyberPolicy",
|
||||
),
|
||||
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
|
||||
(json!({}), "Codex failed"),
|
||||
] {
|
||||
assert_eq!(error_message(&value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
|
||||
for notification_only in [false, true] {
|
||||
let mut transcript = load(Scenario::UsageLimit.file());
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
match frame["method"].as_str() {
|
||||
Some("error") => frame["params"]["error"] = policy.clone(),
|
||||
Some("turn/completed") => {
|
||||
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
match result(&results, "prompt") {
|
||||
Err(RpcError::Server { code, message, .. }) => {
|
||||
assert_eq!(*code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(
|
||||
message,
|
||||
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
|
||||
);
|
||||
}
|
||||
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approvals_offer_what_codex_offers_and_always_a_decline() {
|
||||
let params = json!({"availableDecisions": ["accept",
|
||||
|
||||
@@ -740,7 +740,7 @@ pub(super) enum Failure {
|
||||
UsageLimit(Option<f64>),
|
||||
/// Signed out or refused.
|
||||
Auth,
|
||||
/// The model declined.
|
||||
/// The server blocked the turn under a safety policy.
|
||||
Refusal,
|
||||
Other,
|
||||
}
|
||||
@@ -780,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
|
||||
exhausted.map(|s| s * 1000.0)
|
||||
}
|
||||
|
||||
/// The text a failed turn reports: codex's message, with its details.
|
||||
/// The text a failed turn reports: Codex's message, details and diagnostic code.
|
||||
pub(super) fn error_message(error: &Value) -> String {
|
||||
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
|
||||
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
|
||||
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
|
||||
_ => message.to_owned(),
|
||||
let original =
|
||||
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
|
||||
let mut message = original.to_owned();
|
||||
if let Some(details) =
|
||||
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
|
||||
&& !original.contains(details)
|
||||
{
|
||||
message.push('\n');
|
||||
message.push_str(details);
|
||||
}
|
||||
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
|
||||
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
|
||||
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
|
||||
message.push_str(&format!("\nCodex error: {code}"));
|
||||
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
|
||||
message.push_str(&format!(" (HTTP {status})"));
|
||||
}
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
/// One choice of an approval: what ACP shows and what codex gets back.
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
|
||||
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
|
||||
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
@@ -199,7 +199,7 @@ pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> O
|
||||
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
|
||||
if !prefer_stored
|
||||
&& has_ambient
|
||||
|
||||
@@ -154,12 +154,26 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
|
||||
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
} else if is_copilot
|
||||
&& !strip_ambient_tokens
|
||||
&& !explicit_copilot_token
|
||||
&& ide_core::project_env::github_token(cwd).is_some()
|
||||
&& let Some(default_token) = default_github_token()
|
||||
{
|
||||
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
|
||||
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
@@ -169,7 +183,7 @@ impl ProviderSpec {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
@@ -275,7 +289,18 @@ fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn is_valid_github_login(account: &str) -> bool {
|
||||
let bytes = account.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
if !is_valid_github_login(account) {
|
||||
return Err(format!("Invalid GitHub account login: {account}"));
|
||||
}
|
||||
let program = find_gh_executable()
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
@@ -386,7 +411,8 @@ fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
|
||||
if entry.state.as_deref().is_some_and(|s| s != "success") {
|
||||
continue;
|
||||
}
|
||||
if matches!(entry.token_source.as_deref(), Some("GITHUB_TOKEN" | "GH_TOKEN" | "COPILOT_GITHUB_TOKEN")) {
|
||||
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
|
||||
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
|
||||
@@ -406,7 +432,8 @@ fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
|
||||
let trimmed = line.trim();
|
||||
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
|
||||
let login = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
if !login.is_empty() {
|
||||
current = None;
|
||||
if !login.is_empty() && !rest.contains("_TOKEN") {
|
||||
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
|
||||
current = Some(idx);
|
||||
} else {
|
||||
@@ -423,6 +450,20 @@ fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
|
||||
accounts
|
||||
}
|
||||
|
||||
fn default_github_token() -> Option<String> {
|
||||
let program = find_gh_executable()?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command.output().ok().filter(|out| out.status.success())?;
|
||||
let token = String::from_utf8(output.stdout).ok()?;
|
||||
let token = token.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -431,18 +472,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
|
||||
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
|
||||
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
|
||||
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
|
||||
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
|
||||
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
ide_core::process::shell_env()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
|
||||
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
|
||||
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
|
||||
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds child environment overrides for `copilot`:
|
||||
@@ -453,9 +493,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
|
||||
pub(crate) fn sanitized_copilot_env(
|
||||
spec_env: &[(String, String)],
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Vec<(String, String)> {
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_copilot_env_with(
|
||||
@@ -1695,6 +1736,8 @@ mod tests {
|
||||
|
||||
let text = "\
|
||||
github.com
|
||||
✓ Logged in to github.com account env_user (GH_TOKEN)
|
||||
- Active account: true
|
||||
✓ Logged in to github.com account alice (keyring)
|
||||
- Active account: false
|
||||
✓ Logged in to github.com account alice-work (keyring)
|
||||
|
||||
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
|
||||
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
|
||||
}
|
||||
|
||||
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let linux_arm = format!(
|
||||
"copilot-{}-arm64.tar.gz",
|
||||
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
|
||||
);
|
||||
let linux_x64 =
|
||||
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
|
||||
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
|
||||
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
|
||||
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
|
||||
let (glibc_rel, musl_rel) = match arch {
|
||||
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
|
||||
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
|
||||
};
|
||||
let glibc = root.join(glibc_rel);
|
||||
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
|
||||
let points_to_musl =
|
||||
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
|
||||
let has_glibc = glibc.exists() && !points_to_musl;
|
||||
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -1304,4 +1328,96 @@ esac
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let archives_for = |root: &Path| -> (String, String) {
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
|
||||
(
|
||||
entry.distribution.binary["linux-x86_64"].archive.clone(),
|
||||
entry.distribution.binary["linux-aarch64"].archive.clone(),
|
||||
)
|
||||
};
|
||||
let touch = |path: PathBuf| {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b"").unwrap();
|
||||
};
|
||||
|
||||
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
assert_eq!(
|
||||
archives_for(empty.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
|
||||
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
|
||||
let glibc = tempfile::tempdir().unwrap();
|
||||
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
|
||||
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
|
||||
let musl = tempfile::tempdir().unwrap();
|
||||
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::create_dir_all(musl.path().join("lib64")).unwrap();
|
||||
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let parsed = parse(index).unwrap().remove(0);
|
||||
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
|
||||
assert!(
|
||||
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
|
||||
"unexpected linux-x86_64 archive: {}",
|
||||
parsed.distribution.binary["linux-x86_64"].archive
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
|
||||
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
|
||||
}
|
||||
|
||||
fn command_from_value(val: &Value) -> Option<String> {
|
||||
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
|
||||
match val {
|
||||
Value::String(s) => {
|
||||
let trimmed = s.trim();
|
||||
|
||||
@@ -642,15 +642,98 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
mgr.shutdown();
|
||||
let restored_agent = Arc::new(FakeAgent::default());
|
||||
let restored = manager(tmp.path(), restored_agent.clone());
|
||||
// Listing the tasks leaves the conversation on disk until something asks for it.
|
||||
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
|
||||
assert!(!restored.task(&task.id).unwrap().state.lock().history.is_loaded());
|
||||
assert!(!restored.entries(&task.id, None).unwrap().is_empty());
|
||||
assert!(restored.task(&task.id).unwrap().state.lock().history.is_loaded());
|
||||
assert!(restored_agent.calls.lock().is_empty());
|
||||
assert!(restored.entries("missing-task", None).is_err());
|
||||
assert!(restored.entries(&task.id, Some("missing-subagent".into())).is_err());
|
||||
restored.task(&task.id).unwrap().state.lock().conversation = Conversation::default();
|
||||
restored.task(&task.id).unwrap().state.lock().history.conversation = Conversation::default();
|
||||
assert!(restored.entries(&task.id, None).unwrap().is_empty());
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("hello"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let names = |list: Vec<AgentCommand>| list.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
let snapshot = |mgr: &AgentManager| mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(names(snapshot(&mgr).commands).contains(&"review".to_owned()));
|
||||
|
||||
mgr.archive(&task.id).unwrap();
|
||||
assert!(snapshot(&mgr).commands.is_empty());
|
||||
assert!(names(mgr.commands("claude", Some(&task.id)).await.unwrap()).contains(&"review".to_owned()));
|
||||
mgr.shutdown();
|
||||
|
||||
// A list saved with an archived task (by an earlier version) isn't read back.
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(other.path().join("store")).unwrap();
|
||||
let name = format!("{}.json", task.id);
|
||||
let mut file: Value =
|
||||
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
|
||||
assert_eq!(file["task"]["status"], json!("archived"));
|
||||
file["task"]["commands"] = json!([{"name": "old", "description": "Old", "hint": null}]);
|
||||
std::fs::write(other.path().join("store").join(&name), serde_json::to_vec(&file).unwrap()).unwrap();
|
||||
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
|
||||
assert!(snapshot(&restored).commands.is_empty());
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Keep this"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.shutdown();
|
||||
// In a store of its own: a late save of the first manager can't touch it.
|
||||
let name = format!("{}.json", task.id);
|
||||
let mut file: Value =
|
||||
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
|
||||
file["entries"].as_array_mut().unwrap().push(json!({"type": "no-such-entry"}));
|
||||
let damaged = serde_json::to_vec(&file).unwrap();
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(other.path().join("store")).unwrap();
|
||||
let path = other.path().join("store").join(&name);
|
||||
std::fs::write(&path, &damaged).unwrap();
|
||||
|
||||
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
|
||||
// The task is listed from its own fields; its conversation shows empty.
|
||||
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
|
||||
assert!(restored.entries(&task.id, None).unwrap().is_empty());
|
||||
restored.rename(&task.id, "Renamed").unwrap();
|
||||
restored.shutdown();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), damaged);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1479,9 +1562,9 @@ async fn saving_a_large_task_does_not_hold_up_readers() {
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
for i in 0..24 {
|
||||
let text = format!("output {i}: \"quoted\"\n").repeat(40_000);
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text });
|
||||
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text });
|
||||
}
|
||||
let entries = handle.state.lock().conversation.main.entries.clone();
|
||||
let entries = handle.state.lock().history.conversation.main.entries.clone();
|
||||
let started = std::time::Instant::now();
|
||||
let json = serde_json::to_vec(&entries).unwrap();
|
||||
let serialising = started.elapsed();
|
||||
@@ -1574,7 +1657,7 @@ async fn concurrent_saves_keep_the_newest_state_of_each_task() {
|
||||
let task = idle_task(&mgr, name).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
// Long enough that a save takes a while between the copy and the write.
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
|
||||
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
|
||||
tasks.push((name, handle, task_file(tmp.path(), &task.id)));
|
||||
}
|
||||
// "<name> <n>", n growing with every change made under the state lock.
|
||||
@@ -2693,7 +2776,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
|
||||
mgr.shutdown();
|
||||
let restored = manager(tmp.path(), agent);
|
||||
let handle = restored.task(&task.id).unwrap();
|
||||
assert_eq!(handle.state.lock().conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
|
||||
assert_eq!(handle.state.lock().history.conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
@@ -2789,13 +2872,13 @@ async fn forks_rollbacks_and_steering() {
|
||||
"state": {"state": "idle", "stopReason": "end_turn"}}),
|
||||
);
|
||||
}
|
||||
handle.state.lock().conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
|
||||
handle.state.lock().history.conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
|
||||
let rewinds = agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count();
|
||||
let first = mgr.rollback(&task.id, 0, false).await.unwrap().unwrap();
|
||||
assert_eq!(first.text, "again");
|
||||
assert!(mgr.entries(&task.id, None).unwrap().is_empty());
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_none());
|
||||
assert!(handle.state.lock().conversation.saved_subagents().is_empty());
|
||||
assert!(handle.state.lock().history.conversation.saved_subagents().is_empty());
|
||||
assert!(handle.state.lock().task.usage.is_none());
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count(), rewinds);
|
||||
mgr.shutdown();
|
||||
@@ -4369,6 +4452,7 @@ fn a_running_tools_output_is_sent_as_appends() {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(1.0),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let running = |output| call(AgentToolStatus::Running, output);
|
||||
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
|
||||
@@ -4950,7 +5034,7 @@ async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
|
||||
Isolation::Worktree => None,
|
||||
};
|
||||
assert_eq!(read("later.txt").as_deref(), later, "{case}");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().turns.len(), 1, "{case}");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().history.turns.len(), 1, "{case}");
|
||||
|
||||
// Without `files` they stay; the first message takes the task back to its start.
|
||||
one_turn(&mgr, &task.id, Some("retry"), || write("a.txt", "again\n")).await;
|
||||
@@ -4958,7 +5042,7 @@ async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
|
||||
assert_eq!(read("a.txt").as_deref(), Some("again\n"), "{case}");
|
||||
mgr.rollback(&task.id, 0, true).await.unwrap();
|
||||
assert_eq!(read("a.txt").as_deref(), Some("base\n"), "{case}");
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().turns.is_empty(), "{case}");
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().history.turns.is_empty(), "{case}");
|
||||
let left = std::fs::read_dir(repo.dir.join("store").join(format!("{}.turn", task.id)));
|
||||
assert!(left.map_or(true, |mut d| d.next().is_none()), "{case}: no copies left");
|
||||
mgr.delete(&task.id, true).await.unwrap();
|
||||
@@ -4979,7 +5063,7 @@ async fn a_message_sent_before_turns_were_recorded_cannot_take_the_files_back()
|
||||
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
|
||||
one_turn(&mgr, &task.id, Some("last"), || repo.write("a.txt", "base\nturn 1\nturn 2\nturn 3\n")).await;
|
||||
// As a task saved with its last turn's record only.
|
||||
mgr.task(&task.id).unwrap().state.lock().turns[1] = None;
|
||||
mgr.task(&task.id).unwrap().state.lock().history.turns[1] = None;
|
||||
assert!(mgr.rollback(&task.id, 1, true).await.is_err());
|
||||
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 3, "nothing changed");
|
||||
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\nturn 3\n");
|
||||
@@ -5007,7 +5091,7 @@ async fn rolling_back_to_first_message_without_turn_record_checks_before_changin
|
||||
{
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let mut s = handle.state.lock();
|
||||
s.turns[0] = None;
|
||||
s.history.turns[0] = None;
|
||||
s.saved = None;
|
||||
}
|
||||
assert!(mgr.rollback(&task.id, 0, true).await.is_err());
|
||||
|
||||
@@ -91,6 +91,7 @@ impl Timeline {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let index = match self.tools.get(&id) {
|
||||
Some(&i) => {
|
||||
@@ -154,7 +155,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -171,6 +172,11 @@ impl Timeline {
|
||||
*ended_ms = Some(crate::now_ms());
|
||||
}
|
||||
}
|
||||
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
|
||||
&& let Some(cmd) = crate::security::command_from_value(raw)
|
||||
{
|
||||
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
|
||||
}
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
@@ -471,6 +477,34 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_execute_call_keeps_the_command_from_its_structured_input() {
|
||||
let mut t = Timeline::default();
|
||||
let command = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { command, .. } => command.clone(),
|
||||
_ => panic!(),
|
||||
};
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
|
||||
"rawInput": {"command": "python hello_world.py"}}));
|
||||
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
|
||||
// An argv array whose shell wraps the script, sent with a later update.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
|
||||
assert_eq!(command(&t, 1), None);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
|
||||
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
|
||||
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
|
||||
// One shell line, unwrapped as the permission card does.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
|
||||
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
// A later update without one keeps it; tasks saved before the field load without it.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("command");
|
||||
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
|
||||
@@ -323,7 +323,8 @@ mod tests {
|
||||
"exclude": [path(&root.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let a = root.join("packages/a");
|
||||
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
|
||||
let a = root.join("packages").join("a");
|
||||
assert_eq!(
|
||||
copy(1),
|
||||
json!({
|
||||
@@ -336,14 +337,14 @@ mod tests {
|
||||
"exclude": [path(&a.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let b = root.join("packages/b");
|
||||
let b = root.join("packages").join("b");
|
||||
assert_eq!(
|
||||
copy(2),
|
||||
json!({
|
||||
"extends": path(&b.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
|
||||
},
|
||||
"references": [{"path": s("1.json")}],
|
||||
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
|
||||
|
||||
@@ -91,12 +91,14 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
|
||||
|
||||
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
|
||||
/// redirector loaded before Maven calculates its lifecycle execution plans.
|
||||
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
|
||||
pub fn build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
bundle: &Path,
|
||||
generation: &Path,
|
||||
cancel: &CancellationToken,
|
||||
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = plan(root, model, cancel)?;
|
||||
@@ -124,10 +126,10 @@ pub fn build(
|
||||
for step in &plan.steps {
|
||||
let mut reactor = plan.clone();
|
||||
reactor.steps = vec![step.clone()];
|
||||
let result = compile::run(root, &reactor, cancel, &|event| {
|
||||
if let BuildEvent::Output { text, .. } = event {
|
||||
tracing::debug!("kotlin bridge: {}", text.trim_end());
|
||||
}
|
||||
let result = compile::run(root, &reactor, cancel, &|event| match event {
|
||||
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
|
||||
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
|
||||
_ => {}
|
||||
})?;
|
||||
messages.extend(result.messages);
|
||||
}
|
||||
@@ -456,6 +458,7 @@ mod tests {
|
||||
Path::new("unused.jar"),
|
||||
&directory.path().join("private"),
|
||||
&CancellationToken::new(),
|
||||
&|_, _| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
|
||||
@@ -505,6 +505,19 @@ pub struct LanguageCodeStyle {
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
/// JavaScript / TypeScript › Imports › Import paths:
|
||||
/// `shortest` | `relative` | `non-relative` | `project-relative`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier_ending: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_file_exclude_patterns: Vec<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_specifier_exclude_regexes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -562,6 +575,25 @@ pub struct EncodingSettings {
|
||||
pub native_to_ascii: bool,
|
||||
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
|
||||
pub utf8_bom: String,
|
||||
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
/// relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
#[serde(deserialize_with = "labels")]
|
||||
#[specta(type = BTreeMap<String, String>)]
|
||||
pub mappings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
|
||||
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter_map(|(path, label)| match label {
|
||||
serde_json::Value::String(label) => Some((path, label)),
|
||||
_ => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Default for EncodingSettings {
|
||||
@@ -572,10 +604,30 @@ impl Default for EncodingSettings {
|
||||
properties: "iso-8859-1".into(),
|
||||
native_to_ascii: false,
|
||||
utf8_bom: "never".into(),
|
||||
mappings: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod encoding_mappings_tests {
|
||||
use super::EncodingSettings;
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_keep_the_entries_that_are_labels() {
|
||||
let json = serde_json::json!({
|
||||
"project": "gbk",
|
||||
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
|
||||
});
|
||||
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(settings.project, "gbk");
|
||||
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
|
||||
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
|
||||
assert!(not_a_table.mappings.is_empty());
|
||||
assert!(EncodingSettings::default().mappings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod auto_import_tests {
|
||||
use super::{AutoImportSettings, ImportsOnPaste};
|
||||
|
||||
@@ -13,13 +13,34 @@ use std::sync::Arc;
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to.
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
|
||||
/// Run would, answered the same way.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum McpUiRequest {
|
||||
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
|
||||
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
|
||||
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
|
||||
Confirm {
|
||||
client: String,
|
||||
tool: String,
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
column: Option<u32>,
|
||||
},
|
||||
AgentRun {
|
||||
name: String,
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
config: serde_json::Value,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -27,6 +48,10 @@ pub enum McpUiRequest {
|
||||
pub enum IdeEvent {
|
||||
/// Project data source settings changed; reload the Database tree.
|
||||
DbSourcesChanged,
|
||||
/// A Python run saved a matplotlib figure for the Plots tool window (a PNG file).
|
||||
PlotAdded {
|
||||
path: String,
|
||||
},
|
||||
McpRequest {
|
||||
id: u32,
|
||||
request: McpUiRequest,
|
||||
|
||||
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
|
||||
|
||||
struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
changes: Changes,
|
||||
loading: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(root: PathBuf) -> Self {
|
||||
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
|
||||
if let Some(token) = &self.github_token {
|
||||
combined.push(("GH_TOKEN".into(), Some(token.clone())));
|
||||
}
|
||||
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
|
||||
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
|
||||
combined.extend(self.direnv.iter().cloned());
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
|
||||
static SETTLED: Condvar = Condvar::new();
|
||||
|
||||
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
|
||||
let mut entries = entries();
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => entry.loading = true,
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
|
||||
None => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.loading = true;
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What children started in `root` (or below it) get on top of the IDE's own environment
|
||||
/// (`None`: removed). Ends a [`begin_loading`].
|
||||
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
|
||||
/// environment (`None`: removed). Ends a [`begin_loading`].
|
||||
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
|
||||
let mut entries = entries();
|
||||
let changes = Arc::new(changes);
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => {
|
||||
entry.changes = changes;
|
||||
match entries.iter_mut().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv = changes;
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
|
||||
None if !changes.is_empty() => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.direnv = changes;
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
|
||||
pub fn settle(root: &Path) {
|
||||
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
|
||||
entry.loading = false;
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
entries[idx].loading = false;
|
||||
if entries[idx].is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// `root` has no environment of its own any more (closed, or not trusted).
|
||||
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
|
||||
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
|
||||
pub fn remove(root: &Path) {
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv.clear();
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
|
||||
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
|
||||
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
let token = token.filter(|t| !t.is_empty());
|
||||
let mut entries = entries();
|
||||
match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
if entries[idx].github_token == token {
|
||||
return false;
|
||||
}
|
||||
let entry = &mut entries[idx];
|
||||
entry.github_token = token;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let Some(token) = token else { return false };
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.github_token = Some(token);
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
|
||||
pub fn github_token(dir: &Path) -> Option<OsString> {
|
||||
find(&entries(), dir).and_then(|e| e.github_token.clone())
|
||||
}
|
||||
|
||||
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
|
||||
pub fn remove_all(root: &Path) {
|
||||
entries().retain(|e| e.root != root);
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
@@ -135,4 +226,26 @@ mod tests {
|
||||
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
|
||||
remove(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
|
||||
let root = Path::new("/openidea-test-env/gh-project");
|
||||
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
|
||||
assert!(set_github_token(root, Some("gho_work".into())));
|
||||
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
|
||||
assert!(set_github_token(worktrees, Some("gho_work".into())));
|
||||
remove(root); // no `.envrc` in `root`
|
||||
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
|
||||
|
||||
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
|
||||
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
|
||||
remove_all(root);
|
||||
remove_all(worktrees);
|
||||
assert!(for_dir(root).is_empty());
|
||||
assert!(for_dir(worktrees).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,20 @@ pub struct AgentSettings {
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// Chat text follows the interface font (Appearance › Use custom font).
|
||||
pub chat_use_ui_font: bool,
|
||||
/// Chat text family when it does not follow the interface font.
|
||||
pub chat_font_family: String,
|
||||
/// Covers characters the chat font lacks.
|
||||
pub chat_font_fallback: String,
|
||||
pub chat_font_size: u32,
|
||||
/// Code in chat follows the built-in code font.
|
||||
pub code_use_default_font: bool,
|
||||
/// Code family when it does not follow the built-in code font.
|
||||
pub code_font_family: String,
|
||||
/// Covers characters the code font lacks.
|
||||
pub code_font_fallback: String,
|
||||
pub code_font_size: u32,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -145,6 +159,14 @@ impl Default for AgentSettings {
|
||||
show_cost: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
chat_use_ui_font: true,
|
||||
chat_font_family: "Inter".into(),
|
||||
chat_font_fallback: String::new(),
|
||||
chat_font_size: 13,
|
||||
code_use_default_font: true,
|
||||
code_font_family: "JetBrains Mono".into(),
|
||||
code_font_fallback: String::new(),
|
||||
code_font_size: 13,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
@@ -1426,6 +1448,15 @@ pub struct PythonSettings {
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
|
||||
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
|
||||
pub profiler: String,
|
||||
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
|
||||
/// unless the run sets it); off: matplotlib's own window.
|
||||
pub show_plots_in_tool_window: bool,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1438,6 +1469,9 @@ impl Default for PythonSettings {
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
profiler: "auto".into(),
|
||||
show_plots_in_tool_window: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,17 @@ pub struct VcsSettings {
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GithubSettings {
|
||||
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
|
||||
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
|
||||
pub account: String,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-coverage"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo XML)"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Cobertura XML reports (`coverage xml` of coverage.py, and many other tools):
|
||||
//!
|
||||
//! ```xml
|
||||
//! <coverage>
|
||||
//! <sources><source>/home/runner/work/app/app</source></sources>
|
||||
//! <packages><package name="calc"><classes>
|
||||
//! <class filename="src/calc/__init__.py">
|
||||
//! <methods/>
|
||||
//! <lines>
|
||||
//! <line number="2" hits="1" branch="true" condition-coverage="50% (1/2)"/>
|
||||
//! ```
|
||||
//!
|
||||
//! A relative `filename` belongs to the first `<source>` it exists under, else to the
|
||||
//! first `<source>` (whose path may be another machine's; the importer relocates it).
|
||||
//! Lines repeated under `<methods>` are skipped so their hits don't count twice.
|
||||
|
||||
use crate::Accumulator;
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::{Reader, XmlVersion};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn attr(e: &BytesStart, name: &str) -> Option<String> {
|
||||
e.attributes()
|
||||
.flatten()
|
||||
.find(|a| a.key.as_ref() == name)
|
||||
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok())
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
/// `"50% (1/2)"` → `(1, 2)`.
|
||||
fn conditions(text: &str) -> Option<(u32, u32)> {
|
||||
let (_, rest) = text.split_once('(')?;
|
||||
let (covered, total) = rest.trim_end_matches(')').split_once('/')?;
|
||||
Some((covered.trim().parse().ok()?, total.trim().parse().ok()?))
|
||||
}
|
||||
|
||||
/// `sources` pairs each `<source>` with whether it exists here (asked once: another
|
||||
/// machine's `/home/…` is slow to look up on macOS).
|
||||
fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf {
|
||||
let p = Path::new(filename);
|
||||
if p.has_root() {
|
||||
return p.to_path_buf();
|
||||
}
|
||||
sources
|
||||
.iter()
|
||||
.filter(|(_, here)| *here)
|
||||
.map(|(s, _)| s.join(p))
|
||||
.find(|c| c.is_file())
|
||||
.unwrap_or_else(|| sources.first().map_or_else(|| base.join(p), |(s, _)| s.join(p)))
|
||||
}
|
||||
|
||||
/// Relative sources (and filenames without sources) resolve against `base`.
|
||||
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut acc = Accumulator::default();
|
||||
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
|
||||
let mut source: Option<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
let mut in_methods = false;
|
||||
loop {
|
||||
match reader.read_event()? {
|
||||
Event::Start(e) if e.name().as_ref() == "methods" => in_methods = true,
|
||||
Event::Start(e) | Event::Empty(e) => match e.name().as_ref() {
|
||||
"source" => source = Some(String::new()),
|
||||
"class" => {
|
||||
let path = resolve(&attr(&e, "filename").unwrap_or_default(), &sources, base);
|
||||
acc.file(&path);
|
||||
file = Some(path);
|
||||
}
|
||||
"line" if !in_methods => {
|
||||
let Some(path) = &file else { continue };
|
||||
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let line = number.saturating_sub(1);
|
||||
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
|
||||
if attr(&e, "branch").as_deref() == Some("true")
|
||||
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
|
||||
{
|
||||
acc.has_branches = true;
|
||||
for i in 0..total {
|
||||
acc.branch(path, line, i.to_string(), i < covered);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Text(t) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push_str(t.as_ref());
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(r) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push('&');
|
||||
s.push_str(r.as_ref());
|
||||
s.push(';');
|
||||
}
|
||||
}
|
||||
Event::End(e) => match e.name().as_ref() {
|
||||
"source" => {
|
||||
let raw = source.take().unwrap_or_default();
|
||||
let text = quick_xml::escape::unescape(raw.trim()).map(|t| t.into_owned()).unwrap_or(raw);
|
||||
if !text.is_empty() {
|
||||
let path = Path::new(&text);
|
||||
// Joining a drive-less foreign root on Windows would add the checkout's drive.
|
||||
let dir = if path.has_root() { path.to_path_buf() } else { base.join(path) };
|
||||
let here = dir.is_dir();
|
||||
sources.push((dir, here));
|
||||
}
|
||||
}
|
||||
"methods" => in_methods = false,
|
||||
"class" => file = None,
|
||||
_ => {}
|
||||
},
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_lines_branches_and_skips_method_lines() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let second = tmp.path().join("b&c");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
std::fs::write(second.join("m.py"), "").unwrap();
|
||||
let xml = format!(
|
||||
r#"<?xml version="1.0" ?>
|
||||
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
|
||||
<coverage><sources><source>/elsewhere/a</source><source>{}</source></sources>
|
||||
<packages><package name="p"><classes>
|
||||
<class name="m" filename="m.py">
|
||||
<methods><method name="f"><lines><line number="2" hits="5"/></lines></method></methods>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="5" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
<class name="n" filename="n.py"><lines><line number="1" hits="0"/></lines></class>
|
||||
<class name="abs" filename="/abs/x.py"><lines><line number="7" hits="2"/></lines></class>
|
||||
</classes></package></packages></coverage>"#,
|
||||
tmp.path().join("b&c").display()
|
||||
);
|
||||
let suite = parse(&xml, tmp.path()).unwrap().finish("Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
assert_eq!(suite.files.len(), 3);
|
||||
let file = |path: &Path| suite.files.iter().find(|f| f.path.as_ref() as &Path == path).unwrap();
|
||||
// `m.py` exists under the second source; `n.py` falls back to the first.
|
||||
let m = file(&second.join("m.py"));
|
||||
assert_eq!(file(Path::new("/elsewhere/a/n.py")).lines[0].hits, 0);
|
||||
assert_eq!(
|
||||
m.lines.iter().map(|l| (l.line, l.hits, l.branches_total, l.branches_covered)).collect::<Vec<_>>(),
|
||||
[(0, 1, 0, 0), (1, 5, 2, 1), (2, 0, 0, 0)]
|
||||
);
|
||||
assert!(m.lines[1].partial());
|
||||
assert_eq!(file(Path::new("/abs/x.py")).lines[0].line, 6);
|
||||
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filenames_without_sources_resolve_against_the_base() {
|
||||
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
|
||||
let suite = parse(xml, Path::new("/root")).unwrap().finish("Cobertura");
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, Path::new("/root/a/b.py"));
|
||||
assert!(!suite.has_branches);
|
||||
assert_eq!(conditions("100% (4/4)"), Some((4, 4)));
|
||||
assert_eq!(conditions("100%"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of
|
||||
//! executed lines and arcs. Which lines are statements, excluded or branches only comes from
|
||||
//! analysing the source, so coverage.py in the project's interpreter combines the data into a
|
||||
//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML.
|
||||
|
||||
use crate::{CoverageSuite, cobertura};
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::ffi::OsStr;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const COVERAGE_PY: CliTool = CliTool::new("coverage.py", Decoding::ToolOutput);
|
||||
/// Analysing a large project's sources takes a while; a `[run] plugins` that hangs must not
|
||||
/// block the import for good.
|
||||
const TIMEOUT: Duration = Duration::from_secs(600);
|
||||
/// Files of the combined data (`relative_files` keeps them relative to the directory it ran in).
|
||||
const MEASURED: &str = "import sys, json, coverage\n\
|
||||
d = coverage.CoverageData(sys.argv[1]); d.read(); print(json.dumps(sorted(d.measured_files())))";
|
||||
/// The files coverage.py reads its configuration from, in the directory it runs in.
|
||||
const CONFIG_FILES: [&str; 4] = [".coveragerc", "setup.cfg", "tox.ini", "pyproject.toml"];
|
||||
|
||||
/// Whether `path` is an SQLite database (coverage.py 5+ data).
|
||||
pub fn is_data_file(path: &Path) -> bool {
|
||||
let mut head = [0u8; 16];
|
||||
std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"
|
||||
}
|
||||
|
||||
/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's.
|
||||
fn inputs(path: &Path) -> Vec<PathBuf> {
|
||||
let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage."));
|
||||
let mut files: Vec<PathBuf> = match (parallel, path.parent()) {
|
||||
(true, Some(dir)) => std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if files.is_empty() {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// Where coverage.py ran: the nearest directory of `path` inside `root` with a coverage.py
|
||||
/// configuration file (a monorepo's `backend/pyproject.toml`), else `root`.
|
||||
fn run_dir(path: &Path, root: &Path) -> PathBuf {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find(|d| CONFIG_FILES.iter().any(|f| d.join(f).is_file()))
|
||||
.unwrap_or(root)
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
/// Runs `python -W ignore <args>` in `dir` and returns its stdout. Python warnings are
|
||||
/// ignored so `PYTHONWARNINGS=error` can't turn coverage.py's warnings into failures.
|
||||
fn python(python: &Path, dir: &Path, args: &[&OsStr]) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(python);
|
||||
cmd.current_dir(dir).args(["-W", "ignore"]).args(args);
|
||||
let out = COVERAGE_PY.run(cmd, TIMEOUT, None)?;
|
||||
if out.success {
|
||||
return Ok(out.stdout);
|
||||
}
|
||||
let text = if out.stderr.trim().is_empty() { out.stdout } else { out.stderr };
|
||||
let text = text.trim();
|
||||
if text.contains("No module named coverage") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
if text.contains("no such option") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py 6.3 or later in the project's interpreter ({}): {text}",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
Err(IdeError::invalid(format!("coverage.py could not read the data: {text}")))
|
||||
}
|
||||
|
||||
/// Reads the data file at `path` with `python`'s coverage.py, run where the project's coverage.py
|
||||
/// configuration is; `out` holds the scratch files. Blocking.
|
||||
pub(crate) fn import(path: &Path, root: &Path, python_path: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
let dir = run_dir(path, root);
|
||||
let data = out.join(".coverage");
|
||||
let xml = out.join("coverage.xml");
|
||||
let coverage = |args: &[&OsStr]| {
|
||||
let mut all: Vec<&OsStr> = vec!["-m".as_ref(), "coverage".as_ref()];
|
||||
all.extend(args);
|
||||
python(python_path, &dir, &all)
|
||||
};
|
||||
let inputs = inputs(path);
|
||||
let mut args: Vec<&OsStr> = vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()];
|
||||
args.extend(inputs.iter().map(|p| p.as_os_str()));
|
||||
coverage(&args)?;
|
||||
// `-i`: report what has source here instead of failing on the first file that has none.
|
||||
// `--fail-under=0`: a `[report] fail_under` the data misses must not fail the import.
|
||||
coverage(&[
|
||||
"xml".as_ref(),
|
||||
"-i".as_ref(),
|
||||
"--fail-under=0".as_ref(),
|
||||
"--data-file".as_ref(),
|
||||
data.as_ref(),
|
||||
"-o".as_ref(),
|
||||
xml.as_ref(),
|
||||
])?;
|
||||
let text = std::fs::read_to_string(&xml)?;
|
||||
let mut acc = cobertura::parse(&text, &dir).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
|
||||
// The files the report left out (no source here): listed without lines.
|
||||
let measured = python(python_path, &dir, &["-c".as_ref(), MEASURED.as_ref(), data.as_ref()])?;
|
||||
let measured: Vec<PathBuf> = serde_json::from_str(measured.trim())
|
||||
.map_err(|e| IdeError::invalid(format!("coverage.py listed the measured files unreadably: {e}")))?;
|
||||
for file in measured {
|
||||
acc.file(&dir.join(file));
|
||||
}
|
||||
Ok(acc.finish("coverage.py"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_the_files_of_a_parallel_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let db = |name: &str| {
|
||||
let p = tmp.path().join(name);
|
||||
std::fs::write(&p, b"SQLite format 3\0rest").unwrap();
|
||||
p
|
||||
};
|
||||
let a = db(".coverage.host.1.x");
|
||||
let b = db(".coverage.host.2.y");
|
||||
let single = db(".coverage");
|
||||
std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap();
|
||||
std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap();
|
||||
assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc")));
|
||||
assert_eq!(inputs(&a), [a.clone(), b]);
|
||||
assert_eq!(inputs(&single), [single]);
|
||||
}
|
||||
|
||||
/// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`.
|
||||
/// Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn combines_parallel_data_with_the_projects_paths() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`).
|
||||
let base = tmp.path().canonicalize().unwrap();
|
||||
let ci = base.join("ci/app");
|
||||
let root = base.join("project");
|
||||
let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n";
|
||||
for dir in [&ci, &root] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("calc.py"), calc).unwrap();
|
||||
}
|
||||
std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap();
|
||||
std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap();
|
||||
std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap();
|
||||
for script in ["neg.py", "pos.py"] {
|
||||
let ok = Command::new("python3")
|
||||
.current_dir(&ci)
|
||||
.args(["-m", "coverage", "run", "--branch", "--parallel-mode", script])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(ok.success());
|
||||
}
|
||||
let data = root.join("data");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
for e in std::fs::read_dir(&ci).unwrap().flatten() {
|
||||
if e.file_name().to_string_lossy().starts_with(".coverage.") {
|
||||
std::fs::rename(e.path(), data.join(e.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&ci).unwrap();
|
||||
std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap();
|
||||
let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path();
|
||||
let out = base.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&first, &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap();
|
||||
// Both runs together take both branches of line 2.
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2));
|
||||
// The scripts and `gone.py` have no source in the project: listed without lines.
|
||||
let empty: Vec<&str> = suite
|
||||
.files
|
||||
.iter()
|
||||
.filter(|f| f.lines.is_empty())
|
||||
.filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str())
|
||||
.collect();
|
||||
assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]);
|
||||
// They keep the recorded path, so the import notification counts them as not in the project.
|
||||
assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci)));
|
||||
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_where_the_coverage_configuration_is() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join("backend/reports")).unwrap();
|
||||
std::fs::create_dir_all(root.join("data")).unwrap();
|
||||
std::fs::write(root.join("backend/pyproject.toml"), "").unwrap();
|
||||
assert_eq!(run_dir(&root.join("backend/reports/.coverage"), root), root.join("backend"));
|
||||
assert_eq!(run_dir(&root.join("data/.coverage"), root), root);
|
||||
// A data file outside the project runs in the project.
|
||||
assert_eq!(run_dir(Path::new("/elsewhere/.coverage"), root), root);
|
||||
}
|
||||
|
||||
/// A stand-in interpreter that prints `stderr` and exits with `code`.
|
||||
#[cfg(unix)]
|
||||
fn fake_python(dir: &Path, stderr: &str, code: i32) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let p = dir.join("python");
|
||||
std::fs::write(&p, format!("#!/bin/sh\necho '{stderr}' >&2\nexit {code}\n")).unwrap();
|
||||
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn reports_why_coverage_py_failed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let data = tmp.path().join(".coverage");
|
||||
let err = |stderr: &str| {
|
||||
let python = fake_python(tmp.path(), stderr, 1);
|
||||
import(&data, tmp.path(), &python, tmp.path()).unwrap_err().to_string()
|
||||
};
|
||||
assert!(err("No module named coverage").contains("needs coverage.py in the project's interpreter"));
|
||||
assert!(err("no such option: --data-file").contains("needs coverage.py 6.3 or later"));
|
||||
assert!(err("No usable data files").contains("coverage.py could not read the data: No usable data files"));
|
||||
}
|
||||
|
||||
/// A monorepo member's data recorded with `relative_files`, below its `fail_under`, with
|
||||
/// coverage.py's warnings turned off. Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn reads_a_members_relative_data_below_fail_under() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let member = root.join("backend");
|
||||
std::fs::create_dir_all(member.join("app")).unwrap();
|
||||
std::fs::write(
|
||||
member.join("pyproject.toml"),
|
||||
"[tool.coverage.run]\nrelative_files = true\nbranch = true\ndisable_warnings = [\"couldnt-parse\"]\n\
|
||||
[tool.coverage.report]\nfail_under = 90\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(member.join("app/x.py"), "def f(n):\n if n:\n return 1\n return 2\n").unwrap();
|
||||
std::fs::write(member.join("t.py"), "from app import x\nx.f(1)\n").unwrap();
|
||||
let ok = Command::new("python3").current_dir(&member).args(["-m", "coverage", "run", "t.py"]).status().unwrap();
|
||||
assert!(ok.success());
|
||||
std::fs::remove_file(member.join("t.py")).unwrap();
|
||||
let out = root.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&member.join(".coverage"), &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let x = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("app/x.py")).unwrap();
|
||||
assert_eq!((x.lines_total, x.lines_covered, x.branches_total, x.branches_covered), (4, 3, 2, 1));
|
||||
// `t.py` has no source any more and its warning is off: still listed, without lines.
|
||||
let t = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("t.py")).unwrap();
|
||||
assert!(t.lines.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
//! "Import a report collected in CI from disk": the format is sniffed from the
|
||||
//! content (lcov, Go cover profile, JaCoCo XML, SimpleCov resultset) and paths recorded on another
|
||||
//! content (lcov, Go cover profile, JaCoCo or Cobertura XML, SimpleCov resultset) and paths recorded on another
|
||||
//! machine are mapped into the project by their longest existing suffix.
|
||||
|
||||
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov, simplecov};
|
||||
use crate::{Accumulator, CoverageSuite, cobertura, goprofile, jacoco, lcov, simplecov};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -11,13 +12,19 @@ pub(crate) enum Format {
|
||||
Lcov,
|
||||
GoProfile,
|
||||
Jacoco,
|
||||
Cobertura,
|
||||
SimpleCov,
|
||||
}
|
||||
|
||||
pub(crate) fn detect(text: &str) -> Option<Format> {
|
||||
let head = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if head.starts_with('<') {
|
||||
return head.contains("<report").then_some(Format::Jacoco);
|
||||
// The root element, after any prolog or DOCTYPE naming it.
|
||||
return match (head.find("<report"), head.find("<coverage")) {
|
||||
(Some(r), c) if c.is_none_or(|c| r < c) => Some(Format::Jacoco),
|
||||
(_, Some(_)) => Some(Format::Cobertura),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if head.starts_with('{') {
|
||||
return head.contains("\"coverage\"").then_some(Format::SimpleCov);
|
||||
@@ -39,6 +46,9 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
let (module, module_dir) = go_module_for(root, &text);
|
||||
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
|
||||
}
|
||||
Some(Format::Cobertura) => cobertura::parse(&text, root)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?
|
||||
.finish("Cobertura"),
|
||||
Some(Format::Jacoco) => {
|
||||
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
|
||||
let module = jacoco::module_dir(path);
|
||||
@@ -53,18 +63,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
acc.finish("JaCoCo")
|
||||
}
|
||||
None if text.starts_with("!coverage.py: This is a private format") => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is coverage.py 4 data, which current coverage.py can't read. Import the output of `coverage xml` instead.",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
None => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo XML report or SimpleCov resultset",
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo or Cobertura XML report or SimpleCov resultset",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dirs = HashMap::new();
|
||||
for f in &mut suite.files {
|
||||
let p: &Path = f.path.as_ref();
|
||||
if !p.exists()
|
||||
&& let Some(found) = relocate(p, root)
|
||||
{
|
||||
let present = p.parent().is_none_or(|d| dir_exists(d, &mut dirs)) && p.exists();
|
||||
if !present && let Some(found) = relocate(p, root) {
|
||||
f.path = found.into();
|
||||
}
|
||||
}
|
||||
@@ -72,6 +88,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
Ok(suite)
|
||||
}
|
||||
|
||||
/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`,
|
||||
/// run in `root`; `out` is an empty scratch directory. Blocking.
|
||||
pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
crate::coveragepy::import(path, root, python, out)
|
||||
}
|
||||
|
||||
/// Whether `dir` exists, without asking again below a directory known to be missing: every
|
||||
/// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports
|
||||
/// (`/home/runner/work/…`) name thousands of files there.
|
||||
fn dir_exists(dir: &Path, known: &mut HashMap<PathBuf, bool>) -> bool {
|
||||
if let Some(&e) = known.get(dir) {
|
||||
return e;
|
||||
}
|
||||
let e = dir.parent().is_none_or(|p| dir_exists(p, known)) && dir.is_dir();
|
||||
known.insert(dir.to_path_buf(), e);
|
||||
e
|
||||
}
|
||||
|
||||
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
|
||||
/// `path` that exists under `root`.
|
||||
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
|
||||
@@ -129,12 +163,30 @@ mod tests {
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
|
||||
Some(Format::Jacoco)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), Some(Format::Cobertura));
|
||||
assert_eq!(
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE coverage SYSTEM \"x.dtd\"><coverage/>"),
|
||||
Some(Format::Cobertura)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><html/>"), None);
|
||||
assert_eq!(detect("{\"RSpec\": {\"coverage\": {}}}"), Some(Format::SimpleCov));
|
||||
assert_eq!(detect("{\"name\": \"package.json\"}"), None);
|
||||
assert_eq!(detect("hello"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_directories_are_looked_up_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut known = HashMap::new();
|
||||
assert!(dir_exists(tmp.path(), &mut known));
|
||||
let gone = tmp.path().join("gone");
|
||||
assert!(!dir_exists(&gone.join("a/b"), &mut known));
|
||||
std::fs::create_dir_all(gone.join("a/c")).unwrap();
|
||||
// Known to be missing, so its subdirectories are not looked up.
|
||||
assert!(!dir_exists(&gone.join("a/c"), &mut known));
|
||||
assert_eq!(known.get(&gone), Some(&false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_ci_simplecov_with_foreign_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -168,8 +220,75 @@ mod tests {
|
||||
assert!(import(&tmp.path().join("missing"), &root).is_err());
|
||||
std::fs::write(&report, "nothing").unwrap();
|
||||
assert!(import(&report, &root).is_err());
|
||||
std::fs::write(&report, "!coverage.py: This is a private format, don't read it directly!{\"lines\":{}}")
|
||||
.unwrap();
|
||||
assert!(import(&report, &root).unwrap_err().to_string().contains("coverage.py 4 data"));
|
||||
}
|
||||
|
||||
/// `coverage xml` (coverage.py 7.17, `--branch`) of a project checked out on a CI runner.
|
||||
#[test]
|
||||
fn imports_coverage_py_xml_with_foreign_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
std::fs::create_dir_all(root.join("src/calc")).unwrap();
|
||||
std::fs::write(root.join("src/calc/__init__.py"), "").unwrap();
|
||||
let report = tmp.path().join("coverage.xml");
|
||||
std::fs::write(&report, COVERAGE_PY_XML).unwrap();
|
||||
let suite = import(&report, &root).unwrap();
|
||||
assert_eq!(suite.runner, "Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("src/calc/__init__.py")).unwrap();
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (8, 5, 4, 2));
|
||||
assert_eq!(calc.lines.iter().filter(|l| l.partial()).map(|l| l.line).collect::<Vec<_>>(), [1, 3]);
|
||||
// The test file is not in this checkout: it keeps the runner's path.
|
||||
assert!(
|
||||
suite.files.iter().any(|f| f.path.as_ref() as &Path == Path::new("/home/runner/work/app/app/test_calc.py"))
|
||||
);
|
||||
}
|
||||
|
||||
const COVERAGE_PY_XML: &str = r#"<?xml version="1.0" ?>
|
||||
<coverage version="7.17.5" timestamp="1795754882920" lines-valid="13" lines-covered="10" line-rate="0.7692" branches-valid="4" branches-covered="2" branch-rate="0.5" complexity="0">
|
||||
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.17.5 -->
|
||||
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
|
||||
<sources>
|
||||
<source>/home/runner/work/app/app</source>
|
||||
</sources>
|
||||
<packages>
|
||||
<package name="." line-rate="1" branch-rate="1" complexity="0">
|
||||
<classes>
|
||||
<class name="test_calc.py" filename="test_calc.py" complexity="0" line-rate="1" branch-rate="1">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1"/>
|
||||
<line number="3" hits="1"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="7" hits="1"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
<package name="src.calc" line-rate="0.625" branch-rate="0.5" complexity="0">
|
||||
<classes>
|
||||
<class name="__init__.py" filename="src/calc/__init__.py" complexity="0" line-rate="0.625" branch-rate="0.5">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="5"/>
|
||||
<line number="5" hits="0"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="13" hits="1"/>
|
||||
<line number="14" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
</packages>
|
||||
</coverage>
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn imports_go_profiles_of_nested_modules() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod cobertura;
|
||||
mod coveragepy;
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
@@ -23,7 +25,8 @@ mod lcov;
|
||||
mod plan;
|
||||
mod simplecov;
|
||||
|
||||
pub use import::import;
|
||||
pub use coveragepy::is_data_file;
|
||||
pub use import::{import, import_data};
|
||||
pub use plan::prepare;
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
|
||||
@@ -326,7 +326,8 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
|
||||
argv.extend(py.target.iter().cloned());
|
||||
let report = CoverageReportSpec::Exported {
|
||||
runner: s("coverage.py"),
|
||||
argv: with(&["-m", "coverage", "lcov", "-o", &path(&lcov)]),
|
||||
// `--fail-under=0`: a `[report] fail_under` the run misses must not lose its report.
|
||||
argv: with(&["-m", "coverage", "lcov", "--fail-under=0", "-o", &path(&lcov)]),
|
||||
cwd: dir.to_path_buf().into(),
|
||||
env: config.env.clone(),
|
||||
lcov: lcov.into(),
|
||||
|
||||
@@ -859,6 +859,21 @@ async fn connect_with_retries(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
|
||||
/// language (a template one) declares debugpy before Python.
|
||||
#[test]
|
||||
fn debugpy_comes_from_the_python_language() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let python = include_str!("../../../languages/python.toml").replace(
|
||||
"args = [\"-m\", \"debugpy.adapter\"]",
|
||||
"args = [\"-X\", \"frozen_modules=off\", \"-m\", \"debugpy.adapter\"]",
|
||||
);
|
||||
assert!(python.contains("frozen_modules"));
|
||||
std::fs::write(dir.path().join("python.toml"), python).unwrap();
|
||||
let languages = LanguageRegistry::load(Some(dir.path())).unwrap();
|
||||
assert_eq!(find_config(&languages, "debugpy").unwrap().args[0], "-X");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_run_on_the_tool_search_path() {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Python Debug Server (`attach` with `listen`): the program connects with its own debugpy,
|
||||
//! which may differ from the IDE's adapter. Nothing in the protocol compares them.
|
||||
|
||||
use crate::session::Session;
|
||||
use ide_core::IdeError;
|
||||
use ide_core::event::DebugEvent;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
|
||||
adapter == "debugpy" && request == "attach" && arguments.get("listen").is_some()
|
||||
}
|
||||
|
||||
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
|
||||
/// which would wait for the program forever: find out before starting it. Listening again right
|
||||
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
|
||||
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
|
||||
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
|
||||
const RELEASE: Duration = Duration::from_secs(5);
|
||||
let listen = &arguments["listen"];
|
||||
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
|
||||
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
|
||||
let deadline = tokio::time::Instant::now() + RELEASE;
|
||||
loop {
|
||||
match std::net::TcpListener::bind((host, port)) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
|
||||
/// Evaluated in the stopped frame as a hover: without a frame, debugpy before 1.8 runs the
|
||||
/// expression as a statement and prints its value into the program's output.
|
||||
pub(crate) async fn check_version(s: Arc<Session>, thread: i64) {
|
||||
const WAIT: Duration = Duration::from_secs(5);
|
||||
let request = |command: &'static str, arguments: Value| s.conn.request_timeout(command, arguments, WAIT);
|
||||
let Ok(info) = request("debugpySystemInfo", json!({})).await else { return };
|
||||
let Some(ide) = info.pointer("/debugpy/version").and_then(Value::as_str) else { return };
|
||||
let Ok(trace) = request("stackTrace", json!({ "threadId": thread, "levels": 1 })).await else { return };
|
||||
let Some(frame) = trace.pointer("/stackFrames/0/id").and_then(Value::as_i64) else { return };
|
||||
let expression = json!({ "expression": "__import__('debugpy').__version__", "frameId": frame, "context": "hover" });
|
||||
let Ok(reply) = request("evaluate", expression).await else { return };
|
||||
let Some(program) = reply.get("result").and_then(Value::as_str) else { return };
|
||||
if let Some(warning) = version_warning(ide, program) {
|
||||
s.emit(DebugEvent::Output { category: "console".into(), output: warning });
|
||||
}
|
||||
}
|
||||
|
||||
fn version_warning(ide: &str, program: &str) -> Option<String> {
|
||||
let program = program.trim_matches(|c| c == '\'' || c == '"');
|
||||
(program != ide).then(|| {
|
||||
format!(
|
||||
"The program uses debugpy {program}, the IDE's debugger debugpy {ide}. If breakpoints or stepping \
|
||||
misbehave, install the same version where the program runs: pip install debugpy=={ide}\n"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warns_only_when_versions_differ() {
|
||||
assert_eq!(version_warning("1.8.22", "'1.8.22'"), None);
|
||||
assert_eq!(version_warning("1.8.22", "1.8.22"), None);
|
||||
let w = version_warning("1.8.22", "'1.8.0'").unwrap();
|
||||
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_taken_port_is_reported_before_the_adapter_starts() {
|
||||
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = taken.local_addr().unwrap().port();
|
||||
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
|
||||
let e = require_free_port(&listen).await.unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
|
||||
drop(taken);
|
||||
assert!(require_free_port(&listen).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_address_the_machine_lacks_is_reported_at_once() {
|
||||
// 192.0.2.0/24 is reserved for documentation, never a local address.
|
||||
let started = std::time::Instant::now();
|
||||
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
|
||||
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_the_previous_adapter_to_release_the_port() {
|
||||
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = previous.local_addr().unwrap().port();
|
||||
let released = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
drop(previous);
|
||||
});
|
||||
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
|
||||
released.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_debugpy_listen_attaches_check() {
|
||||
assert!(listens("debugpy", "attach", &json!({"listen": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "attach", &json!({"connect": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "launch", &json!({"listen": {}})));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod adapter;
|
||||
pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod debugpy;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
@@ -901,6 +902,9 @@ impl DebugManager {
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let mut arguments = launch_arguments(&config)?;
|
||||
if debugpy::listens(&config.adapter, &config.request, &arguments) {
|
||||
debugpy::require_free_port(&arguments).await?;
|
||||
}
|
||||
// An IDE-side marker (never sent to the adapter): the session is a Flutter
|
||||
// one regardless of what the working directory holds.
|
||||
let force_flutter =
|
||||
@@ -1149,6 +1153,9 @@ impl DebugManager {
|
||||
});
|
||||
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
|
||||
|
||||
if debugpy::listens(&session.adapter, &session.request, &arguments) {
|
||||
session.debugpy_version_unchecked.store(true, Ordering::Release);
|
||||
}
|
||||
let configured = tokio::select! {
|
||||
biased;
|
||||
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
|
||||
@@ -75,6 +75,8 @@ pub(crate) struct Session {
|
||||
pub jdwp_port: std::sync::OnceLock<u16>,
|
||||
/// The attach goes through the listen-mode relay of [`crate::jdwp::listen_for_jvm`].
|
||||
pub listen_relay: AtomicBool,
|
||||
/// A Python Debug Server session whose program's debugpy version is checked on its first stop.
|
||||
pub(crate) debugpy_version_unchecked: AtomicBool,
|
||||
pub suspended: Suspension,
|
||||
/// Pids signalled for the current stop: the reported pid and everything it started (an
|
||||
/// adapter may report the launcher shell, whose child is the program).
|
||||
@@ -316,6 +318,7 @@ impl Session {
|
||||
jvm_pid: AtomicI64::new(0),
|
||||
jdwp_port: std::sync::OnceLock::new(),
|
||||
listen_relay: AtomicBool::new(false),
|
||||
debugpy_version_unchecked: AtomicBool::new(false),
|
||||
suspended: Suspension::default(),
|
||||
stop_pids: parking_lot::Mutex::new(Vec::new()),
|
||||
#[cfg(windows)]
|
||||
@@ -854,6 +857,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
});
|
||||
if let Some(thread) = int("threadId")
|
||||
&& s.debugpy_version_unchecked.swap(false, Ordering::AcqRel)
|
||||
{
|
||||
tokio::spawn(crate::debugpy::check_version(s.clone(), thread));
|
||||
}
|
||||
}
|
||||
"continued" => {
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
|
||||
|
||||
@@ -127,7 +127,10 @@ mod tests {
|
||||
fn schema(name: &str, tables: &[&str]) -> CatalogSchema {
|
||||
CatalogSchema {
|
||||
name: name.into(),
|
||||
tables: tables.iter().map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table }).collect(),
|
||||
tables: tables
|
||||
.iter()
|
||||
.map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table, comment: None })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -655,7 +655,7 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default, comment) by table.
|
||||
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
|
||||
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
|
||||
for row in rows {
|
||||
@@ -664,12 +664,15 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
|
||||
let data_type = it.next().flatten().unwrap_or_default();
|
||||
let nullable = it.next().flatten().as_deref() != Some("0");
|
||||
let has_default = it.next().flatten().is_some();
|
||||
// Bridges built before the comment column send five fields.
|
||||
let comment = it.next().flatten().filter(|c| !c.trim().is_empty());
|
||||
by_table.entry(table).or_default().push(crate::CompletionColumn {
|
||||
name,
|
||||
data_type,
|
||||
nullable,
|
||||
primary_key: false,
|
||||
has_default,
|
||||
comment,
|
||||
});
|
||||
}
|
||||
by_table
|
||||
@@ -684,16 +687,18 @@ mod tests {
|
||||
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
|
||||
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
|
||||
};
|
||||
let by_table = schema_columns(vec![
|
||||
row("orders", "id", "0", None),
|
||||
row("orders", "note", "1", Some("'none'")),
|
||||
row("items", "sku", "1", None),
|
||||
vec![None, Some("orphan".into())],
|
||||
]);
|
||||
let mut commented = row("orders", "note", "1", Some("'none'"));
|
||||
commented.push(Some("free text".into()));
|
||||
let mut blank = row("items", "sku", "1", None);
|
||||
blank.push(Some(" ".into()));
|
||||
let by_table =
|
||||
schema_columns(vec![row("orders", "id", "0", None), commented, blank, vec![None, Some("orphan".into())]]);
|
||||
let orders = &by_table["orders"];
|
||||
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
|
||||
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
|
||||
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
|
||||
assert_eq!((orders[0].comment.as_deref(), orders[1].comment.as_deref()), (None, Some("free text")));
|
||||
assert_eq!(by_table["items"][0].comment, None);
|
||||
assert_eq!(by_table["items"].len(), 1);
|
||||
assert_eq!(by_table.len(), 2);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ pub use history::HistoryEntry;
|
||||
pub use plan::{PlanNode, PlanProperty};
|
||||
pub use source::{
|
||||
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
@@ -146,6 +146,10 @@ pub struct SchemaObject {
|
||||
pub struct TableInfo {
|
||||
pub name: String,
|
||||
pub kind: DbTableKind,
|
||||
/// The table's or view's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -208,6 +212,10 @@ pub struct CompletionColumn {
|
||||
pub primary_key: bool,
|
||||
/// Has a default (or is generated): optional in INSERT.
|
||||
pub has_default: bool,
|
||||
/// The column's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -568,6 +576,18 @@ impl DbManager {
|
||||
None => {}
|
||||
}
|
||||
source::save(&self.root, &project)?;
|
||||
if let Ok(mut folders) = source::load_folders(&self.root) {
|
||||
let known: std::collections::HashSet<&str> = sources.iter().map(|source| source.id.as_str()).collect();
|
||||
let mut changed = false;
|
||||
for folder in &mut folders {
|
||||
let before = folder.sources.len();
|
||||
folder.sources.retain(|id| known.contains(id.as_str()));
|
||||
changed |= folder.sources.len() != before;
|
||||
}
|
||||
if changed {
|
||||
source::save_folders(&self.root, &folders)?;
|
||||
}
|
||||
}
|
||||
old
|
||||
};
|
||||
for o in old {
|
||||
@@ -1103,7 +1123,11 @@ impl DbManager {
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
let name = it.next().flatten()?;
|
||||
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
|
||||
Some(TableInfo {
|
||||
name,
|
||||
kind: DbTableKind::from_catalog(it.next().flatten().as_deref()),
|
||||
comment: it.next().flatten().filter(|comment| !comment.is_empty()),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -1410,10 +1434,13 @@ impl DbManager {
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
|
||||
let (oid, kind) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind)]) => {
|
||||
(oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?, kind.clone())
|
||||
}
|
||||
let (oid, kind, owner, comment) = match rel.as_deref() {
|
||||
Some([Some(oid), Some(kind), owner, comment]) => (
|
||||
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
|
||||
kind.clone(),
|
||||
owner.clone(),
|
||||
comment.clone(),
|
||||
),
|
||||
_ => return Err(missing()),
|
||||
};
|
||||
if kind == "v" || kind == "m" {
|
||||
@@ -1434,6 +1461,7 @@ impl DbManager {
|
||||
data_type: it.next().flatten().unwrap_or_default(),
|
||||
not_null: flag(&it.next().flatten()),
|
||||
default: it.next().flatten(),
|
||||
comment: it.next().flatten(),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -1447,7 +1475,18 @@ impl DbManager {
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes))
|
||||
let grants = pool
|
||||
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
|
||||
})
|
||||
.collect();
|
||||
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
|
||||
let extras = sql::DdlExtras { comment, owner, grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1495,6 +1534,7 @@ impl DbManager {
|
||||
nullable: flag(&Some(next())),
|
||||
primary_key: flag(&Some(next())),
|
||||
has_default: flag(&Some(next())),
|
||||
comment: Some(next()).filter(|c| !c.trim().is_empty()),
|
||||
};
|
||||
if name.is_empty() || column.name.is_empty() {
|
||||
continue;
|
||||
|
||||
@@ -113,7 +113,11 @@ pub(crate) async fn tables(pool: &SnowflakePool, schema: &str) -> IdeResult<Vec<
|
||||
Ok(shown
|
||||
.records()
|
||||
.filter_map(|r| {
|
||||
Some(TableInfo { name: r.get("name")?.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) })
|
||||
Some(TableInfo {
|
||||
name: r.get("name")?.to_owned(),
|
||||
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
|
||||
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -238,7 +242,11 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
|
||||
let (Some(&index), Some(name)) = (at.get(r.get("schema_name").unwrap_or_default()), r.get("name")) else {
|
||||
continue;
|
||||
};
|
||||
out[index].tables.push(TableInfo { name: name.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) });
|
||||
out[index].tables.push(TableInfo {
|
||||
name: name.to_owned(),
|
||||
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
|
||||
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
|
||||
});
|
||||
}
|
||||
for schema in &mut out {
|
||||
schema.tables.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
@@ -447,6 +455,7 @@ pub(crate) async fn completion(pool: &SnowflakePool) -> IdeResult<Vec<Completion
|
||||
primary_key: false,
|
||||
has_default: r.get("default").is_some_and(|d| !d.is_empty())
|
||||
|| r.get("autoincrement").is_some_and(|a| !a.is_empty()),
|
||||
comment: r.get("comment").filter(|c| !c.trim().is_empty()).map(str::to_owned),
|
||||
});
|
||||
}
|
||||
Ok(tables)
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
//! Data sources: per-project connection settings in `.openidea/data-sources.toml`, and
|
||||
//! global ones (IDEA's Make Global: listed in every project) in `data-sources.toml` of the
|
||||
//! app data directory. Passwords never go there: saved ones live in [`crate::secrets`],
|
||||
//! app data directory. Project folder grouping is in `.openidea/data-source-folders.toml`.
|
||||
//! Passwords never go there: saved ones live in [`crate::secrets`],
|
||||
//! the others only in memory for the session.
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) const FILE: &str = "data-sources.toml";
|
||||
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -697,6 +699,108 @@ fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A user folder grouping data sources in one project's Database tree.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DbSourceFolder {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// Reserved for nested folders; the first UI version only creates root folders.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub parent: Option<String>,
|
||||
pub order: i32,
|
||||
pub sources: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct SourceFoldersFile {
|
||||
#[serde(default = "folders_version")]
|
||||
version: u32,
|
||||
#[serde(default, rename = "folder")]
|
||||
folders: Vec<DbSourceFolder>,
|
||||
}
|
||||
|
||||
fn folders_version() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// The project's data source folders and their members.
|
||||
pub fn load_folders(root: &Path) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
let path = project_dir::path(root, FOLDERS_FILE);
|
||||
let text = match std::fs::read_to_string(&path) {
|
||||
Ok(text) => text,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let file: SourceFoldersFile =
|
||||
toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
if file.version > 1 {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{}: folder format version {} is newer than this OpenIDEA",
|
||||
path.display(),
|
||||
file.version
|
||||
)));
|
||||
}
|
||||
Ok(file.folders)
|
||||
}
|
||||
|
||||
/// Replaces the project's data source folders after validating ids, parents and memberships.
|
||||
pub fn save_folders(root: &Path, folders: &[DbSourceFolder]) -> IdeResult<()> {
|
||||
validate_folders(folders)?;
|
||||
let path = project_dir::path(root, FOLDERS_FILE);
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let file = SourceFoldersFile { version: folders_version(), folders: folders.to_vec() };
|
||||
let text = toml::to_string_pretty(&file).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let tmp = path.with_file_name(format!(".{FOLDERS_FILE}.{}.tmp", uuid::Uuid::new_v4()));
|
||||
std::fs::write(&tmp, text)?;
|
||||
if let Err(e) = std::fs::rename(&tmp, &path) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(e.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_folders(folders: &[DbSourceFolder]) -> IdeResult<()> {
|
||||
let mut ids = HashSet::new();
|
||||
let mut members = HashSet::new();
|
||||
for folder in folders {
|
||||
if folder.id.trim().is_empty() || folder.name.trim().is_empty() {
|
||||
return Err(IdeError::invalid("every data source folder needs an id and a name"));
|
||||
}
|
||||
if !ids.insert(folder.id.as_str()) {
|
||||
return Err(IdeError::invalid(format!("duplicate data source folder id '{}'", folder.id)));
|
||||
}
|
||||
for source in &folder.sources {
|
||||
if source.is_empty() {
|
||||
return Err(IdeError::invalid(format!("folder '{}' has an empty data source id", folder.name)));
|
||||
}
|
||||
if !members.insert(source.as_str()) {
|
||||
return Err(IdeError::invalid(format!("data source '{source}' belongs to more than one folder")));
|
||||
}
|
||||
}
|
||||
}
|
||||
for folder in folders {
|
||||
let mut seen = HashSet::new();
|
||||
let mut parent = folder.parent.as_deref();
|
||||
while let Some(id) = parent {
|
||||
if id == folder.id || !seen.insert(id) {
|
||||
return Err(IdeError::invalid(format!("data source folder '{}' has a parent cycle", folder.name)));
|
||||
}
|
||||
parent =
|
||||
folders.iter().find(|candidate| candidate.id == id).and_then(|candidate| candidate.parent.as_deref());
|
||||
if parent.is_none() && !folders.iter().any(|candidate| candidate.id == id) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"data source folder '{}' has an unknown parent '{id}'",
|
||||
folder.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Credential store access. Blocking (may show an OS prompt): call off the async runtime.
|
||||
/// Keys are data source ids; [`secrets::ssh_key`] names the SSH password / passphrase.
|
||||
#[cfg(test)]
|
||||
@@ -724,6 +828,38 @@ mod tests {
|
||||
assert!(save(tmp.path(), &[DataSource::default()]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_folders_round_trip_and_reject_invalid_memberships() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let folders = vec![
|
||||
DbSourceFolder {
|
||||
id: "prod".into(),
|
||||
name: "Production".into(),
|
||||
parent: None,
|
||||
order: 0,
|
||||
sources: vec!["pg".into(), "mysql".into()],
|
||||
},
|
||||
DbSourceFolder { id: "empty".into(), name: "Empty".into(), parent: None, order: 1, sources: vec![] },
|
||||
];
|
||||
save_folders(tmp.path(), &folders).unwrap();
|
||||
assert_eq!(load_folders(tmp.path()).unwrap(), folders);
|
||||
|
||||
let duplicate = vec![
|
||||
DbSourceFolder { sources: vec!["pg".into()], ..folders[0].clone() },
|
||||
DbSourceFolder { id: "other".into(), sources: vec!["pg".into()], ..folders[1].clone() },
|
||||
];
|
||||
assert!(save_folders(tmp.path(), &duplicate).is_err());
|
||||
|
||||
let cycle = vec![
|
||||
DbSourceFolder { parent: Some("b".into()), ..folders[0].clone() },
|
||||
DbSourceFolder { id: "b".into(), parent: Some("prod".into()), ..folders[1].clone() },
|
||||
];
|
||||
assert!(save_folders(tmp.path(), &cycle).is_err());
|
||||
|
||||
let missing = vec![DbSourceFolder { parent: Some("missing".into()), ..folders[0].clone() }];
|
||||
assert!(save_folders(tmp.path(), &missing).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_configs_written_before_the_new_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
+158
-29
@@ -95,46 +95,52 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
|
||||
/// Rows: `name, kind, comment` where kind is `table`, `view` or `materialized view`.
|
||||
pub fn tables(driver: DbDriver, schema: &str) -> String {
|
||||
match driver {
|
||||
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, CASE engine WHEN 'View' THEN 'view' WHEN 'MaterializedView' THEN 'materialized view' \
|
||||
WHEN 'WindowView' THEN 'view' ELSE 'table' END FROM system.tables \
|
||||
WHEN 'WindowView' THEN 'view' ELSE 'table' END, comment FROM system.tables \
|
||||
WHERE database = {} AND is_temporary = 0 ORDER BY name",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
"SELECT name, type FROM {}.sqlite_master WHERE type IN ('table', 'view') \
|
||||
"SELECT name, type, NULL FROM {}.sqlite_master WHERE type IN ('table', 'view') \
|
||||
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
|
||||
quote_ident(driver, schema)
|
||||
),
|
||||
DbDriver::Snowflake => format!(
|
||||
"SELECT table_name, CASE table_type WHEN 'VIEW' THEN 'view' WHEN 'MATERIALIZED VIEW' THEN 'materialized view' \
|
||||
ELSE 'table' END FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
ELSE 'table' END, comment FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT table_name, 'table' FROM all_tables WHERE owner = {} \
|
||||
UNION ALL SELECT view_name, 'view' FROM all_views WHERE owner = {} ORDER BY 1",
|
||||
quote_literal(driver, schema),
|
||||
"SELECT table_name, CASE WHEN table_type = 'VIEW' THEN 'view' ELSE 'table' END, comments \
|
||||
FROM all_tab_comments WHERE owner = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Postgres => format!(
|
||||
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END \
|
||||
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, \
|
||||
obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
WHERE n.nspname = {} AND c.relkind IN ('r', 'v', 'm', 'p', 'f') ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
CASE WHEN table_type LIKE '%VIEW%' THEN NULL ELSE NULLIF(table_comment, '') END \
|
||||
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
DbDriver::SqlServer => format!(
|
||||
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
|
||||
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
|
||||
"SELECT t.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
CAST(ep.value AS nvarchar(max)) \
|
||||
FROM INFORMATION_SCHEMA.TABLES t \
|
||||
LEFT JOIN sys.extended_properties ep \
|
||||
ON ep.major_id = OBJECT_ID(QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)) \
|
||||
AND ep.minor_id = 0 AND ep.name = 'MS_Description' \
|
||||
WHERE t.TABLE_SCHEMA = {} ORDER BY 1",
|
||||
quote_literal(driver, schema)
|
||||
),
|
||||
}
|
||||
@@ -301,7 +307,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
|
||||
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
|
||||
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1, c.comment \
|
||||
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
|
||||
"c.database",
|
||||
@@ -312,7 +318,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
|
||||
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
|
||||
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END, NULL \
|
||||
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
|
||||
"'main'",
|
||||
@@ -325,7 +331,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
AND a.attnum = ANY(i.indkey)) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN a.atthasdef OR EXISTS (SELECT 1 FROM pg_depend d WHERE d.refclassid = 'pg_class'::regclass \
|
||||
AND d.refobjid = c.oid AND d.refobjsubid = a.attnum AND d.classid = 'pg_class'::regclass \
|
||||
AND d.deptype = 'i') THEN 1 ELSE 0 END \
|
||||
AND d.deptype = 'i') THEN 1 ELSE 0 END, col_description(c.oid, a.attnum) \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
|
||||
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
|
||||
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
|
||||
@@ -336,7 +342,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
DbDriver::Mysql => (
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END, c.column_comment \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
|
||||
@@ -351,7 +357,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
|
||||
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
|
||||
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END, NULL \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
|
||||
@@ -361,7 +367,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
DbDriver::Snowflake => (
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END, c.comment \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
|
||||
@@ -372,8 +378,10 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
|
||||
FROM all_tab_columns c \
|
||||
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
|
||||
AND cc.column_name = c.column_name \
|
||||
LEFT JOIN all_views v ON v.owner = c.owner AND v.view_name = c.table_name \
|
||||
LEFT JOIN (SELECT con.owner, con.table_name, kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
@@ -658,21 +666,22 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `oid, relkind` of a PostgreSQL relation.
|
||||
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
|
||||
pub fn postgres_relation(schema: &str, name: &str) -> String {
|
||||
format!(
|
||||
"SELECT c.oid::text, c.relkind::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
WHERE n.nspname = {} AND c.relname = {}",
|
||||
quote_literal(DbDriver::Postgres, schema),
|
||||
quote_literal(DbDriver::Postgres, name)
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, type, not null (0/1), default` of relation `oid`.
|
||||
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
|
||||
pub fn postgres_ddl_columns(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
|
||||
pg_get_expr(d.adbin, d.adrelid) FROM pg_attribute a \
|
||||
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
|
||||
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
|
||||
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
|
||||
)
|
||||
@@ -695,6 +704,27 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), grantable (0/1) of
|
||||
/// the privileges relation `oid` grants beyond its owner's. A relation whose ACL was never
|
||||
/// changed (`relacl` null) grants none.
|
||||
pub fn postgres_ddl_grants(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
|
||||
string_agg(lower(a.privilege_type), ', ' ORDER BY a.privilege_type), \
|
||||
CASE WHEN a.is_grantable THEN 1 ELSE 0 END \
|
||||
FROM pg_class c CROSS JOIN LATERAL aclexplode(c.relacl) a \
|
||||
WHERE c.oid = {oid} AND a.grantee <> c.relowner GROUP BY 1, 3 ORDER BY 1, 3"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
|
||||
pub fn postgres_ddl_triggers(oid: u32) -> String {
|
||||
format!(
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
|
||||
ORDER BY tgname"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, timing, events` of the triggers of a table (SQLite: `name, sql`).
|
||||
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
@@ -934,6 +964,18 @@ pub struct DdlColumn {
|
||||
pub data_type: String,
|
||||
pub not_null: bool,
|
||||
pub default: Option<String>,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
|
||||
#[derive(Default)]
|
||||
pub struct DdlExtras {
|
||||
pub comment: Option<String>,
|
||||
pub owner: Option<String>,
|
||||
/// `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), with grant option.
|
||||
pub grants: Vec<(String, String, bool)>,
|
||||
/// `CREATE TRIGGER …` statements.
|
||||
pub triggers: Vec<String>,
|
||||
}
|
||||
|
||||
/// `create table` of a PostgreSQL table from its catalog (the server has no `SHOW CREATE`).
|
||||
@@ -943,6 +985,7 @@ pub fn postgres_table_ddl(
|
||||
columns: &[DdlColumn],
|
||||
constraints: &[(String, String)],
|
||||
indexes: &[String],
|
||||
extras: &DdlExtras,
|
||||
) -> String {
|
||||
let d = DbDriver::Postgres;
|
||||
let mut items: Vec<String> = columns
|
||||
@@ -959,9 +1002,31 @@ pub fn postgres_table_ddl(
|
||||
})
|
||||
.collect();
|
||||
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
|
||||
let mut out = format!("create table {}\n(\n{}\n);\n", qualified(d, schema, table), items.join(",\n"));
|
||||
for i in indexes {
|
||||
out.push_str(&format!("\n{i};\n"));
|
||||
let target = qualified(d, schema, table);
|
||||
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
|
||||
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
|
||||
if let Some(comment) = &extras.comment {
|
||||
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
|
||||
}
|
||||
for c in columns {
|
||||
if let Some(comment) = &c.comment {
|
||||
let column = format!("{target}.{}", quote_ident(d, &c.name));
|
||||
out.push_str(&format!("\ncomment on column {column} is {};\n", quote_literal(d, comment)));
|
||||
}
|
||||
}
|
||||
if let Some(owner) = &extras.owner {
|
||||
out.push_str(&format!("\nalter table {target}\n owner to {};\n", quote_ident(d, owner)));
|
||||
}
|
||||
if !extras.grants.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
for (grantee, privileges, grantable) in &extras.grants {
|
||||
let to = if grantee == "PUBLIC" { "public".to_owned() } else { quote_ident(d, grantee) };
|
||||
let option = if *grantable { " with grant option" } else { "" };
|
||||
out.push_str(&format!("grant {privileges} on {target} to {to}{option};\n"));
|
||||
}
|
||||
for statement in indexes.iter().chain(&extras.triggers) {
|
||||
out.push_str(&format!("\n{};\n", statement.trim_end().trim_end_matches(';')));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -988,6 +1053,24 @@ mod tests {
|
||||
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
|
||||
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
|
||||
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
|
||||
assert!(tables(DbDriver::Postgres, "public").contains("obj_description(c.oid, 'pg_class')"));
|
||||
assert!(tables(DbDriver::Mysql, "db").contains("table_comment"));
|
||||
assert!(tables(DbDriver::Oracle, "S").contains("all_tab_comments"));
|
||||
assert!(tables(DbDriver::Clickhouse, "db").contains("END, comment FROM system.tables"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
|
||||
// Completion (the hover card of a table or column) carries them too, as the ninth field.
|
||||
let completion = |driver| completion_columns(driver, CompletionScope::All);
|
||||
assert!(completion(DbDriver::Postgres).contains("col_description(c.oid, a.attnum)"));
|
||||
assert!(completion(DbDriver::Mysql).contains("ELSE 0 END, c.column_comment"));
|
||||
assert!(
|
||||
completion(DbDriver::Oracle).contains("cc.comments")
|
||||
&& completion(DbDriver::Oracle).contains("all_col_comments")
|
||||
);
|
||||
assert!(completion(DbDriver::Clickhouse).contains("c.is_in_primary_key, 1, c.comment"));
|
||||
assert!(completion(DbDriver::Snowflake).contains("ELSE 0 END, c.comment"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer] {
|
||||
assert!(completion(driver).contains("ELSE 0 END, NULL"), "{driver:?}");
|
||||
}
|
||||
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
|
||||
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
|
||||
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
|
||||
@@ -1015,6 +1098,7 @@ mod tests {
|
||||
assert_eq!(current_schema(driver), Some("SELECT currentDatabase()"));
|
||||
let relations = tables(driver, "event's\\db");
|
||||
assert!(relations.contains("WHEN 'MaterializedView' THEN 'materialized view'"));
|
||||
assert!(relations.contains(r"END, comment FROM system.tables"));
|
||||
assert!(relations.contains(r"WHERE database = 'event''s\\db' AND is_temporary = 0"));
|
||||
let fields = columns(driver, "default", "events");
|
||||
assert!(fields.starts_with("SELECT name, type, CASE WHEN startsWith(type, 'Nullable(')"));
|
||||
@@ -1130,6 +1214,7 @@ mod tests {
|
||||
#[test]
|
||||
fn sqlserver_introspection_queries() {
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
|
||||
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
|
||||
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
@@ -1206,8 +1291,10 @@ mod tests {
|
||||
assert_eq!(DbDriver::Oracle.default_port(), Some(1521));
|
||||
assert!(schemas(DbDriver::Oracle, true).contains("all_users"));
|
||||
assert!(schemas(DbDriver::Oracle, false).contains("'MDSYS'"));
|
||||
assert!(tables(DbDriver::Oracle, "hr").contains("all_tables"));
|
||||
assert!(tables(DbDriver::Oracle, "hr").contains("all_views"));
|
||||
let relations = tables(DbDriver::Oracle, "hr");
|
||||
assert!(relations.contains("all_tab_comments"));
|
||||
assert!(relations.contains("table_type = 'VIEW'"));
|
||||
assert!(relations.contains("comments"));
|
||||
let cols = columns(DbDriver::Oracle, "hr", "employees");
|
||||
assert!(cols.contains("all_tab_columns"));
|
||||
assert!(cols.contains("DECODE(c.nullable, 'Y', 'YES', 'NO')"));
|
||||
@@ -1296,12 +1383,13 @@ mod tests {
|
||||
#[test]
|
||||
fn postgres_ddl() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None },
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "name".into(),
|
||||
data_type: "character varying(40)".into(),
|
||||
not_null: false,
|
||||
default: Some("'x'::character varying".into()),
|
||||
comment: None,
|
||||
},
|
||||
];
|
||||
assert_eq!(
|
||||
@@ -1310,12 +1398,53 @@ mod tests {
|
||||
"t",
|
||||
&cols,
|
||||
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()]
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
|
||||
&DdlExtras::default(),
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "note".into(),
|
||||
data_type: "text".into(),
|
||||
not_null: false,
|
||||
default: None,
|
||||
comment: Some("what's this".into()),
|
||||
},
|
||||
];
|
||||
let extras = DdlExtras {
|
||||
comment: Some("Orders".into()),
|
||||
owner: Some("app owner".into()),
|
||||
grants: vec![("PUBLIC".into(), "select".into(), false), ("reader".into(), "insert, select".into(), true)],
|
||||
triggers: vec![
|
||||
"CREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit()".into(),
|
||||
],
|
||||
};
|
||||
assert_eq!(
|
||||
postgres_table_ddl(
|
||||
"public",
|
||||
"t",
|
||||
&cols,
|
||||
&[],
|
||||
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
|
||||
&extras
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
|
||||
\ncomment on table \"public\".\"t\" is 'Orders';\n\
|
||||
\ncomment on column \"public\".\"t\".\"note\" is 'what''s this';\n\
|
||||
\nalter table \"public\".\"t\"\n owner to \"app owner\";\n\
|
||||
\ngrant select on \"public\".\"t\" to public;\n\
|
||||
grant insert, select on \"public\".\"t\" to \"reader\" with grant option;\n\
|
||||
\nCREATE INDEX t_note ON public.t USING btree (note);\n\
|
||||
\nCREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit();\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snowflake_quotes_names_and_reads_its_information_schema() {
|
||||
let driver = DbDriver::Snowflake;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! Data source files edited outside the Database tool window (by hand, by a coding
|
||||
//! agent, by `git checkout`) are picked up while the project is open, as IDEA does
|
||||
//! Data source and data source folder files edited outside the Database tool window
|
||||
//! (by hand, by a coding agent, by `git checkout`) are picked up while the project is open, as IDEA does
|
||||
//! for `dataSources.xml`. The project file tree's watcher is no help here: it never
|
||||
//! reports a modification inside a gitignored `.openidea/`.
|
||||
|
||||
use crate::source::FILE;
|
||||
use crate::source::{FILE, FOLDERS_FILE};
|
||||
use ide_core::{IdeError, IdeResult, project_dir};
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use parking_lot::Mutex;
|
||||
@@ -15,8 +15,8 @@ use std::time::Duration;
|
||||
/// the files are read.
|
||||
const SETTLE: Duration = Duration::from_millis(200);
|
||||
|
||||
/// Watches `<root>/.openidea/data-sources.toml` and `<global>/data-sources.toml`;
|
||||
/// stops when dropped.
|
||||
/// Watches `<root>/.openidea/data-sources.toml`, `data-source-folders.toml` and
|
||||
/// `<global>/data-sources.toml`; stops when dropped.
|
||||
pub struct SourcesWatch {
|
||||
_watcher: Arc<Mutex<RecommendedWatcher>>,
|
||||
}
|
||||
@@ -29,7 +29,7 @@ impl SourcesWatch {
|
||||
let (tx, rx) = mpsc::channel::<()>();
|
||||
let relevant = {
|
||||
let config = config.clone();
|
||||
move |p: &Path| p.file_name().is_some_and(|n| n == FILE) || p == config
|
||||
move |p: &Path| p.file_name().is_some_and(|n| n == FILE || n == FOLDERS_FILE) || p == config
|
||||
};
|
||||
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
if let Ok(e) = res
|
||||
@@ -131,6 +131,10 @@ mod tests {
|
||||
std::fs::write(project.join(".openidea/data-sources.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "project file");
|
||||
|
||||
let seen = count.load(Ordering::SeqCst);
|
||||
std::fs::write(project.join(".openidea/data-source-folders.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "project folders file");
|
||||
|
||||
let seen = count.load(Ordering::SeqCst);
|
||||
std::fs::write(global.join("data-sources.toml"), "").unwrap();
|
||||
assert!(wait_for(&count, seen + 1), "global file");
|
||||
|
||||
@@ -57,6 +57,7 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
assert!(schemas.iter().any(|n| n == s), "{s} missing from {schemas:?}");
|
||||
let tables = db.tables("m", s).await?;
|
||||
assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["用户"], "tables of {s}");
|
||||
assert_eq!(tables[0].comment.as_deref(), Some("用户表"));
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
|
||||
@@ -353,6 +353,9 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
|
||||
let orders = db.table_details("p", "oi_meta", "orders").await?;
|
||||
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let listed = db.tables("p", "oi_meta").await?;
|
||||
let listed_orders = listed.iter().find(|table| table.name == "orders").expect("orders in the table list");
|
||||
assert_eq!(listed_orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, None, Some("Free text")]);
|
||||
assert_eq!(details.comment, None);
|
||||
@@ -420,7 +423,29 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
|
||||
db.execute("p", "CREATE SEQUENCE oi_keys.seq", 10, &c).await?;
|
||||
let objects = db.schema_objects("p", "oi_keys").await?;
|
||||
assert_eq!(objects.sequences.len(), 1);
|
||||
assert!(db.ddl("p", "oi_keys", "refs").await?.contains("FOREIGN KEY"));
|
||||
let plain = db.ddl("p", "oi_keys", "refs").await?;
|
||||
assert!(plain.contains("FOREIGN KEY"), "{plain}");
|
||||
assert!(plain.contains("\n owner to "), "{plain}");
|
||||
assert!(!plain.contains("comment on") && !plain.contains("grant ") && !plain.contains("TRIGGER"), "{plain}");
|
||||
// Comments, privileges and triggers come back too, so the script rebuilds the table.
|
||||
for statement in [
|
||||
"COMMENT ON TABLE oi_keys.refs IS 'Refs'",
|
||||
"COMMENT ON COLUMN oi_keys.refs.x IS 'it''s x'",
|
||||
"GRANT SELECT, INSERT ON oi_keys.refs TO PUBLIC",
|
||||
"CREATE FUNCTION oi_keys.touch() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END'",
|
||||
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch()",
|
||||
] {
|
||||
db.execute("p", statement, 10, &c).await?;
|
||||
}
|
||||
let full = db.ddl("p", "oi_keys", "refs").await?;
|
||||
for part in [
|
||||
"comment on table \"oi_keys\".\"refs\" is 'Refs';",
|
||||
"comment on column \"oi_keys\".\"refs\".\"x\" is 'it''s x';",
|
||||
"grant insert, select on \"oi_keys\".\"refs\" to public;",
|
||||
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch();",
|
||||
] {
|
||||
assert!(full.contains(part), "{part}\n{full}");
|
||||
}
|
||||
db.execute("p", "DROP SCHEMA oi_keys CASCADE", 10, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -27,18 +27,24 @@ const QUICK: Duration = Duration::from_secs(20);
|
||||
/// Stop / restart wait for the container's grace period (10 s by default).
|
||||
const LIFECYCLE: Duration = Duration::from_secs(90);
|
||||
|
||||
/// Locates the docker executable once per process. GUI apps on macOS start with a
|
||||
/// minimal `PATH`, so the usual install locations are probed after the lookup.
|
||||
/// Locates the docker executable. GUI apps on macOS start with a minimal `PATH`, so
|
||||
/// the login/reloaded `PATH` and usual install locations are probed after the lookup.
|
||||
/// Only a found path is cached, so installing Docker while the backend runs is picked up.
|
||||
pub fn docker_executable() -> Option<PathBuf> {
|
||||
static DOCKER: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
DOCKER
|
||||
.get_or_init(|| {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
if let Ok(found) = which::which("docker") {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
static DOCKER: OnceLock<PathBuf> = OnceLock::new();
|
||||
if let Some(cached) = DOCKER.get().filter(|p| p.is_file()) {
|
||||
return Some(cached.clone());
|
||||
}
|
||||
let found = which::which("docker")
|
||||
.ok()
|
||||
.or_else(|| {
|
||||
let path = ide_core::process::host_var_os("PATH")?;
|
||||
which::which_in("docker", Some(path), ".").ok()
|
||||
})
|
||||
.or_else(|| {
|
||||
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
|
||||
let mut candidates: Vec<PathBuf> = if cfg!(windows) {
|
||||
vec![PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin\docker.exe")]
|
||||
@@ -60,8 +66,11 @@ pub fn docker_executable() -> Option<PathBuf> {
|
||||
candidates.push(home.join(".docker/bin/docker"));
|
||||
}
|
||||
candidates.into_iter().find(|p| p.is_file())
|
||||
})
|
||||
.clone()
|
||||
});
|
||||
if let Some(ref path) = found {
|
||||
let _ = DOCKER.set(path.clone());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Environment for docker command lines a run configuration launches: the endpoint's
|
||||
|
||||
@@ -76,6 +76,7 @@ tracing.workspace = true
|
||||
url = "2"
|
||||
tracing-subscriber.workspace = true
|
||||
parking_lot.workspace = true
|
||||
notify.workspace = true
|
||||
dunce.workspace = true
|
||||
dirs.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
@@ -82,6 +82,11 @@ impl Environment {
|
||||
}
|
||||
}
|
||||
|
||||
/// True on `openidea-server`, where the backend runs on a remote/headless host rather than the desktop shell.
|
||||
pub fn is_remote(&self) -> bool {
|
||||
self.project_env
|
||||
}
|
||||
|
||||
/// A trusted project at `root` opened or became trusted: loads its direnv environment in
|
||||
/// the background, unless another window of it already did. Its language servers wait.
|
||||
pub(crate) fn direnv_opened(&self, root: &Path, sink: &SharedSink) {
|
||||
|
||||
@@ -261,6 +261,12 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of the formatters' language lists that covers `language`. MDX was part of Markdown
|
||||
/// and follows its entry, so lists saved before it had its own language keep formatting it.
|
||||
fn formatter_language(language: &str) -> &str {
|
||||
if language == "mdx" { "markdown" } else { language }
|
||||
}
|
||||
|
||||
/// The external formatter of a file, for a language with an external formatter.
|
||||
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
|
||||
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
|
||||
@@ -295,7 +301,8 @@ fn external_tool(
|
||||
)))
|
||||
};
|
||||
}
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
|
||||
let id = formatter_language(language.id.as_str());
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
|
||||
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
|
||||
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
|
||||
Some(Black)
|
||||
@@ -897,6 +904,24 @@ mod tests {
|
||||
external_tool(forced, language.as_ref(), file, settings)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mdx_follows_the_markdown_entry_of_saved_language_lists() {
|
||||
// Saved before MDX had its own language: the whole list, with no `mdx` in it.
|
||||
let old: ide_core::settings::Settings = serde_json::from_str(
|
||||
r#"{"languages":{"prettier":{"languages":["markdown","css"]},"oxfmt":{"languages":["css"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let file = Path::new("/project/docs/intro.mdx");
|
||||
assert_eq!(tool(None, "mdx", file, &old.languages).unwrap(), Some(Prettier));
|
||||
let mut no_markdown = old.languages.clone();
|
||||
no_markdown.prettier.languages.retain(|l| l != "markdown");
|
||||
assert_eq!(tool(None, "mdx", file, &no_markdown).unwrap(), None);
|
||||
let mut oxfmt = old.languages.clone();
|
||||
oxfmt.oxfmt.languages.push("markdown".into());
|
||||
oxfmt.oxfmt.prefer = true;
|
||||
assert_eq!(tool(None, "mdx", file, &oxfmt).unwrap(), Some(Oxfmt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_settings_use_ruff_for_python_and_prettier_for_the_web() {
|
||||
let settings = LanguagesSettings::default();
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
//! Project-scoped GitHub CLI (`gh`) account selection and opt-in `GH_TOKEN` injection.
|
||||
//!
|
||||
//! Each project may pin a GitHub login in `vcs.github.account` (`.openidea/settings.toml`) or
|
||||
//! leave it empty (`Automatic`). `Automatic` leaves `gh`'s own behaviour untouched—no `GH_TOKEN`
|
||||
//! is injected into [`ide_core::project_env`] and opening a project makes no GitHub API calls.
|
||||
//! When the user inspects GitHub settings or Pull Requests with multiple `gh` keyring accounts,
|
||||
//! OpenIDEA probes the repository remote (`owner/repo`) to suggest a matching non-active account
|
||||
//! ("Use <login> for this project"). Only when an account is explicitly chosen does OpenIDEA
|
||||
//! resolve its token into [`ide_core::project_env`] (for both `project.root` and `.worktrees`).
|
||||
|
||||
use crate::Project;
|
||||
use ide_agent::GhAuthAccount;
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::LazyLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const AMBIENT_GH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
const GH_TOOL: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
|
||||
const LOCAL_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
|
||||
const CACHE_TTL: Duration = Duration::from_secs(10 * 60);
|
||||
|
||||
/// GitHub CLI accounts available on this machine and which one applies to the project.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhProjectAccountStatus {
|
||||
pub gh_installed: bool,
|
||||
pub accounts: Vec<GhAuthAccount>,
|
||||
/// Value of `vcs.github.account` (`""` = Automatic).
|
||||
pub configured_account: String,
|
||||
/// Account login currently used (`configured_account` if signed in, else `gh`'s active account).
|
||||
pub effective_account: Option<String>,
|
||||
/// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty.
|
||||
pub suggested_account: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedAutoAccount {
|
||||
login: Option<String>,
|
||||
at: Instant,
|
||||
}
|
||||
|
||||
type AutoCacheMap = HashMap<(String, Vec<String>), CachedAutoAccount>;
|
||||
static AUTO_CACHE: LazyLock<Mutex<AutoCacheMap>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub(crate) fn is_valid_github_login(login: &str) -> bool {
|
||||
let bytes = login.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn clean_gh_command(program: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.current_dir(std::env::temp_dir())
|
||||
.args(args)
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1")
|
||||
.env("CLICOLOR", "0");
|
||||
// Strip ambient tokens by setting empty then removing after `prepare`: `CliTool::run` calls
|
||||
// `ide_core::process::prepare`, which skips keys already present in `cmd.get_envs()`.
|
||||
for key in AMBIENT_GH_VARS {
|
||||
cmd.env_remove(key);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
fn gh_token_for_account(program: &Path, login: &str) -> Option<String> {
|
||||
if !is_valid_github_login(login) {
|
||||
return None;
|
||||
}
|
||||
let cmd = clean_gh_command(program, &["auth", "token", "--hostname", "github.com", "--user", login]);
|
||||
let out = GH_TOOL.run(cmd, LOCAL_TIMEOUT, None).ok().filter(|o| o.success)?;
|
||||
let token = out.stdout.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
/// Access level of an account for a specific `owner/repo` on `github.com`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum RepoAccess {
|
||||
None = 0,
|
||||
Read = 1,
|
||||
Push = 2,
|
||||
}
|
||||
|
||||
fn probe_repo_access(program: &Path, token: &str, owner: &str, name: &str) -> RepoAccess {
|
||||
let endpoint = format!("repos/{owner}/{name}");
|
||||
let mut cmd =
|
||||
clean_gh_command(program, &["api", "--hostname", "github.com", &endpoint, "--jq", ".permissions.push"]);
|
||||
cmd.env("GH_TOKEN", token);
|
||||
let Ok(out) = GH_TOOL.run(cmd, PROBE_TIMEOUT, None) else {
|
||||
return RepoAccess::None;
|
||||
};
|
||||
if !out.success {
|
||||
return RepoAccess::None;
|
||||
}
|
||||
if out.stdout.trim() == "true" { RepoAccess::Push } else { RepoAccess::Read }
|
||||
}
|
||||
|
||||
fn pick_best_account(candidates: &[(GhAuthAccount, RepoAccess)]) -> Option<(&GhAuthAccount, bool)> {
|
||||
let active_access =
|
||||
candidates.iter().find(|(a, _)| a.active).map(|(_, access)| *access).unwrap_or(RepoAccess::None);
|
||||
// Prefer higher RepoAccess; break ties in favor of the globally active account.
|
||||
let (best, best_access) = candidates.iter().max_by_key(|(acc, access)| (*access, acc.active))?;
|
||||
if *best_access == RepoAccess::None {
|
||||
// Nobody could reach the repo (offline or SSO required): keep the active account.
|
||||
return candidates.iter().find(|(a, _)| a.active).or_else(|| candidates.first()).map(|(a, _)| (a, false));
|
||||
}
|
||||
let auto_detected = !best.active && *best_access > active_access;
|
||||
Some((best, auto_detected))
|
||||
}
|
||||
|
||||
/// Parses `github.com` `(owner, repo)` from HTTPS, SSH, or SCP-style remote URLs.
|
||||
pub(crate) fn parse_github_owner_repo(url: &str) -> Option<(String, String)> {
|
||||
let url = url.trim();
|
||||
let path = if let Some(rest) =
|
||||
url.strip_prefix("https://github.com/").or_else(|| url.strip_prefix("http://github.com/"))
|
||||
{
|
||||
rest
|
||||
} else if let Some(rest) = url.strip_prefix("ssh://") {
|
||||
rest.strip_prefix("[email protected]/").or_else(|| rest.strip_prefix("github.com/"))?
|
||||
} else {
|
||||
url.strip_prefix("[email protected]:")?
|
||||
};
|
||||
let path = path.trim_matches('/');
|
||||
let (owner, rest) = path.split_once('/')?;
|
||||
let repo = rest.split('/').next()?;
|
||||
let repo = repo.strip_suffix(".git").unwrap_or(repo);
|
||||
if owner.is_empty() || repo.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((owner.to_owned(), repo.to_owned()))
|
||||
}
|
||||
|
||||
fn primary_github_repo(project: &Project) -> Option<(String, String)> {
|
||||
let repos = project.repos();
|
||||
let mut ordered = Vec::new();
|
||||
if let Some(primary) = repos.primary() {
|
||||
ordered.push(primary);
|
||||
}
|
||||
for repo in repos.all() {
|
||||
if ordered.first().is_none_or(|p| p.root() != repo.root()) {
|
||||
ordered.push(repo);
|
||||
}
|
||||
}
|
||||
for repo in ordered {
|
||||
let Ok(mut remotes) = repo.remotes() else { continue };
|
||||
remotes.sort_by_key(|r| r.name != "origin");
|
||||
for remote in remotes {
|
||||
let url = remote.resolved_url.as_deref().unwrap_or(&remote.url);
|
||||
if let Some(coords) = parse_github_owner_repo(url) {
|
||||
return Some(coords);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn auto_detect_account(program: &Path, accounts: &[GhAuthAccount], owner: &str, repo: &str) -> Option<(String, bool)> {
|
||||
// Fast path: the repository owner matches one of the signed-in accounts directly.
|
||||
if let Some(matched) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(owner)) {
|
||||
return Some((matched.login.clone(), !matched.active));
|
||||
}
|
||||
let key_repo = format!("{}/{}", owner.to_ascii_lowercase(), repo.to_ascii_lowercase());
|
||||
let key_logins: Vec<String> = accounts.iter().map(|a| format!("{}:{}", a.login, a.active)).collect();
|
||||
let cache_key = (key_repo, key_logins);
|
||||
if let Some(cached) = AUTO_CACHE.lock().get(&cache_key).cloned()
|
||||
&& cached.at.elapsed() < CACHE_TTL
|
||||
{
|
||||
if let Some(login) = cached.login {
|
||||
let is_active = accounts.iter().any(|a| a.login == login && a.active);
|
||||
return Some((login, !is_active));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let tokens: Vec<(GhAuthAccount, Option<String>)> =
|
||||
accounts.iter().map(|acc| (acc.clone(), gh_token_for_account(program, &acc.login))).collect();
|
||||
let results: Vec<(GhAuthAccount, RepoAccess)> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = tokens
|
||||
.into_iter()
|
||||
.map(|(acc, token)| {
|
||||
s.spawn(move || {
|
||||
let access = match token {
|
||||
Some(tok) => probe_repo_access(program, &tok, owner, repo),
|
||||
None => RepoAccess::None,
|
||||
};
|
||||
(acc, access)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().filter_map(|h| h.join().ok()).collect()
|
||||
});
|
||||
let picked = pick_best_account(&results).map(|(acc, auto)| (acc.login.clone(), auto));
|
||||
AUTO_CACHE
|
||||
.lock()
|
||||
.insert(cache_key, CachedAutoAccount { login: picked.as_ref().map(|(l, _)| l.clone()), at: Instant::now() });
|
||||
picked
|
||||
}
|
||||
|
||||
/// Resolves global status when no project is open.
|
||||
pub fn global_status(configured_account: String) -> GhProjectAccountStatus {
|
||||
let configured_account = configured_account.trim().to_owned();
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone())
|
||||
};
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account: None }
|
||||
}
|
||||
|
||||
/// Applies the project's explicit `vcs.github.account` setting to [`ide_core::project_env`]
|
||||
/// without making any network requests. `Automatic` (`""`) clears any injected `GH_TOKEN` so
|
||||
/// processes use `gh`'s own behaviour.
|
||||
pub fn apply_to_project(project: &Project) {
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return;
|
||||
}
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if configured_account.is_empty() {
|
||||
set_project_token(project, None);
|
||||
return;
|
||||
}
|
||||
let token = find_gh_executable().and_then(|program| gh_token_for_account(&program, &configured_account));
|
||||
set_project_token(project, token);
|
||||
}
|
||||
|
||||
/// Applies the project's explicit account setting and returns the full account status,
|
||||
/// probing the project's GitHub remote to suggest a matching non-active `gh` account when
|
||||
/// `vcs.github.account` is `Automatic` (`""`) and multiple `gh` accounts are signed in.
|
||||
pub fn project_status(project: &Project) -> GhProjectAccountStatus {
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
}
|
||||
apply_to_project(project);
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
};
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let active_login = accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone());
|
||||
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
active_login
|
||||
};
|
||||
|
||||
let suggested_account = if configured_account.is_empty() && accounts.len() >= 2 {
|
||||
primary_github_repo(project)
|
||||
.and_then(|(owner, repo)| auto_detect_account(&program, &accounts, &owner, &repo))
|
||||
.and_then(|(login, non_active_match)| non_active_match.then_some(login))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account }
|
||||
}
|
||||
|
||||
fn set_project_token(project: &Project, token: Option<String>) {
|
||||
let os_tok = token.map(std::ffi::OsString::from);
|
||||
let changed_root = ide_core::project_env::set_github_token(&project.root, os_tok.clone());
|
||||
let changed_wt = ide_core::project_env::set_github_token(project.agents.worktrees_dir(), os_tok);
|
||||
if changed_root || changed_wt {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_project_env(project: &Project) {
|
||||
ide_core::project_env::remove_all(&project.root);
|
||||
ide_core::project_env::remove_all(project.agents.worktrees_dir());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_github_owner_repo_across_https_ssh_and_scp_remotes() {
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("https://github.com/l0ng-ai/openidea.git"),
|
||||
Some(("l0ng-ai".into(), "openidea".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("[email protected]:acme-corp/payments.git"),
|
||||
Some(("acme-corp".into(), "payments".into()))
|
||||
);
|
||||
assert_eq!(parse_github_owner_repo("ssh://[email protected]/alice/demo/"), Some(("alice".into(), "demo".into())));
|
||||
assert_eq!(parse_github_owner_repo("https://gitlab.com/foo/bar.git"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_github_logins_against_flag_injection() {
|
||||
assert!(is_valid_github_login("alice"));
|
||||
assert!(is_valid_github_login("alice-work"));
|
||||
assert!(is_valid_github_login("l0ng-ai"));
|
||||
assert!(!is_valid_github_login(""));
|
||||
assert!(!is_valid_github_login("--hostname"));
|
||||
assert!(!is_valid_github_login("bad space"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_account_with_push_or_private_access_and_preserves_active_on_ties() {
|
||||
let personal = GhAuthAccount { login: "alice".into(), active: true };
|
||||
let work = GhAuthAccount { login: "alice-work".into(), active: false };
|
||||
|
||||
// Private org repo: personal gets 404 (None), work gets Push -> auto-detects work.
|
||||
let private_org = vec![(personal.clone(), RepoAccess::None), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&private_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Public org repo: personal gets Read, work gets Push -> auto-detects work.
|
||||
let public_org = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&public_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Third-party public repo: both get Read -> keeps active personal account without auto flag.
|
||||
let oss = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Read)];
|
||||
let (picked, auto) = pick_best_account(&oss).unwrap();
|
||||
assert_eq!(picked.login, "alice");
|
||||
assert!(!auto);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use ide_build::kotlin_bridge::{self, Outcome, ProjectLibraries};
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink, TaskId};
|
||||
use ide_lsp::LspManager;
|
||||
use ide_workspace::SettingsStore;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
@@ -223,9 +223,15 @@ impl KotlinBridge {
|
||||
let staging = directory.clone();
|
||||
let root = self.root.clone();
|
||||
let token = cancel.clone();
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || kotlin_bridge::build(&root, &model, &bundle, &staging, &token))
|
||||
.await;
|
||||
// The build runs Maven over the Kotlin modules, which can take a minute: it shows in
|
||||
// the status bar and can be stopped there (the next saved change builds again).
|
||||
let task = BuildTask::start(self.sink.clone(), &cancel);
|
||||
let progress = task.reporter();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
kotlin_bridge::build(&root, &model, &bundle, &staging, &token, &progress)
|
||||
})
|
||||
.await;
|
||||
drop(task);
|
||||
if !self.revision.lock().current(generation) || self.lifetime.is_cancelled() {
|
||||
remove_directory(directory).await;
|
||||
continue;
|
||||
@@ -306,6 +312,58 @@ impl KotlinBridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status bar's background task for one bridge build; ends when dropped.
|
||||
struct BuildTask {
|
||||
id: TaskId,
|
||||
sink: SharedSink,
|
||||
_cancel: ide_core::task::CancelHandle,
|
||||
}
|
||||
|
||||
impl BuildTask {
|
||||
const TITLE: &str = "Compiling Kotlin for Java";
|
||||
|
||||
fn start(sink: SharedSink, cancel: &CancellationToken) -> Self {
|
||||
let id = TaskId::next();
|
||||
let cancel = cancel.clone();
|
||||
let handle = ide_core::task::on_cancel(id, move || cancel.cancel());
|
||||
let task = Self { id, sink, _cancel: handle };
|
||||
task.emit(None, None, false);
|
||||
task
|
||||
}
|
||||
|
||||
fn emit(&self, message: Option<String>, fraction: Option<f32>, done: bool) {
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
id: self.id,
|
||||
title: Self::TITLE.into(),
|
||||
message,
|
||||
fraction,
|
||||
done,
|
||||
cancellable: !done,
|
||||
});
|
||||
}
|
||||
|
||||
/// Forwards Maven's progress to the task.
|
||||
fn reporter(&self) -> impl Fn(&str, Option<f32>) + Send + Sync + 'static {
|
||||
let (id, sink) = (self.id, self.sink.clone());
|
||||
move |message: &str, fraction| {
|
||||
sink.emit(IdeEvent::Task {
|
||||
id,
|
||||
title: Self::TITLE.into(),
|
||||
message: Some(message.to_owned()),
|
||||
fraction,
|
||||
done: false,
|
||||
cancellable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BuildTask {
|
||||
fn drop(&mut self) {
|
||||
self.emit(None, None, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
|
||||
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
|
||||
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
|
||||
@@ -369,6 +427,41 @@ impl DocumentObserver for KotlinBridge {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_build_shows_as_a_cancellable_background_task() {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink: SharedSink = Arc::new({
|
||||
let events = events.clone();
|
||||
move |e: IdeEvent| events.lock().push(e)
|
||||
});
|
||||
let cancel = CancellationToken::new();
|
||||
let task = BuildTask::start(sink, &cancel);
|
||||
let progress = task.reporter();
|
||||
progress("Building app 1.0 [2/3]", Some(0.5));
|
||||
assert!(ide_core::task::cancel(task.id), "the status bar can stop it");
|
||||
assert!(cancel.is_cancelled());
|
||||
drop(task);
|
||||
let seen: Vec<_> = events
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|e| match e {
|
||||
IdeEvent::Task { title, message, fraction, done, cancellable, .. } => {
|
||||
assert_eq!(title, "Compiling Kotlin for Java");
|
||||
(message.clone(), *fraction, *done, *cancellable)
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
seen,
|
||||
[
|
||||
(None, None, false, true),
|
||||
(Some("Building app 1.0 [2/3]".into()), Some(0.5), false, true),
|
||||
(None, None, true, false),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_package_directory_does_not_trigger() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
pub mod environment;
|
||||
mod formatter;
|
||||
pub mod github_auth;
|
||||
mod java_runtime;
|
||||
mod kotlin_bridge;
|
||||
pub mod mcp;
|
||||
@@ -124,6 +125,7 @@ pub struct Host {
|
||||
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
|
||||
/// The IDE's Java build: resident javac processes shared by every window's launches.
|
||||
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
|
||||
pub(crate) metrics_sampler: Mutex<ops::host_metrics::HostMetricsSampler>,
|
||||
/// SSH connections of Settings › SSH Configurations.
|
||||
pub ssh: Arc<ide_ssh::SshManager>,
|
||||
/// SFTP deployment, remote file editing and runs on run targets.
|
||||
@@ -254,6 +256,7 @@ impl Host {
|
||||
heap_requests: Default::default(),
|
||||
rebase_editors: Default::default(),
|
||||
java_build: Default::default(),
|
||||
metrics_sampler: Default::default(),
|
||||
languages,
|
||||
syntax,
|
||||
config_dir,
|
||||
@@ -419,6 +422,7 @@ impl Host {
|
||||
self.environment.project_closed();
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
}
|
||||
}
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
|
||||
@@ -38,6 +38,11 @@ impl Requests {
|
||||
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
|
||||
Ok(())
|
||||
}
|
||||
/// Whether `window` answers requests (a project loaded for MCP alone has no window).
|
||||
pub(super) fn window_ready(&self, window: &str) -> bool {
|
||||
self.0.lock().ready.contains(window)
|
||||
}
|
||||
|
||||
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
|
||||
let id = super::tool::request_id().0;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
@@ -15,8 +15,9 @@ use ide_core::{IdeError, IdeResult, RunId, Severity};
|
||||
use ide_run::{OutputChunk, RunConfig};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -286,6 +287,79 @@ workingDirectory, envs).",
|
||||
/// not the user's own runs.
|
||||
static STARTED: LazyLock<Mutex<HashSet<RunId>>> = LazyLock::new(Default::default);
|
||||
|
||||
/// Run configuration parameter naming the `execute_run_configuration` call a start belongs to.
|
||||
pub const CONFIG_RUN_PARAM: &str = "mcp.configRun";
|
||||
|
||||
/// The `execute_run_configuration` calls waiting for the Run tool window to start their run.
|
||||
struct ConfigLaunch {
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
started: Option<Result<ide_run::RunInfo, String>>,
|
||||
}
|
||||
static LAUNCHES: LazyLock<Mutex<HashMap<u64, ConfigLaunch>>> = LazyLock::new(Default::default);
|
||||
static NEXT_LAUNCH: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// The Run tool window's start of an `execute_run_configuration` run: its output also goes to
|
||||
/// the call's output file, and the call learns the run it started.
|
||||
pub(crate) struct ConfigRunLaunch {
|
||||
token: u64,
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
}
|
||||
|
||||
/// The call `config` was started for (its first start only; a rerun from the tab is the user's).
|
||||
pub(crate) fn config_run_launch(config: &RunConfig) -> Option<ConfigRunLaunch> {
|
||||
let token = config.extras.params.get(CONFIG_RUN_PARAM)?.parse().ok()?;
|
||||
let launches = LAUNCHES.lock();
|
||||
let launch = launches.get(&token).filter(|l| l.started.is_none())?;
|
||||
Some(ConfigRunLaunch { token, output: launch.output.clone() })
|
||||
}
|
||||
|
||||
impl ConfigRunLaunch {
|
||||
pub(crate) fn wrap_output(&self, on_output: crate::ops::Emit<OutputChunk>) -> crate::ops::Emit<OutputChunk> {
|
||||
let output = self.output.clone();
|
||||
Arc::new(move |chunk: OutputChunk| {
|
||||
// As JetBrains skips `ProcessOutputType.SYSTEM` (`Process finished…`).
|
||||
if let OutputChunk::Stdout { text } | OutputChunk::Stderr { text } = &chunk {
|
||||
output.lock().append(text);
|
||||
}
|
||||
on_output(chunk);
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn started(&self, result: &IdeResult<ide_run::RunInfo>) {
|
||||
if let Some(launch) = LAUNCHES.lock().get_mut(&self.token) {
|
||||
launch.started = Some(result.clone().map_err(|e| e.message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts `config` in the Run tool window, as the user's Run would: a tab with its console and
|
||||
/// Stop. Its before launch tasks already ran.
|
||||
async fn start_in_run_window(
|
||||
call: &Call,
|
||||
mut config: RunConfig,
|
||||
output: Arc<Mutex<OutputCollector>>,
|
||||
) -> IdeResult<ide_run::RunInfo> {
|
||||
struct Forget(u64);
|
||||
impl Drop for Forget {
|
||||
fn drop(&mut self) {
|
||||
LAUNCHES.lock().remove(&self.0);
|
||||
}
|
||||
}
|
||||
let token = NEXT_LAUNCH.fetch_add(1, Ordering::Relaxed);
|
||||
LAUNCHES.lock().insert(token, ConfigLaunch { output, started: None });
|
||||
let _forget = Forget(token);
|
||||
config.extras.params.insert(CONFIG_RUN_PARAM.into(), token.to_string());
|
||||
let config = serde_json::to_value(&config).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
let asked = call.ask(ide_core::event::McpUiRequest::RunConfiguration { config }).await;
|
||||
let started = LAUNCHES.lock().get_mut(&token).and_then(|l| l.started.take());
|
||||
match (asked, started) {
|
||||
(_, Some(Ok(info))) => Ok(info),
|
||||
(_, Some(Err(message))) => Err(IdeError::invalid(message)),
|
||||
(Err(e), None) => Err(e),
|
||||
(Ok(()), None) => Err(IdeError::invalid("the run did not start")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn started_by_mcp(id: RunId) -> bool {
|
||||
STARTED.lock().contains(&id)
|
||||
}
|
||||
@@ -753,9 +827,9 @@ Behavior:
|
||||
|
||||
Returns the execution result including current output snapshot, optional exit code, and optional `fullOutputPath`.
|
||||
In OpenIDEA the user is asked first for every call; `programArguments` replace the configuration's \
|
||||
arguments (appended to a command that is one shell line, such as `npm run dev`); the run does not appear in the Run \
|
||||
tool window: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \
|
||||
and deleted after a day.",
|
||||
arguments (appended to a command that is one shell line, such as `npm run dev`); the run appears in the Run tool \
|
||||
window like a run the user started, with its console and Stop; while it is still running, the result carries `runId`, \
|
||||
which `stop_run` stops; output files are private and deleted after a day.",
|
||||
|call| async move {
|
||||
let target = execution_target(
|
||||
call.opt_str("configurationName")?,
|
||||
@@ -811,9 +885,15 @@ one by one",
|
||||
};
|
||||
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
|
||||
let output_path = collector.lock().path.clone();
|
||||
let sink = collector.clone();
|
||||
let emit = process_output(move |text| sink.lock().append(text));
|
||||
let info = match crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await {
|
||||
let started = if call.has_window() {
|
||||
start_in_run_window(&call, config, collector.clone()).await
|
||||
} else {
|
||||
// A project loaded for MCP alone has no Run tool window to show it in.
|
||||
let sink = collector.clone();
|
||||
let emit = process_output(move |text| sink.lock().append(text));
|
||||
crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await
|
||||
};
|
||||
let info = match started {
|
||||
Ok(info) => info,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&output_path);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
pub(crate) mod agent;
|
||||
mod agent_tools;
|
||||
mod build;
|
||||
mod configs;
|
||||
pub(crate) mod configs;
|
||||
mod output;
|
||||
mod process;
|
||||
mod targets;
|
||||
|
||||
@@ -493,7 +493,7 @@ fn test_kinds(rel: &str) -> &'static [&'static str] {
|
||||
if JS_FILE.is_match(rel) {
|
||||
&["npm", "deno", "bun"]
|
||||
} else if rel.ends_with(".py") {
|
||||
&["pytest", "python"]
|
||||
&["pytest", "unittest", "python"]
|
||||
} else if rel.ends_with(".go") {
|
||||
&["go"]
|
||||
} else if rel.ends_with(".rs") {
|
||||
@@ -644,6 +644,11 @@ fn test_config_for(root: &Path, rel: &str, configs: &[RunConfig]) -> Option<RunC
|
||||
"npm" | "bun" if base.args.iter().any(|a| a == "--") => derived(&base, rel, with(&[file])),
|
||||
"npm" | "bun" => derived(&base, rel, with(&["--".into(), file])),
|
||||
"deno" | "pytest" | "python" => derived(&base, rel, with(&[file])),
|
||||
// `python -m unittest <file>`; a `discover` selection gives way to the file.
|
||||
"unittest" => {
|
||||
let end = base.args.iter().position(|a| a == "discover").unwrap_or(base.args.len());
|
||||
derived(&base, rel, [base.args[..end].to_vec(), vec![file]].concat())
|
||||
}
|
||||
"go" => {
|
||||
let dir = dir_of(&file);
|
||||
let target = if dir.is_empty() { ".".to_owned() } else { format!("./{dir}") };
|
||||
@@ -790,6 +795,11 @@ pub fn target_config(
|
||||
"pytest" | "python" => {
|
||||
Some(named(replace_last(file.args.clone(), |f| format!("{f}::{}", target.path.join("::")))))
|
||||
}
|
||||
// unittest names tests by dotted module path: `tests.test_calc.TestCalc.test_add`.
|
||||
"unittest" => Some(named(replace_last(file.args.clone(), |f| {
|
||||
let module = f.strip_suffix(".py").unwrap_or(f).replace(['/', '\\'], ".");
|
||||
format!("{module}.{}", target.path.join("."))
|
||||
}))),
|
||||
"go" => {
|
||||
let pattern = format!("^{}$", target.path.iter().map(|p| escape_regexp(p)).collect::<Vec<_>>().join("$/^"));
|
||||
let benchmark = target.path.first().is_some_and(|p| p.starts_with("Benchmark"));
|
||||
@@ -921,6 +931,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_unittest_configs_to_files_and_dotted_tests() {
|
||||
let root = Path::new("/p");
|
||||
let mut unittest =
|
||||
blank("unittest".into(), "unittest", "unittest", "python3".into(), vec!["-m".into(), "unittest".into()]);
|
||||
unittest.is_test = true;
|
||||
let mut discover = unittest.clone();
|
||||
discover.args.extend(["discover".into(), "-s".into(), "tests".into()]);
|
||||
let src = "import unittest\n\nclass TestCalc(unittest.TestCase):\n def test_add(self):\n pass\n";
|
||||
let rel = "tests/test_calc.py";
|
||||
for configs in [vec![unittest], vec![discover]] {
|
||||
let c = context_config(root, rel, &configs, src).unwrap();
|
||||
assert_eq!(
|
||||
(c.kind.as_str(), c.args.as_slice()),
|
||||
("unittest", ["-m", "unittest", rel].map(String::from).as_slice())
|
||||
);
|
||||
let ts = detect(src, rel);
|
||||
let c = target_config(root, &ts[1], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc.test_add"]);
|
||||
let c = target_config(root, &ts[0], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_cargo_test_configs() {
|
||||
let root = Path::new("/p");
|
||||
|
||||
@@ -70,6 +70,10 @@ impl Call {
|
||||
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
|
||||
self.host.mcp_requests.ask(self, request).await
|
||||
}
|
||||
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
|
||||
pub fn has_window(&self) -> bool {
|
||||
self.host.mcp_requests.window_ready(&self.window)
|
||||
}
|
||||
/// Asks the user before a tool changes the project or starts a process, unless brave mode
|
||||
/// is on — read from the IDE's own settings only, which a project's settings can't set.
|
||||
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
|
||||
|
||||
@@ -754,6 +754,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
));
|
||||
|
||||
let mut tools = vec![
|
||||
act("code.saveAsLiveTemplate", "Save as Live Template…"),
|
||||
SEP,
|
||||
act("http.newRequest", "New HTTP Request"),
|
||||
act("http.showToolWindow", "HTTP Client"),
|
||||
SEP,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Project-incarnation notebook ownership and whole-batch execution admission.
|
||||
use crate::ops::Channel;
|
||||
use base64::Engine;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, IpcPath, SharedSink};
|
||||
use ide_notebook::kernel::{KernelManager, KernelOutput};
|
||||
use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot};
|
||||
use parking_lot::Mutex;
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -28,6 +29,31 @@ pub struct NotebookOutputEvent {
|
||||
pub changed_cells: Vec<String>,
|
||||
}
|
||||
|
||||
/// One row of the Jupyter Variables tool window.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
pub struct NotebookVariable {
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub type_name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
const VARIABLES: &str = include_str!("notebook_variables.py");
|
||||
|
||||
/// The rows from the `user_expressions` of the variables request.
|
||||
fn parse_variables(reply: &serde_json::Value) -> IdeResult<Vec<NotebookVariable>> {
|
||||
let rows = &reply["rows"];
|
||||
if rows["status"] != "ok" {
|
||||
let reason = rows["evalue"].as_str().unwrap_or("no result");
|
||||
return Err(IdeError::unavailable(format!("could not read the kernel's variables: {reason}")));
|
||||
}
|
||||
// The value is a base64 str, so its text/plain is that text in quotes.
|
||||
let text = rows["data"]["text/plain"].as_str().unwrap_or_default().trim_matches(['\'', '"']);
|
||||
let bad = |error: String| IdeError::unavailable(format!("could not read the kernel's variables: {error}"));
|
||||
let json = base64::engine::general_purpose::STANDARD.decode(text).map_err(|e| bad(e.to_string()))?;
|
||||
serde_json::from_slice(&json).map_err(|e| bad(e.to_string()))
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Registry {
|
||||
stopped: bool,
|
||||
@@ -323,6 +349,19 @@ impl NotebookService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The variables of the notebook's running kernel; `None` when no kernel runs.
|
||||
pub async fn variables(&self, id: &str) -> IdeResult<Option<Vec<NotebookVariable>>> {
|
||||
let document = self.resolve(id)?;
|
||||
if document.state.lock().active.is_some() {
|
||||
return Err(IdeError::unavailable("notebook is running"));
|
||||
}
|
||||
let expressions = HashMap::from([("rows".to_owned(), "_openidea_variables()".to_owned())]);
|
||||
match self.kernels.inspect(&document.path, VARIABLES, expressions).await? {
|
||||
Some(reply) => parse_variables(&reply).map(Some),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn admit(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -588,6 +627,21 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn variables_are_decoded_from_the_user_expression() {
|
||||
let rows = r#"[{"name": "x", "type": "int", "value": "1"}]"#;
|
||||
let text = format!("'{}'", base64::engine::general_purpose::STANDARD.encode(rows));
|
||||
let reply = json!({"rows": {"status": "ok", "data": {"text/plain": text}, "metadata": {}}});
|
||||
assert_eq!(
|
||||
parse_variables(&reply).unwrap(),
|
||||
vec![NotebookVariable { name: "x".into(), type_name: "int".into(), value: "1".into() }]
|
||||
);
|
||||
let failed =
|
||||
json!({"rows": {"status": "error", "ename": "NameError", "evalue": "name 'get_ipython' is not defined"}});
|
||||
assert!(parse_variables(&failed).unwrap_err().message.contains("get_ipython"));
|
||||
assert!(parse_variables(&json!({})).is_err());
|
||||
}
|
||||
|
||||
fn fixture() -> (tempfile::TempDir, Arc<NotebookService>, NotebookSnapshot) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("session.ipynb");
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Run silently on a notebook's kernel by the Jupyter Variables tool window; the IDE then
|
||||
# evaluates `_openidea_variables()` as a user expression. Same rows as the Python Console's.
|
||||
def _openidea_variables():
|
||||
import base64
|
||||
import json
|
||||
import reprlib
|
||||
import types
|
||||
|
||||
shell = get_ipython() # noqa: F821 -- defined in every IPython namespace
|
||||
short = reprlib.Repr()
|
||||
short.maxstring = short.maxother = 200
|
||||
rows = []
|
||||
for name, value in list(shell.user_ns.items()):
|
||||
if name.startswith("_") or name in shell.user_ns_hidden or isinstance(value, types.ModuleType):
|
||||
continue
|
||||
try:
|
||||
text = short.repr(value)
|
||||
except Exception as error: # a broken __repr__ must not hide the other variables
|
||||
text = "<repr failed: %s>" % type(error).__name__
|
||||
rows.append({"name": name, "type": type(value).__name__, "value": text})
|
||||
rows.sort(key=lambda row: row["name"])
|
||||
# Base64 so the expression's text/plain (a str repr) needs no unescaping.
|
||||
return base64.b64encode(json.dumps(rows).encode()).decode()
|
||||
@@ -80,6 +80,19 @@ pub fn agent_refresh_models(
|
||||
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_preview_copilot_models(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
account: String,
|
||||
model: Option<String>,
|
||||
) -> IdeResult<AgentModelCatalog> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
agents.preview_copilot_models(&account, model.as_deref()).await
|
||||
}
|
||||
|
||||
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
|
||||
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
|
||||
#[command(trust = trusted)]
|
||||
@@ -122,6 +135,39 @@ pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult<C
|
||||
}
|
||||
}
|
||||
|
||||
const REMOTE_SESSION_ENV_VARS: [&str; 5] =
|
||||
["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "CODESPACES", "REMOTE_CONTAINERS"];
|
||||
|
||||
fn prepare_login_launch_env(
|
||||
is_remote: bool,
|
||||
target_is_gh: bool,
|
||||
env: &mut std::collections::BTreeMap<String, String>,
|
||||
host_has: impl Fn(&str) -> bool,
|
||||
) {
|
||||
if !is_remote {
|
||||
return;
|
||||
}
|
||||
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
|
||||
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
|
||||
};
|
||||
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
|
||||
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
|
||||
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
|
||||
if !REMOTE_SESSION_ENV_VARS.iter().any(|key| has_non_empty(env, key)) {
|
||||
env.insert("REMOTE_CONTAINERS".into(), "1".into());
|
||||
}
|
||||
if target_is_gh && !has_non_empty(env, "GH_BROWSER") && !has_non_empty(env, "BROWSER") {
|
||||
env.insert("GH_BROWSER".into(), "true".into());
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_remote_login_env(host: &Host, cwd: &std::path::Path, target_is_gh: bool, launch: &mut LoginLaunch) {
|
||||
let cwd = if cwd.is_dir() { cwd.to_path_buf() } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
|
||||
prepare_login_launch_env(host.environment.is_remote(), target_is_gh, &mut launch.env, |key| {
|
||||
ide_core::process::host_var_os_in(&cwd, key).is_some_and(|v| !v.is_empty())
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn_login_pty(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -167,7 +213,7 @@ pub async fn agent_login_spawn(
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let (cwd, launch) = match host.project(window) {
|
||||
let (cwd, mut launch) = match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
@@ -186,6 +232,7 @@ pub async fn agent_login_spawn(
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
apply_remote_login_env(host, &cwd, false, &mut launch);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
@@ -204,7 +251,8 @@ pub async fn agent_gh_login_spawn(
|
||||
.project(window)
|
||||
.map(|p| p.root.clone())
|
||||
.unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir));
|
||||
let launch = host.blocking(ide_agent::gh_login_launch).await?;
|
||||
let mut launch = host.blocking(ide_agent::gh_login_launch).await?;
|
||||
apply_remote_login_env(host, &cwd, true, &mut launch);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
@@ -356,8 +404,9 @@ pub async fn agent_commands(
|
||||
host.project(window)?.agents.commands(&provider, task.as_deref()).await
|
||||
}
|
||||
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. Async so a long
|
||||
/// conversation is cloned and serialised off the main thread.
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. On the blocking pool:
|
||||
/// the first read of a saved conversation parses its task file, and a long one is cloned
|
||||
/// and serialised.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_entries(
|
||||
host: &Host,
|
||||
@@ -365,7 +414,8 @@ pub async fn agent_entries(
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<Vec<AgentEntry>> {
|
||||
host.project(window)?.agents.entries(&task, subagent)
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
host.blocking(move || agents.entries(&task, subagent)).await
|
||||
}
|
||||
|
||||
/// Sessions of the project on this machine that no task holds yet, newest first.
|
||||
@@ -1549,6 +1599,29 @@ mod tests {
|
||||
assert!(reloaded.approved(&root, "extra", &extra));
|
||||
assert!(!reloaded.approved(&tmp.path().join("other"), "extra", &extra));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
|
||||
let mut desktop_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
|
||||
assert!(desktop_env.is_empty());
|
||||
|
||||
let mut remote_agent_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
|
||||
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
|
||||
|
||||
let mut remote_gh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
|
||||
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
|
||||
|
||||
// Preserves existing SSH/remote indicators and explicit browser settings.
|
||||
let mut ssh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
|
||||
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
|
||||
assert!(!ssh_env.contains_key("GH_BROWSER"));
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
@@ -1584,6 +1657,7 @@ ide_command::domain!(
|
||||
agent_mcp_save_json,
|
||||
agent_mcp_set_enabled,
|
||||
agent_mcp_test,
|
||||
agent_preview_copilot_models,
|
||||
agent_probe,
|
||||
agent_prompt,
|
||||
agent_providers,
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::blocking;
|
||||
use ide_core::{IdeResult, IpcPath};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
|
||||
use ide_run::RunConfig;
|
||||
|
||||
@@ -35,9 +35,30 @@ pub async fn coverage_collect(host: &Host, window: &str, report: CoverageReportS
|
||||
/// with paths mapped into this project.
|
||||
#[command(trust = always)]
|
||||
pub async fn coverage_import(host: &Host, window: &str, path: IpcPath) -> IdeResult<CoverageSuite> {
|
||||
// Also reads a SimpleCov resultset.
|
||||
let root = host.project(window)?.root.clone();
|
||||
blocking(move || ide_coverage::import(&path, &root)).await
|
||||
// Also reads Cobertura XML, a SimpleCov resultset and coverage.py data files.
|
||||
let project = host.project(window)?;
|
||||
let (root, cache, config_dir) =
|
||||
(project.root.clone(), project.cache_dir.join("coverage-import"), host.config_dir.clone());
|
||||
let trusted = project.require_trust();
|
||||
blocking(move || {
|
||||
if !ide_coverage::is_data_file(&path) {
|
||||
return ide_coverage::import(&path, &root);
|
||||
}
|
||||
// coverage.py analyses the sources with the project's interpreter: that runs project code.
|
||||
trusted.map_err(|_| {
|
||||
IdeError::unavailable(
|
||||
"Reading a .coverage data file runs the project's Python. Trust the project, or import the output of `coverage xml`.",
|
||||
)
|
||||
})?;
|
||||
let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| {
|
||||
IdeError::unavailable(
|
||||
"Reading a .coverage data file needs the project's Python interpreter. Choose one, or import the output of `coverage xml`.",
|
||||
)
|
||||
})?;
|
||||
let out = ide_run::wrap::new_output_dir(&cache, KEEP_RUNS)?;
|
||||
ide_coverage::import_data(&path, &root, &python, &out)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(coverage: coverage_collect, coverage_import, coverage_prepare);
|
||||
@@ -8,8 +8,8 @@ use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
|
||||
use ide_db::split::SqlStatement;
|
||||
use ide_db::{
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode,
|
||||
QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange, HistoryEntry,
|
||||
PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -75,6 +75,20 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
// The project's user-created folders and their data source members.
|
||||
ide_db::source::load_folders(&host.project(window)?.root)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_save_source_folders(host: &Host, window: &str, folders: Vec<DbSourceFolder>) -> IdeResult<()> {
|
||||
// Replaces the project's data source folders; only grouping changes, never a source.
|
||||
let root = host.project(window)?.root.clone();
|
||||
ide_db::source::save_folders(&root, &folders)?;
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_save_source_visibility(
|
||||
host: &Host,
|
||||
@@ -612,7 +626,16 @@ pub fn db_consoles(host: &Host, id: String, create: bool) -> IdeResult<Vec<IpcPa
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
|
||||
/// The project view root for every data source's query consoles (`<dataDir>/consoles/db`).
|
||||
#[command(trust = always)]
|
||||
pub fn db_consoles_dir(host: &Host) -> IdeResult<IpcPath> {
|
||||
let dir = host.data_dir.join("consoles").join("db");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir.into())
|
||||
}
|
||||
|
||||
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database,
|
||||
/// `<id>.<database>` for the others.
|
||||
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
|
||||
let (source, database) = ide_db::split_target(id);
|
||||
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
|
||||
@@ -670,6 +693,7 @@ ide_command::domain!(
|
||||
db_connect,
|
||||
db_connected,
|
||||
db_console_path,
|
||||
db_consoles_dir,
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_database_catalog,
|
||||
@@ -692,6 +716,7 @@ ide_command::domain!(
|
||||
db_result_row,
|
||||
db_remove_history,
|
||||
db_retain_catalog,
|
||||
db_save_source_folders,
|
||||
db_save_source_visibility,
|
||||
db_save_sources,
|
||||
db_saved_catalog,
|
||||
@@ -701,6 +726,7 @@ ide_command::domain!(
|
||||
db_set_manual_commit,
|
||||
db_set_password,
|
||||
db_set_ssh_secret,
|
||||
db_source_folders,
|
||||
db_sources,
|
||||
db_statements,
|
||||
db_table_details,
|
||||
|
||||
@@ -60,7 +60,8 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
python.as_deref(),
|
||||
config.cwd.as_deref(),
|
||||
);
|
||||
super::python::prepare_debug(&mut config, &paths)?;
|
||||
let plots = super::plots::prepare(host, &project);
|
||||
super::python::prepare_debug(&mut config, &paths, plots.as_ref())?;
|
||||
}
|
||||
let label = window;
|
||||
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
|
||||
|
||||
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save(doc)).await?;
|
||||
host.blocking(move || {
|
||||
project.documents.save(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
|
||||
#[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?;
|
||||
let saved = host
|
||||
.blocking(move || {
|
||||
let saved = project.documents.autosave(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(saved)
|
||||
})
|
||||
.await?;
|
||||
if saved {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
|
||||
}
|
||||
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save_all()).await?;
|
||||
host.blocking(move || {
|
||||
let saved = project.documents.save_all();
|
||||
remember_saved_encodings(&project);
|
||||
saved
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use crate::project::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
|
||||
/// editor buffer, so syntax features and language-server requests work in it.
|
||||
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
|
||||
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
|
||||
}
|
||||
|
||||
/// Keeps the encoding the user chose for a project file in the project's File Encodings
|
||||
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
|
||||
/// until then its file is still in the old encoding. Nothing is kept for a document without
|
||||
/// a file in the project.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let info = project.documents.snapshot(doc)?;
|
||||
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
|
||||
return Ok(());
|
||||
}
|
||||
remember_encoding(&project, &info.path, &info.encoding)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Keeps the encodings of the converted documents a save has just written.
|
||||
pub(super) fn remember_saved_encodings(project: &Project) {
|
||||
for (path, encoding) in project.documents.take_saved_encodings() {
|
||||
if let Err(e) = remember_encoding(project, &path, &encoding) {
|
||||
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
|
||||
const MAPPINGS: &str = "editor.encodings.mappings";
|
||||
if project.light {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
|
||||
return Ok(());
|
||||
};
|
||||
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
|
||||
return Ok(());
|
||||
}
|
||||
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
|
||||
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
|
||||
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
|
||||
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
|
||||
@@ -118,7 +163,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
|
||||
}
|
||||
items
|
||||
}
|
||||
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
|
||||
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
|
||||
None => syntax(),
|
||||
})
|
||||
})
|
||||
@@ -263,6 +308,7 @@ ide_command::domain!(
|
||||
doc_outline,
|
||||
doc_python_facts,
|
||||
doc_rearrange,
|
||||
doc_remember_encoding,
|
||||
doc_selection_ranges,
|
||||
doc_set_bom,
|
||||
doc_set_encoding,
|
||||
|
||||
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
|
||||
f.sync().await;
|
||||
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
|
||||
|
||||
impl Fixture {
|
||||
fn project_settings(&self) -> PathBuf {
|
||||
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
|
||||
}
|
||||
|
||||
fn mappings_changed(&self) -> usize {
|
||||
let events = self.events.lock();
|
||||
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
assert!(!settings.exists());
|
||||
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
let written = std::fs::read_to_string(&settings).unwrap();
|
||||
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
// The same choice again leaves the file alone.
|
||||
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
|
||||
// A file outside the project has no place in the project's settings.
|
||||
let outside = f.open(&f.outside).await;
|
||||
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
|
||||
assert!(!settings.exists());
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
|
||||
|
||||
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&settings).unwrap(),
|
||||
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
|
||||
);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
// Later saves keep nothing more.
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", reopened.id).await.unwrap();
|
||||
let again = f.open(&f.path).await;
|
||||
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
|
||||
std::fs::write(&settings, "[editor\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
|
||||
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
|
||||
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
|
||||
assert_eq!(f.mappings_changed(), 0);
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
//! Docker run configurations: the environment their `docker` command line runs with; and Docker
|
||||
//! connections through an SSH configuration, tunnelled with the IDE's own SSH client.
|
||||
//! Services tool window › Docker (`ide-docker`) and Docker run configurations: run on the
|
||||
//! project host (`Host` locally, `openidea-server` in a remote window), with SSH connections
|
||||
//! tunnelled through the host's own SSH client.
|
||||
use super::Channel;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
use ide_docker::{
|
||||
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
|
||||
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
|
||||
};
|
||||
use ide_ssh::Tunnel;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
@@ -54,6 +59,242 @@ pub async fn disconnect(host: &Host, endpoint: &DockerEndpoint) {
|
||||
host.ssh.release(id);
|
||||
}
|
||||
|
||||
/// Runs a cancellable docker command (`request` → `cancel_request`) off the async workers.
|
||||
async fn cancellable<T: Send + 'static>(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
f: impl FnOnce(&CancellationToken) -> IdeResult<T> + Send + 'static,
|
||||
) -> IdeResult<T> {
|
||||
let cancel = host.begin_request(request);
|
||||
let result = host.blocking(move || f(&cancel)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Closes the connection's SSH tunnel and, when nothing else uses it, its SSH connection
|
||||
/// (Services › Disconnect); other endpoints keep nothing open.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_disconnect(host: &Host, endpoint: DockerEndpoint) -> IdeResult<()> {
|
||||
disconnect(host, &endpoint).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Availability plus containers, images, volumes and networks.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_snapshot(host: &Host, endpoint: DockerEndpoint) -> IdeResult<DockerSnapshot> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || Ok(ide_docker::snapshot(&endpoint))).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_op(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
ids: Vec<String>,
|
||||
op: ContainerOp,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_remove(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
object: DockerObject,
|
||||
ids: Vec<String>,
|
||||
force: bool,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::remove(&endpoint, object, &ids, force)).await
|
||||
}
|
||||
|
||||
/// Pretty-printed `docker inspect` JSON.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_inspect(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
object: DockerObject,
|
||||
id: String,
|
||||
) -> IdeResult<String> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::inspect(&endpoint, object, &id)).await
|
||||
}
|
||||
|
||||
/// Layers of an image (`docker image history`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_image_history(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
) -> IdeResult<Vec<DockerImageLayer>> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::image_history(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Processes running inside a container (`docker top`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_top(host: &Host, endpoint: DockerEndpoint, id: String) -> IdeResult<DockerProcessList> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_top(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_container_stats(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
) -> IdeResult<DockerContainerStats> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await
|
||||
}
|
||||
|
||||
/// Disk usage per volume name (`docker system df -v`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_volume_sizes(host: &Host, endpoint: DockerEndpoint) -> IdeResult<BTreeMap<String, String>> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
host.blocking(move || ide_docker::volume_sizes(&endpoint)).await
|
||||
}
|
||||
|
||||
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn docker_logs(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
id: String,
|
||||
tail: u32,
|
||||
follow: bool,
|
||||
timestamps: bool,
|
||||
on_lines: Channel<Vec<DockerLogLine>>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| {
|
||||
let _ = on_lines.send(lines);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Follows `docker events` until the daemon goes away or the request is cancelled.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_events(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
on_event: Channel<DockerEvent>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::watch_events(&endpoint, cancel, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// `docker pull`, logging in first when a saved registry with a password serves the image.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_pull(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
reference: String,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
let data_dir = host.data_dir.clone();
|
||||
cancellable(host, request, move |cancel| {
|
||||
let auth = ide_docker::auth_for(&data_dir, &reference);
|
||||
ide_docker::pull(&endpoint, &reference, auth.as_ref(), cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_prune(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
target: PruneTarget,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::prune(&endpoint, target, cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// `docker compose` start / stop / restart / down of a project found through labels.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn docker_compose_op(
|
||||
host: &Host,
|
||||
request: RequestId,
|
||||
endpoint: DockerEndpoint,
|
||||
project: String,
|
||||
files: Vec<String>,
|
||||
working_dir: Option<String>,
|
||||
op: ComposeOp,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
cancellable(host, request, move |cancel| {
|
||||
ide_docker::compose_op(&endpoint, &project, &files, working_dir.as_deref(), op, cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Docker connections and registries of the project host.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_settings(host: &Host) -> IdeResult<DockerSettings> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || Ok(ide_docker::load_settings(&data_dir))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_save_settings(host: &Host, settings: DockerSettings) -> IdeResult<()> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || ide_docker::save_settings(&data_dir, &settings)).await
|
||||
}
|
||||
|
||||
/// Saves (`None`: forgets) a registry's password.
|
||||
#[command(trust = always)]
|
||||
pub async fn docker_set_registry_password(host: &Host, id: String, password: Option<String>) -> IdeResult<()> {
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || ide_docker::set_registry_password(&data_dir, &id, password.as_deref())).await
|
||||
}
|
||||
|
||||
/// Test login to `registry` (`password`, else the saved one) through `endpoint`'s daemon.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn docker_registry_login(
|
||||
host: &Host,
|
||||
endpoint: DockerEndpoint,
|
||||
registry: DockerRegistry,
|
||||
password: Option<String>,
|
||||
) -> IdeResult<String> {
|
||||
let endpoint = resolve(host, endpoint).await?;
|
||||
let data_dir = host.data_dir.clone();
|
||||
host.blocking(move || {
|
||||
let password = password
|
||||
.or_else(|| ide_docker::registry_password(&data_dir, ®istry.id))
|
||||
.ok_or_else(|| IdeError::invalid("enter the registry password"))?;
|
||||
let auth = RegistryAuth { address: registry.address, username: registry.username, password };
|
||||
ide_docker::login(&endpoint, &auth)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Environment for a Docker run configuration's command line: selects `endpoint`'s
|
||||
/// daemon and puts the docker executable on `PATH`.
|
||||
#[command(trust = always)]
|
||||
@@ -64,4 +305,25 @@ pub async fn docker_run_env(host: &Host, endpoint: DockerEndpoint) -> IdeResult<
|
||||
host.blocking(move || Ok(ide_docker::run_env(&endpoint))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(docker: docker_run_env);
|
||||
ide_command::domain!(
|
||||
docker:
|
||||
docker_compose_op,
|
||||
docker_container_op,
|
||||
docker_container_stats,
|
||||
docker_container_top,
|
||||
docker_disconnect,
|
||||
docker_events,
|
||||
docker_image_history,
|
||||
docker_inspect,
|
||||
docker_logs,
|
||||
docker_prune,
|
||||
docker_pull,
|
||||
docker_registry_login,
|
||||
docker_remove,
|
||||
docker_run_env,
|
||||
docker_save_settings,
|
||||
docker_set_registry_password,
|
||||
docker_settings,
|
||||
docker_snapshot,
|
||||
docker_volume_sizes,
|
||||
);
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Host resource metrics (`host_metrics`, `host_end_process`) for the Remote Host
|
||||
//! Resources status bar widget and popover dashboard.
|
||||
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
|
||||
use ide_workspace::system::SystemSampler;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct HostMetricsSampler {
|
||||
system: SystemSampler,
|
||||
cpu: CpuSampler,
|
||||
}
|
||||
|
||||
/// One process outside OpenIDEA's own process tree on the host (read-only in the UI).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostProcess {
|
||||
pub pid: u32,
|
||||
pub name: String,
|
||||
pub cpu_percent: Option<f32>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
/// Snapshot of host-wide CPU, memory, network, disk and process usage.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct HostMetrics {
|
||||
/// Overall CPU utilization across all logical cores (`0..=100`); `null` on the first sample.
|
||||
pub cpu_percent: Option<f32>,
|
||||
/// Logical CPU cores available to this host or container.
|
||||
pub cpu_cores: u32,
|
||||
/// Unix 1m, 5m, 15m load averages; `null` on Windows.
|
||||
pub load_average: Option<[f32; 3]>,
|
||||
/// Host or container memory in use, in bytes.
|
||||
pub memory_used_bytes: Option<u64>,
|
||||
/// Total physical (or container limit) memory, in bytes.
|
||||
pub memory_total_bytes: Option<u64>,
|
||||
/// Bytes/s received across non-loopback network interfaces; `null` on the first sample or unsupported OS.
|
||||
pub net_rx_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s sent across non-loopback network interfaces; `null` on the first sample or unsupported OS.
|
||||
pub net_tx_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s read from block storage; `null` on the first sample or unsupported OS.
|
||||
pub disk_read_bytes_per_sec: Option<f64>,
|
||||
/// Bytes/s written to block storage; `null` on the first sample or unsupported OS.
|
||||
pub disk_write_bytes_per_sec: Option<f64>,
|
||||
/// Free bytes available to the user on the project volume (or `$HOME` fallback).
|
||||
pub disk_available_bytes: Option<u64>,
|
||||
/// Total capacity in bytes of the project volume (or `$HOME` fallback).
|
||||
pub disk_total_bytes: Option<u64>,
|
||||
/// Uptime of the backend process in milliseconds.
|
||||
pub uptime_ms: f64,
|
||||
/// OpenIDEA backend, language servers, runs, terminals, debug adapters and agents (`includeProcesses = true`).
|
||||
pub processes: Vec<ProcessMemory>,
|
||||
/// Highest-usage processes on the host outside OpenIDEA's own process tree (`includeProcesses = true`).
|
||||
pub external_processes: Vec<HostProcess>,
|
||||
}
|
||||
|
||||
const MAX_EXTERNAL_PROCESSES: usize = 5;
|
||||
const MIN_EXTERNAL_CPU_PERCENT: f32 = 0.5;
|
||||
const MIN_EXTERNAL_MEMORY_BYTES: u64 = 32 << 20;
|
||||
|
||||
fn project_name(root: &Path) -> String {
|
||||
root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string())
|
||||
}
|
||||
|
||||
fn process_root(pid: u32, label: String, kind: &str) -> MemoryRoot {
|
||||
MemoryRoot { pid, category: MemoryCategory::Process, label, detail: Some(kind.into()), with_children: true }
|
||||
}
|
||||
|
||||
fn volume_path(host: &Host, window: &str) -> PathBuf {
|
||||
if let Ok(p) = host.project(window) {
|
||||
return p.root.clone();
|
||||
}
|
||||
if let Some(p) = host.projects().into_iter().next() {
|
||||
return p.root.clone();
|
||||
}
|
||||
dirs::home_dir().unwrap_or_else(|| host.data_dir.clone())
|
||||
}
|
||||
|
||||
fn disk_space(path: &Path) -> Option<(u64, u64)> {
|
||||
#[cfg(unix)]
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
{
|
||||
let stat = rustix::fs::statvfs(path).ok()?;
|
||||
let frsize = stat.f_frsize as u64;
|
||||
let total = (stat.f_blocks as u64).saturating_mul(frsize);
|
||||
let avail = (stat.f_bavail as u64).saturating_mul(frsize);
|
||||
(total > 0).then_some((avail.min(total), total))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
|
||||
let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64);
|
||||
// SAFETY: `wide` is NUL-terminated and all three u64 out-pointers are writable.
|
||||
let ok = unsafe {
|
||||
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
|
||||
wide.as_ptr(),
|
||||
&mut avail,
|
||||
&mut total,
|
||||
&mut free,
|
||||
)
|
||||
};
|
||||
(ok != 0 && total > 0).then_some((avail.min(total), total))
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
let _ = path;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_roots(host: &Host) -> Vec<MemoryRoot> {
|
||||
let mut roots = Vec::new();
|
||||
for p in host.projects() {
|
||||
for s in p.lsp.servers() {
|
||||
if let Some(pid) = s.pid {
|
||||
roots.push(MemoryRoot {
|
||||
pid,
|
||||
category: MemoryCategory::LanguageServer,
|
||||
label: s.name,
|
||||
detail: Some(project_name(s.root.as_ref())),
|
||||
with_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for r in host.processes.list().into_iter().filter(|r| r.running) {
|
||||
if let Some(pid) = r.pid {
|
||||
roots.push(process_root(pid, r.name, "Run"));
|
||||
}
|
||||
}
|
||||
for t in host.terminals.list() {
|
||||
if let Some(pid) = t.pid {
|
||||
roots.push(process_root(pid, t.title, "Terminal"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn resource_share(p: &HostProcess, cores: u32, total_memory: Option<u64>) -> f64 {
|
||||
let cpu_share = p.cpu_percent.map(|c| c as f64 / (cores.max(1) as f64 * 100.0)).unwrap_or(0.0);
|
||||
let mem_share = match (p.memory_bytes, total_memory.filter(|&t| t > 0)) {
|
||||
(Some(b), Some(t)) => b as f64 / t as f64,
|
||||
_ => 0.0,
|
||||
};
|
||||
cpu_share.max(mem_share)
|
||||
}
|
||||
|
||||
/// Snapshot of host-wide resource counters (CPU, memory, network, disk) and, when
|
||||
/// `include_processes` is true, the process breakdown of OpenIDEA and top host processes.
|
||||
#[command(trust = always)]
|
||||
pub async fn host_metrics(host: &Arc<Host>, window: &str, include_processes: bool) -> IdeResult<HostMetrics> {
|
||||
let disk_target = volume_path(host, window);
|
||||
let roots = if include_processes { collect_roots(host) } else { Vec::new() };
|
||||
let h = host.clone();
|
||||
host.blocking(move || {
|
||||
let table = include_processes.then(ProcessTable::snapshot);
|
||||
let (disk_available_bytes, disk_total_bytes) = match disk_space(&disk_target) {
|
||||
Some((a, t)) => (Some(a), Some(t)),
|
||||
None => (None, None),
|
||||
};
|
||||
let uptime_ms =
|
||||
ide_workspace::process::process_age().unwrap_or_else(ide_workspace::process::uptime).as_secs_f64() * 1000.0;
|
||||
|
||||
let mut sampler = h.metrics_sampler.lock();
|
||||
let rates = sampler.system.sample();
|
||||
|
||||
let (processes, external_processes) = if let Some(table) = table {
|
||||
sampler.cpu.retain(&table);
|
||||
let me = std::process::id();
|
||||
let processes =
|
||||
memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| sampler.cpu.percent(pid));
|
||||
let claimed: HashSet<u32> = table.tree(me).into_iter().collect();
|
||||
let mut external: Vec<HostProcess> = table
|
||||
.entries()
|
||||
.filter(|e| e.pid != 0 && !claimed.contains(&e.pid))
|
||||
.filter_map(|e| {
|
||||
let cpu_percent = sampler.cpu.percent(e.pid);
|
||||
let memory_bytes = memory::fast_resident_bytes(e.pid);
|
||||
let active = cpu_percent.unwrap_or(0.0) >= MIN_EXTERNAL_CPU_PERCENT
|
||||
|| memory_bytes.unwrap_or(0) >= MIN_EXTERNAL_MEMORY_BYTES;
|
||||
active.then(|| HostProcess { pid: e.pid, name: e.name.clone(), cpu_percent, memory_bytes })
|
||||
})
|
||||
.collect();
|
||||
external.sort_by(|a, b| {
|
||||
resource_share(b, rates.cpu_cores, rates.memory_total_bytes)
|
||||
.total_cmp(&resource_share(a, rates.cpu_cores, rates.memory_total_bytes))
|
||||
.then_with(|| b.memory_bytes.unwrap_or(0).cmp(&a.memory_bytes.unwrap_or(0)))
|
||||
.then_with(|| a.pid.cmp(&b.pid))
|
||||
});
|
||||
external.truncate(MAX_EXTERNAL_PROCESSES);
|
||||
(processes, external)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
|
||||
Ok(HostMetrics {
|
||||
cpu_percent: rates.cpu_percent,
|
||||
cpu_cores: rates.cpu_cores,
|
||||
load_average: rates.load_average,
|
||||
memory_used_bytes: rates.memory_used_bytes,
|
||||
memory_total_bytes: rates.memory_total_bytes,
|
||||
net_rx_bytes_per_sec: rates.net_rx_bytes_per_sec,
|
||||
net_tx_bytes_per_sec: rates.net_tx_bytes_per_sec,
|
||||
disk_read_bytes_per_sec: rates.disk_read_bytes_per_sec,
|
||||
disk_write_bytes_per_sec: rates.disk_write_bytes_per_sec,
|
||||
disk_available_bytes,
|
||||
disk_total_bytes,
|
||||
uptime_ms,
|
||||
processes,
|
||||
external_processes,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Ends a child process started by this OpenIDEA host (language server, run, terminal,
|
||||
/// debug adapter or agent) and its descendants; refuses processes outside this host's tree.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn host_end_process(host: &Arc<Host>, pid: u32) -> IdeResult<bool> {
|
||||
host.blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, Duration::from_secs(3)))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(host_metrics: host_metrics, host_end_process);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::HostConfig;
|
||||
|
||||
#[tokio::test]
|
||||
async fn collects_light_and_detailed_host_metrics() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let host = Arc::new(Host::new(HostConfig::for_test(dir.path())));
|
||||
|
||||
let light = host_metrics(&host, "main", false).await.unwrap();
|
||||
assert!(light.cpu_cores >= 1);
|
||||
assert!(light.processes.is_empty());
|
||||
assert!(light.external_processes.is_empty());
|
||||
if cfg!(any(unix, windows)) {
|
||||
let avail = light.disk_available_bytes.expect("disk_available_bytes");
|
||||
let total = light.disk_total_bytes.expect("disk_total_bytes");
|
||||
assert!(total > 0 && avail <= total, "{avail} / {total}");
|
||||
}
|
||||
|
||||
let detailed = host_metrics(&host, "main", true).await.unwrap();
|
||||
assert!(!detailed.processes.is_empty());
|
||||
assert_eq!(detailed.processes[0].label, "Backend");
|
||||
assert!(detailed.external_processes.len() <= MAX_EXTERNAL_PROCESSES);
|
||||
|
||||
// Refuses to terminate the backend itself or PID 1.
|
||||
assert!(!host_end_process(&host, std::process::id()).await.unwrap());
|
||||
assert!(!host_end_process(&host, 1).await.unwrap());
|
||||
}
|
||||
}
|
||||
@@ -1881,6 +1881,29 @@ pub async fn lsp_snapshot_diagnostics(
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_snapshot_completion(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: std::path::PathBuf,
|
||||
text: String,
|
||||
pos: Pos,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<CompletionItem>> {
|
||||
let project = host.project(window)?;
|
||||
if !path.is_absolute() || path.file_name().is_none() {
|
||||
return Err(IdeError::invalid("a text snapshot requires a file path"));
|
||||
}
|
||||
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let language = project.documents.language_of(&path, text.lines().next()).language;
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = project.lsp.snapshot_completion(&path, &language, &text, pos, &cancel).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
@@ -3236,6 +3259,7 @@ ide_command::domain!(
|
||||
lsp_extract_interface_info,
|
||||
lsp_format,
|
||||
lsp_format_text,
|
||||
lsp_snapshot_completion,
|
||||
lsp_snapshot_diagnostics,
|
||||
lsp_source_action_text,
|
||||
lsp_goto,
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod flutter;
|
||||
pub mod fs;
|
||||
pub mod heap;
|
||||
pub mod history;
|
||||
pub mod host_metrics;
|
||||
pub mod http;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
@@ -26,7 +27,9 @@ pub mod lsp;
|
||||
pub mod maven_placeholder;
|
||||
pub mod nav;
|
||||
pub mod notebook;
|
||||
mod plots;
|
||||
pub mod project;
|
||||
pub mod pytest_fixtures;
|
||||
mod python;
|
||||
pub mod python_stubs;
|
||||
pub mod refactor;
|
||||
@@ -93,6 +96,7 @@ ide_command::domains!(
|
||||
fs: crate::ops::fs,
|
||||
heap: crate::ops::heap,
|
||||
history: crate::ops::history,
|
||||
host_metrics: crate::ops::host_metrics,
|
||||
http: crate::ops::http,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use super::blocking;
|
||||
use super::pytest_fixtures::{PytestFixtureAt, PytestFixtureUsages, fixture_at, fixture_usages, rename_fixture};
|
||||
use super::python_stubs::{
|
||||
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
|
||||
};
|
||||
use crate::Host;
|
||||
use crate::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId, WorkspaceEdit};
|
||||
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
|
||||
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
|
||||
use ide_workspace::file_refs::{self, PathCompletion};
|
||||
@@ -478,6 +479,78 @@ pub async fn nav_python_stubs(host: &Host, window: &str, doc: DocId) -> IdeResul
|
||||
.await
|
||||
}
|
||||
|
||||
/// pytest fixtures at `pos` of a Python document: the definition pytest uses for the fixture
|
||||
/// named there (a test's parameter, a `usefixtures` / `getfixturevalue` string), and the
|
||||
/// fixtures visible where a fixture name goes, for completion.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<PytestFixtureAt> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.large || snap.language.as_str() != "python" {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
Ok(fixture_at(&project, &syntax, &snap.path, &snap.text, pos))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Find Usages of the pytest fixture at `pos` (its definition, or a place asking for it): every
|
||||
/// test and fixture parameter, `usefixtures` and `getfixturevalue` string that gets it.
|
||||
/// None when `pos` names no fixture. Cancellable.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixture_usages(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Option<PytestFixtureUsages>> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.large || snap.language.as_str() != "python" {
|
||||
return Ok(None);
|
||||
}
|
||||
fixture_usages(&project, &syntax, &snap.path, &snap.text, pos, &|| token.is_cancelled())
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Rename of the pytest fixture at `pos`: its definition, every place that gets it and the
|
||||
/// uses of those parameters in their functions. Cancellable.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_pytest_fixture_rename(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
new_name: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let mut edit =
|
||||
rename_fixture(&project, &syntax, &snap.path, &snap.text, pos, &new_name, &|| token.is_cancelled())?;
|
||||
if token.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut edit)?;
|
||||
Ok(edit)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
nav:
|
||||
find_dirs,
|
||||
@@ -491,6 +564,9 @@ ide_command::domain!(
|
||||
mark_recent,
|
||||
nav_index_definitions,
|
||||
nav_inheritance,
|
||||
nav_pytest_fixture_rename,
|
||||
nav_pytest_fixture_usages,
|
||||
nav_pytest_fixtures,
|
||||
nav_python_stubs,
|
||||
nav_resolve_module,
|
||||
path_completions,
|
||||
|
||||
@@ -93,6 +93,18 @@ pub async fn notebook_interrupt(host: &Host, window: &str, id: String) -> IdeRes
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn notebook_variables(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
) -> IdeResult<Option<Vec<crate::notebook::NotebookVariable>>> {
|
||||
let notebooks = host.project(window)?.notebooks.clone();
|
||||
tokio::spawn(async move { notebooks.variables(&id).await })
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn notebook_execute(
|
||||
@@ -162,4 +174,5 @@ ide_command::domain!(
|
||||
notebook_restart,
|
||||
notebook_save,
|
||||
notebook_undo,
|
||||
notebook_variables,
|
||||
);
|
||||
@@ -0,0 +1,66 @@
|
||||
//! The Plots tool window: matplotlib figures that Python runs and debug sessions save (see
|
||||
//! [`ide_run::plots`]) reach the window as [`IdeEvent::PlotAdded`].
|
||||
use crate::Host;
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeEvent;
|
||||
use ide_run::plots::Plots;
|
||||
use notify::{RecursiveMode, Watcher};
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
/// The backend and plots folder for a Python run of `project`, installed and watched on first use;
|
||||
/// `None` when Settings › Python turns the tool window off.
|
||||
pub(crate) fn prepare(host: &Host, project: &Project) -> Option<Plots> {
|
||||
if !project.settings.effective().languages.python.show_plots_in_tool_window {
|
||||
return None;
|
||||
}
|
||||
let plots = Plots { backend: host.local_data_dir.join("matplotlib-backend"), dir: project.cache_dir.join("plots") };
|
||||
match ide_run::plots::install(&plots.backend).and_then(|()| watch(project, &plots.dir)) {
|
||||
Ok(()) => Some(plots),
|
||||
Err(e) => {
|
||||
tracing::warn!("cannot set up the Plots tool window in {}: {e}", plots.dir.display());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn watch(project: &Project, dir: &Path) -> io::Result<()> {
|
||||
let mut slot = project.plots_watch.lock();
|
||||
if slot.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
// Figures of an earlier session are not shown again.
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let sink = project.sink.clone();
|
||||
// Every event of a finished PNG is sent (create, rename, modify); the window keeps each path once.
|
||||
let mut watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
|
||||
for path in res.map(|e| e.paths).unwrap_or_default() {
|
||||
if is_plot(&path) && path.is_file() {
|
||||
sink.emit(IdeEvent::PlotAdded { path: path.to_string_lossy().into_owned() });
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(io::Error::other)?;
|
||||
watcher.watch(dir, RecursiveMode::NonRecursive).map_err(io::Error::other)?;
|
||||
*slot = Some(watcher);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A finished figure: the backend writes `.<name>.png` first, then renames it.
|
||||
fn is_plot(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e == "png")
|
||||
&& path.file_name().is_some_and(|n| !n.to_string_lossy().starts_with('.'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_finished_pngs_are_plots() {
|
||||
assert!(is_plot(Path::new("/c/plots/1-2-0.png")));
|
||||
assert!(!is_plot(Path::new("/c/plots/.1-2-0.png")));
|
||||
assert!(!is_plot(Path::new("/c/plots/notes.txt")));
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,22 @@ pub fn settings_removed_theme(host: &Host, window: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a changed setting `key` starts or stops right away. Both `settings_set` commands (this
|
||||
/// crate's and the desktop's) call it after writing the value.
|
||||
pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
|
||||
/// value: that project's windows) is told (`IdeEvent::SettingsChanged`) so it
|
||||
/// re-reads its effective settings.
|
||||
@@ -122,17 +138,7 @@ pub fn settings_set(
|
||||
value: String,
|
||||
) -> IdeResult<Settings> {
|
||||
let applied = set_settings(host, window, scope, &key, &value)?;
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(&key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
apply_setting(host, window, &key);
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key });
|
||||
if let Some(root) = applied.roots_changed {
|
||||
@@ -448,6 +454,14 @@ pub fn set_settings(
|
||||
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
|
||||
host.apply_git_executable();
|
||||
}
|
||||
if key == "vcs" || key == "vcs.github" || key.starts_with("vcs.github.") {
|
||||
let affected = affected();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
for project in affected {
|
||||
crate::github_auth::apply_to_project(&project);
|
||||
}
|
||||
});
|
||||
}
|
||||
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
|
||||
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
|
||||
for project in affected() {
|
||||
@@ -524,11 +538,56 @@ pub fn set_settings(
|
||||
Ok(SettingsApplied { settings: host.with_proxy_password(settings), project_scope, roots_changed })
|
||||
}
|
||||
|
||||
/// Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_project_account_status(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let current = host.project(window).ok().filter(|p| !p.light);
|
||||
let global_account = host.global_settings.effective().vcs.github.account;
|
||||
host.blocking(move || match current {
|
||||
Some(project) => Ok(crate::github_auth::project_status(&project)),
|
||||
None => Ok(crate::github_auth::global_status(global_account)),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Sets `vcs.github.account` for `window`'s project (or globally when no project is open),
|
||||
/// updates the project's `GH_TOKEN` environment immediately, and returns the updated status.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_set_project_account(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
account: String,
|
||||
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let trimmed = account.trim().to_owned();
|
||||
if !trimmed.is_empty() && !crate::github_auth::is_valid_github_login(&trimmed) {
|
||||
return Err(ide_core::IdeError::invalid(format!("invalid GitHub account login: {trimmed}")));
|
||||
}
|
||||
let current = host.project(window).ok().filter(|p| !p.light);
|
||||
let scope = if current.is_some() { SettingsScope::Project } else { SettingsScope::Global };
|
||||
let json = serde_json::to_string(&trimmed).map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
|
||||
set_settings(host, window, scope, "vcs.github.account", &json)?;
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key: "vcs.github.account".into() });
|
||||
let global_account = host.global_settings.effective().vcs.github.account;
|
||||
host.blocking(move || match current {
|
||||
Some(project) => Ok(crate::github_auth::project_status(&project)),
|
||||
None => Ok(crate::github_auth::global_status(global_account)),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
project:
|
||||
cancel_request,
|
||||
cancel_task,
|
||||
close_project,
|
||||
gh_project_account_status,
|
||||
gh_set_project_account,
|
||||
open_project,
|
||||
project_current,
|
||||
project_roots,
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
//! pytest fixtures across files: the modules a test file sees, nearest first (the file, its
|
||||
//! `conftest.py` files up to the project root, the modules `pytest_plugins` names, installed
|
||||
//! plugins' `pytest11` entry points, pytest's own `_pytest` package), for Go to Declaration
|
||||
//! and completion of fixture names.
|
||||
|
||||
use super::python_stubs::site_packages;
|
||||
use crate::Project;
|
||||
use ide_core::{FileEdit, IdeError, IdeResult, IpcPath, LanguageId, Location, Pos, Range, TextEdit, WorkspaceEdit};
|
||||
use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureAt {
|
||||
/// The fixture name at the position, and the definition pytest uses for it.
|
||||
pub reference: Option<PytestFixtureReference>,
|
||||
/// At a place a fixture name goes (a test's parameters, a `usefixtures` string): the
|
||||
/// fixtures visible there, nearest first.
|
||||
pub completions: Option<Vec<PytestFixtureItem>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureReference {
|
||||
pub name: String,
|
||||
pub range: Range,
|
||||
/// None when no visible module defines it (`request`, a fixture from a hook).
|
||||
pub definition: Option<Location>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureItem {
|
||||
pub name: String,
|
||||
/// The file defining it.
|
||||
pub path: IpcPath,
|
||||
}
|
||||
|
||||
/// Fixtures at `pos` of the Python document `path` / `text`.
|
||||
pub(crate) fn fixture_at(project: &Project, syntax: &Syntax, path: &Path, text: &str, pos: Pos) -> PytestFixtureAt {
|
||||
let own = syntax.pytest_module(&python(), text);
|
||||
let usage = own.use_at(pos).cloned();
|
||||
let slot = own.slot_at(pos).cloned();
|
||||
if usage.is_none() && slot.is_none() {
|
||||
return PytestFixtureAt::default();
|
||||
}
|
||||
let layers = Scope::new(project).layers(project, syntax, path, Arc::new(own));
|
||||
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
|
||||
let reference = usage.map(|u| {
|
||||
let found = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name));
|
||||
PytestFixtureReference {
|
||||
definition: found.map(|(l, f)| Location {
|
||||
path: IpcPath::from(layers[l].0.clone()),
|
||||
range: modules[l].fixtures[f].selection,
|
||||
uri: None,
|
||||
}),
|
||||
name: u.name,
|
||||
range: u.range,
|
||||
}
|
||||
});
|
||||
let completions = slot.map(|s| {
|
||||
visible_fixtures(&modules, s.class.as_deref())
|
||||
.into_iter()
|
||||
// `_name` fixtures are internal, as `pytest --fixtures` hides them.
|
||||
.filter(|&(l, f)| !modules[l].fixtures[f].name.starts_with('_'))
|
||||
.map(|(l, f)| PytestFixtureItem {
|
||||
name: modules[l].fixtures[f].name.clone(),
|
||||
path: IpcPath::from(layers[l].0.clone()),
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
PytestFixtureAt { reference, completions }
|
||||
}
|
||||
|
||||
fn python() -> LanguageId {
|
||||
LanguageId::new("python")
|
||||
}
|
||||
|
||||
type Layer = (PathBuf, Arc<PytestModule>);
|
||||
|
||||
/// What every file of the project sees after its own `conftest.py` files: the folders
|
||||
/// `pytest_plugins` modules are found in, installed plugins and pytest's own modules.
|
||||
struct Scope {
|
||||
search: Vec<PathBuf>,
|
||||
tail: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
fn new(project: &Project) -> Self {
|
||||
let packages = interpreter_site_packages(project);
|
||||
let mut search = super::python::paths(project);
|
||||
search.extend(packages.iter().cloned());
|
||||
// `pytest_plugins = ["pytester"]` names pytest's own optional plugins by their short name.
|
||||
search.extend(packages.iter().map(|p| p.join("_pytest")));
|
||||
let mut tail = Vec::new();
|
||||
for packages in &packages {
|
||||
tail.extend(
|
||||
entry_point_modules(packages).iter().filter_map(|m| module_file(m, std::slice::from_ref(packages))),
|
||||
);
|
||||
}
|
||||
for packages in &packages {
|
||||
tail.extend(builtin_modules(&packages.join("_pytest")));
|
||||
}
|
||||
Self { search, tail }
|
||||
}
|
||||
|
||||
/// The modules `path` sees, nearest first, `own` being its own: its `conftest.py` files up to
|
||||
/// the project root, the modules their `pytest_plugins` name, then installed plugins and pytest.
|
||||
fn layers(&self, project: &Project, syntax: &Syntax, path: &Path, own: Arc<PytestModule>) -> Vec<Layer> {
|
||||
let mut out: Vec<Layer> = vec![(path.to_path_buf(), own)];
|
||||
let mut dir = path.parent();
|
||||
while let Some(d) = dir.filter(|d| d.starts_with(&project.root)) {
|
||||
let conftest = d.join("conftest.py");
|
||||
if conftest != path
|
||||
&& let Some(m) = module_of(project, syntax, &conftest)
|
||||
{
|
||||
out.push((conftest, m));
|
||||
}
|
||||
dir = d.parent();
|
||||
}
|
||||
let named: Vec<String> = out.iter().flat_map(|(_, m)| m.plugins.clone()).collect();
|
||||
let extra =
|
||||
named.iter().filter_map(|module| module_file(module, &self.search)).chain(self.tail.iter().cloned());
|
||||
for file in extra.collect::<Vec<_>>() {
|
||||
if !out.iter().any(|(p, _)| *p == file)
|
||||
&& let Some(m) = module_of(project, syntax, &file)
|
||||
{
|
||||
out.push((file, m));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A fixture definition: its file and the range of its name there.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct Definition {
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
selection: Range,
|
||||
}
|
||||
|
||||
/// Where pytest finds the fixture `u` asks for, seen from `layers`.
|
||||
fn definition_of(layers: &[Layer], u: &ide_language::PytestFixtureUse) -> Option<Definition> {
|
||||
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
|
||||
let (l, f) = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name))?;
|
||||
Some(Definition { name: u.name.clone(), path: layers[l].0.clone(), selection: modules[l].fixtures[f].selection })
|
||||
}
|
||||
|
||||
/// The fixture at `pos` of `path`: the one defined there, or the one a test asks for there.
|
||||
fn target_at(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
scope: &Scope,
|
||||
path: &Path,
|
||||
own: &Arc<PytestModule>,
|
||||
pos: Pos,
|
||||
) -> Option<Definition> {
|
||||
if let Some(f) = own.definition_at(pos) {
|
||||
let fixture = &own.fixtures[f];
|
||||
return Some(Definition { name: fixture.name.clone(), path: path.to_path_buf(), selection: fixture.selection });
|
||||
}
|
||||
let usage = own.use_at(pos)?;
|
||||
definition_of(&scope.layers(project, syntax, path, own.clone()), usage)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PytestFixtureUsages {
|
||||
pub name: String,
|
||||
pub definition: Location,
|
||||
/// Defined in the project (not by a plugin or pytest): it may be renamed.
|
||||
pub in_project: bool,
|
||||
/// Every place that gets this fixture: parameters, `usefixtures` and `getfixturevalue` strings.
|
||||
pub usages: Vec<Location>,
|
||||
}
|
||||
|
||||
struct Usage {
|
||||
path: PathBuf,
|
||||
use_: ide_language::PytestFixtureUse,
|
||||
}
|
||||
|
||||
/// The fixture at `pos` of the Python document `path` / `text` and every place that gets it.
|
||||
pub(crate) fn fixture_usages(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<Option<PytestFixtureUsages>> {
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else { return Ok(None) };
|
||||
Ok(Some(PytestFixtureUsages {
|
||||
name: target.name.clone(),
|
||||
in_project: is_project_file(project, &target.path),
|
||||
definition: Location { path: IpcPath::from(target.path), range: target.selection, uri: None },
|
||||
usages: usages
|
||||
.into_iter()
|
||||
.map(|u| Location { path: IpcPath::from(u.path), range: u.use_.range, uri: None })
|
||||
.collect(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Rename of the fixture at `pos`: its definition (the `name=` string, else the function name),
|
||||
/// every place that gets it, and the uses of a renamed parameter in its function's body.
|
||||
pub(crate) fn rename_fixture(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
new_name: &str,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<WorkspaceEdit> {
|
||||
let Some((target, usages)) = usages_of(project, syntax, path, text, pos, cancelled)? else {
|
||||
return Err(IdeError::invalid("No pytest fixture here"));
|
||||
};
|
||||
if !is_project_file(project, &target.path) {
|
||||
return Err(IdeError::invalid("The fixture is defined outside the project"));
|
||||
}
|
||||
let mut by_file: Vec<(PathBuf, Vec<TextEdit>)> = Vec::new();
|
||||
let mut edit = |file: &Path, range: Range| {
|
||||
let edits = match by_file.iter_mut().find(|(p, _)| p == file) {
|
||||
Some((_, edits)) => edits,
|
||||
None => {
|
||||
by_file.push((file.to_path_buf(), Vec::new()));
|
||||
&mut by_file.last_mut().expect("just pushed").1
|
||||
}
|
||||
};
|
||||
if !edits.iter().any(|e| e.range == range) {
|
||||
edits.push(TextEdit { range, new_text: new_name.to_owned() });
|
||||
}
|
||||
};
|
||||
edit(&target.path, target.selection);
|
||||
for u in &usages {
|
||||
edit(&u.path, u.use_.range);
|
||||
for &r in &u.use_.body {
|
||||
edit(&u.path, r);
|
||||
}
|
||||
}
|
||||
let files = by_file
|
||||
.into_iter()
|
||||
.map(|(p, mut edits)| {
|
||||
edits.sort_by_key(|e| e.range);
|
||||
FileEdit::Edit { path: IpcPath::from(p), edits, version: None }
|
||||
})
|
||||
.collect();
|
||||
Ok(WorkspaceEdit { files, preconditions: Vec::new() })
|
||||
}
|
||||
|
||||
fn usages_of(
|
||||
project: &Project,
|
||||
syntax: &Syntax,
|
||||
path: &Path,
|
||||
text: &str,
|
||||
pos: Pos,
|
||||
cancelled: &dyn Fn() -> bool,
|
||||
) -> IdeResult<Option<(Definition, Vec<Usage>)>> {
|
||||
let own = Arc::new(syntax.pytest_module(&python(), text));
|
||||
if own.definition_at(pos).is_none() && own.use_at(pos).is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let scope = Scope::new(project);
|
||||
let Some(target) = target_at(project, syntax, &scope, path, &own, pos) else { return Ok(None) };
|
||||
let mut files = candidate_files(project, &target.path);
|
||||
if !files.iter().any(|f| f == path) && path.starts_with(&project.root) {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
let mut usages = Vec::new();
|
||||
for file in files {
|
||||
if cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let module = if file == path { Some(own.clone()) } else { module_of(project, syntax, &file) };
|
||||
let Some(module) = module else { continue };
|
||||
if !module.uses.iter().any(|u| u.name == target.name) {
|
||||
continue;
|
||||
}
|
||||
let layers = scope.layers(project, syntax, &file, module.clone());
|
||||
for u in module.uses.iter().filter(|u| u.name == target.name) {
|
||||
if definition_of(&layers, u).as_ref() == Some(&target) {
|
||||
usages.push(Usage { path: file.clone(), use_: u.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some((target, usages)))
|
||||
}
|
||||
|
||||
/// The files that may get a fixture defined in `definition`: that test module alone, the test
|
||||
/// modules and `conftest.py` files below a `conftest.py`, all of the project's for a plugin's.
|
||||
fn candidate_files(project: &Project, definition: &Path) -> Vec<PathBuf> {
|
||||
let in_project = is_project_file(project, definition);
|
||||
let is_conftest = definition.file_name().is_some_and(|n| n == "conftest.py");
|
||||
if in_project && !is_conftest {
|
||||
return vec![definition.to_path_buf()];
|
||||
}
|
||||
let dir = if in_project { definition.parent().unwrap_or(&project.root) } else { &project.root };
|
||||
let mut files = project.index.files_matching(dir, is_test_file, MAX_FILES).unwrap_or_default();
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
const MAX_FILES: usize = 20_000;
|
||||
|
||||
/// A file of the project's own code: below its root, not in an installed package (a
|
||||
/// virtualenv inside the project holds pytest and its plugins).
|
||||
fn is_project_file(project: &Project, path: &Path) -> bool {
|
||||
path.starts_with(&project.root) && !path.components().any(|c| c.as_os_str() == "site-packages")
|
||||
}
|
||||
|
||||
/// `test_*.py`, `*_test.py` and `conftest.py`: the files pytest collects or loads.
|
||||
fn is_test_file(rel: &Path) -> bool {
|
||||
let Some(name) = rel.file_name().and_then(|n| n.to_str()) else { return false };
|
||||
let Some(stem) = name.strip_suffix(".py") else { return false };
|
||||
stem == "conftest" || stem.starts_with("test_") || stem.ends_with("_test")
|
||||
}
|
||||
|
||||
/// The `site-packages` of the project's interpreter: its virtualenv's, else its install prefix's.
|
||||
fn interpreter_site_packages(project: &Project) -> Vec<PathBuf> {
|
||||
let settings = project.settings.effective();
|
||||
let Some(python) = ide_sdk::apply::python_interpreter(&project.root, &settings) else { return Vec::new() };
|
||||
let prefix = ide_sdk::venv_of(&python).or_else(|| python.parent()?.parent().map(Path::to_path_buf));
|
||||
prefix.map(|p| site_packages(&p)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `pkg.mod` → `pkg/mod.py` or `pkg/mod/__init__.py` in the first folder that has it.
|
||||
fn module_file(module: &str, search: &[PathBuf]) -> Option<PathBuf> {
|
||||
let rel: PathBuf = module.split('.').collect();
|
||||
search.iter().find_map(|base| {
|
||||
let file = base.join(&rel).with_extension("py");
|
||||
let package = base.join(&rel).join("__init__.py");
|
||||
[file, package].into_iter().find(|p| p.is_file())
|
||||
})
|
||||
}
|
||||
|
||||
/// The modules of the `[pytest11]` entry points of the distributions in `site_packages`.
|
||||
fn entry_point_modules(site_packages: &Path) -> Vec<String> {
|
||||
let Ok(entries) = std::fs::read_dir(site_packages) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
if !entry.file_name().to_string_lossy().ends_with(".dist-info") {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(entry.path().join("entry_points.txt")) else { continue };
|
||||
out.extend(pytest11_modules(&text));
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// The modules of the `[pytest11]` section of an `entry_points.txt` (`name = module:attr`).
|
||||
fn pytest11_modules(text: &str) -> Vec<String> {
|
||||
let mut section = "";
|
||||
let mut out = Vec::new();
|
||||
for line in text.lines().map(str::trim) {
|
||||
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
||||
section = name;
|
||||
} else if section == "pytest11"
|
||||
&& let Some((_, value)) = line.split_once('=')
|
||||
{
|
||||
let module = value.trim().split(':').next().unwrap_or_default().trim();
|
||||
if !module.is_empty() {
|
||||
out.push(module.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// pytest's own plugins that are off unless `pytest_plugins` names them.
|
||||
const OPTIONAL_BUILTINS: [&str; 2] = ["pytester.py", "pytester_assertions.py"];
|
||||
|
||||
/// pytest's own modules that may define fixtures: `_pytest/*.py`, one level of subpackages.
|
||||
fn builtin_modules(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return out };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if OPTIONAL_BUILTINS.iter().any(|name| entry.file_name() == *name) {
|
||||
continue;
|
||||
}
|
||||
if path.extension().is_some_and(|e| e == "py") {
|
||||
out.push(path);
|
||||
} else if path.is_dir() {
|
||||
out.extend(
|
||||
std::fs::read_dir(&path)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "py")),
|
||||
);
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
/// A parsed file and the modification time and length it was read at.
|
||||
type Cached = (SystemTime, u64, Arc<PytestModule>);
|
||||
|
||||
/// The fixtures of a file: from its open editor, else from disk, parsed once per modification.
|
||||
fn module_of(project: &Project, syntax: &Syntax, path: &Path) -> Option<Arc<PytestModule>> {
|
||||
if let Some(text) = project.documents.text_of(path) {
|
||||
return Some(Arc::new(syntax.pytest_module(&python(), &text)));
|
||||
}
|
||||
static CACHE: LazyLock<Mutex<HashMap<PathBuf, Cached>>> = LazyLock::new(Default::default);
|
||||
let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?;
|
||||
if meta.len() > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
return None;
|
||||
}
|
||||
let stamp = (meta.modified().ok()?, meta.len());
|
||||
if let Some((time, len, m)) = CACHE.lock().ok()?.get(path)
|
||||
&& (*time, *len) == stamp
|
||||
{
|
||||
return Some(m.clone());
|
||||
}
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let module = Arc::new(syntax.pytest_module(&python(), &ide_text::normalize_line_endings(&text)));
|
||||
CACHE.lock().ok()?.insert(path.to_path_buf(), (stamp.0, stamp.1, module.clone()));
|
||||
Some(module)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_files_are_the_ones_pytest_loads() {
|
||||
for (rel, expected) in [
|
||||
("tests/test_a.py", true),
|
||||
("a_test.py", true),
|
||||
("pkg/conftest.py", true),
|
||||
("pkg/helpers.py", false),
|
||||
("test_data.json", false),
|
||||
] {
|
||||
assert_eq!(is_test_file(Path::new(rel)), expected, "{rel}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_pytest11_entry_points() {
|
||||
let text =
|
||||
"[console_scripts]\nx = a:b\n\n[pytest11]\nmock = pytest_mock\nasyncio = pytest_asyncio.plugin:main\n";
|
||||
assert_eq!(pytest11_modules(text), ["pytest_mock", "pytest_asyncio.plugin"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_module_files_and_packages() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("pkg/sub")).unwrap();
|
||||
std::fs::write(dir.path().join("pkg/fixtures.py"), "").unwrap();
|
||||
std::fs::write(dir.path().join("pkg/sub/__init__.py"), "").unwrap();
|
||||
let search = [dir.path().to_path_buf()];
|
||||
assert_eq!(module_file("pkg.fixtures", &search), Some(dir.path().join("pkg/fixtures.py")));
|
||||
assert_eq!(module_file("pkg.sub", &search), Some(dir.path().join("pkg/sub/__init__.py")));
|
||||
assert_eq!(module_file("pkg.none", &search), None);
|
||||
}
|
||||
}
|
||||
@@ -52,29 +52,43 @@ pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
|
||||
extra.get("python")?.as_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
/// Adds the project's import paths, and the Plots tool window's backend (`plots`), to a debugpy
|
||||
/// launch's environment.
|
||||
pub(super) fn prepare_debug(
|
||||
config: &mut LaunchConfig,
|
||||
paths: &[PathBuf],
|
||||
plots: Option<&ide_run::plots::Plots>,
|
||||
) -> IdeResult<()> {
|
||||
// Adapter-specific env takes precedence over the common launch fields in DAP.
|
||||
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
|
||||
// A custom adapter may run on another host; local paths are not portable.
|
||||
if extra.as_ref().is_some_and(|e| e.get("debugServer").is_some()) {
|
||||
return Ok(());
|
||||
}
|
||||
let plots = plots.filter(|_| !config.env.contains_key("MPLBACKEND"));
|
||||
if let Some(env) = extra.as_mut().and_then(|e| e.get_mut("env")) {
|
||||
if env.is_null() {
|
||||
*env = serde_json::json!({});
|
||||
}
|
||||
if !env.is_object() {
|
||||
let Some(object) = env.as_object_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut vars: BTreeMap<String, String> =
|
||||
object.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_owned()))).collect();
|
||||
let inherit = !vars.contains_key("PYTHONPATH");
|
||||
ide_run::python_path::extend(&mut vars, paths, inherit)?;
|
||||
if let Some(plots) = plots {
|
||||
ide_run::plots::add(&mut vars, plots, true)?;
|
||||
}
|
||||
let mut vars = BTreeMap::new();
|
||||
if let Some(value) = env.get("PYTHONPATH").and_then(|v| v.as_str()) {
|
||||
vars.insert("PYTHONPATH".into(), value.to_owned());
|
||||
for (key, value) in vars {
|
||||
object.insert(key, serde_json::json!(value));
|
||||
}
|
||||
ide_run::python_path::extend(&mut vars, paths, env.get("PYTHONPATH").is_none())?;
|
||||
env["PYTHONPATH"] = serde_json::json!(vars["PYTHONPATH"]);
|
||||
config.extra_json = extra.map(|e| e.to_string());
|
||||
} else {
|
||||
ide_run::python_path::extend(&mut config.env, paths, true)?;
|
||||
if let Some(plots) = plots {
|
||||
ide_run::plots::add(&mut config.env, plots, true)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -97,11 +111,11 @@ mod tests {
|
||||
extra_json: Some(serde_json::json!({"env": null, "debugServer": "remote:5678"}).to_string()),
|
||||
};
|
||||
let before = config.extra_json.clone();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
assert_eq!(config.extra_json, before);
|
||||
assert!(config.env.is_empty());
|
||||
config.extra_json = Some(serde_json::json!({"env": null}).to_string());
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
let paths = std::env::split_paths(value["env"]["PYTHONPATH"].as_str().unwrap()).collect::<Vec<_>>();
|
||||
assert_eq!(paths[0], root);
|
||||
@@ -123,7 +137,7 @@ mod tests {
|
||||
env: vars.clone(),
|
||||
extra_json: extra.then(|| serde_json::json!({"env": vars}).to_string()),
|
||||
};
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root)).unwrap();
|
||||
prepare_debug(&mut config, std::slice::from_ref(&root), None).unwrap();
|
||||
let vars: BTreeMap<String, String> = if extra {
|
||||
let value: serde_json::Value = serde_json::from_str(config.extra_json.as_deref().unwrap()).unwrap();
|
||||
serde_json::from_value(value["env"].clone()).unwrap()
|
||||
|
||||
@@ -6,8 +6,9 @@ use ide_command::command;
|
||||
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
|
||||
use ide_language::Syntax;
|
||||
use ide_lsp::types::FileRenameEdits;
|
||||
use ide_workspace::file_moves::moved_path;
|
||||
use ide_workspace::roots::{ProjectRoots, RootKind};
|
||||
use ide_workspace::Documents;
|
||||
use ide_workspace::file_moves::{moved_path, read_text};
|
||||
use ide_workspace::roots::{PYTHON_FILES, ProjectRoots, RootKind, SourceFolder};
|
||||
use ide_workspace::{FileMove, UndoOutcome};
|
||||
use parking_lot::Mutex;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -18,7 +19,8 @@ fn pairs(moves: &[FileMove]) -> Vec<(PathBuf, PathBuf)> {
|
||||
moves.iter().map(|m| (m.from.to_path_buf(), m.to.to_path_buf())).collect()
|
||||
}
|
||||
|
||||
/// `workspace/willRenameFiles` on every interested server (before the move). Cancellable.
|
||||
/// `workspace/willRenameFiles` on every interested server (before the move), plus the
|
||||
/// Python import updates the IDE makes itself. Cancellable.
|
||||
#[command(trust = always)]
|
||||
pub async fn refactor_file_move_edits(
|
||||
host: &Host,
|
||||
@@ -28,46 +30,72 @@ pub async fn refactor_file_move_edits(
|
||||
) -> IdeResult<FileRenameEdits> {
|
||||
let project = host.project(window)?;
|
||||
let token = host.begin_request(request);
|
||||
let result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await;
|
||||
host.end_request(request);
|
||||
let mut result = result?;
|
||||
let syntax = host.syntax();
|
||||
blocking(move || {
|
||||
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
|
||||
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
|
||||
let python = python_import_edits(&project, &syntax, &moves, &|| token.is_cancelled());
|
||||
result.edit.files.extend(python.files);
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut result.edit)?;
|
||||
Ok(result)
|
||||
})
|
||||
.await
|
||||
let result = async {
|
||||
let mut result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await?;
|
||||
blocking(move || {
|
||||
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
|
||||
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
|
||||
let python = python_import_edits(
|
||||
&project.root,
|
||||
&project.roots(),
|
||||
&project.exclude_globs(),
|
||||
&project.documents,
|
||||
&syntax,
|
||||
&moves,
|
||||
&|| token.is_cancelled(),
|
||||
);
|
||||
result.edit.files.extend(python.files);
|
||||
}
|
||||
if token.is_cancelled() {
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
project.documents.prepare_workspace_edit(&mut result.edit)?;
|
||||
Ok(result)
|
||||
})
|
||||
.await
|
||||
}
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
fn is_python(path: &Path) -> bool {
|
||||
path.extension().is_some_and(|e| e == "py" || e == "pyi")
|
||||
}
|
||||
|
||||
/// The dotted name of a Python module file or package folder, from its project's Python roots
|
||||
/// (`src/a/b.py` → `a.b` in a `src` layout).
|
||||
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<String> {
|
||||
let rel = path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/");
|
||||
let base = roots
|
||||
.root_for(&rel)
|
||||
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
|
||||
.map_or("", |r| r.path.as_str());
|
||||
/// The folders Python imports modules from: source and test roots of Python projects (or marked
|
||||
/// by the user), else the project root. Other languages' roots (`frontend/src`) don't count.
|
||||
fn python_root<'a>(roots: &'a ProjectRoots, rel: &str) -> &'a str {
|
||||
let python = |r: &&SourceFolder| {
|
||||
matches!(r.kind, RootKind::Source | RootKind::Test)
|
||||
&& r.detected_from.as_deref().is_none_or(|f| PYTHON_FILES.iter().any(|p| f.rsplit('/').next() == Some(*p)))
|
||||
};
|
||||
let inside = |r: &&SourceFolder| r.path.is_empty() || rel == r.path || rel.starts_with(&format!("{}/", r.path));
|
||||
roots.roots.iter().filter(python).filter(inside).max_by_key(|r| r.path.len()).map_or("", |r| r.path.as_str())
|
||||
}
|
||||
|
||||
fn rel_path(root: &Path, path: &Path) -> Option<String> {
|
||||
Some(path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// The dotted name of a Python module file or package folder and the root it is imported from
|
||||
/// (`src/a/b.py` → `a.b` from `src` in a `src` layout).
|
||||
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<(String, String)> {
|
||||
let rel = rel_path(root, path)?;
|
||||
let base = python_root(roots, &rel);
|
||||
let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') };
|
||||
let inner = if is_dir { inner } else { inner.strip_suffix(".py").or_else(|| inner.strip_suffix(".pyi"))? };
|
||||
let inner = inner.strip_suffix("/__init__").unwrap_or(inner);
|
||||
let valid = |s: &str| {
|
||||
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
|
||||
};
|
||||
(!inner.is_empty() && inner.split('/').all(valid)).then(|| inner.replace('/', "."))
|
||||
(!inner.is_empty() && inner.split('/').all(valid)).then(|| (inner.replace('/', "."), base.to_owned()))
|
||||
}
|
||||
|
||||
/// The package relative imports in `file` start from.
|
||||
fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
|
||||
let Some(module) = python_module(root, roots, file, false) else { return String::new() };
|
||||
let Some((module, _)) = python_module(root, roots, file, false) else { return String::new() };
|
||||
if file.file_stem().is_some_and(|s| s == "__init__") {
|
||||
module
|
||||
} else {
|
||||
@@ -75,52 +103,91 @@ fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `dir` holds Python modules (a package or namespace package), at any depth.
|
||||
fn has_python(dir: &Path) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|e| {
|
||||
let path = e.path();
|
||||
let name = e.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if e.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
!name.starts_with('.') && !matches!(name.as_ref(), "node_modules" | "__pycache__") && has_python(&path)
|
||||
} else {
|
||||
is_python(&path)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Import updates in the project's Python files for `moves` (paths before the move).
|
||||
fn python_import_edits(
|
||||
project: &crate::project::Project,
|
||||
root: &Path,
|
||||
roots: &ProjectRoots,
|
||||
excludes: &[String],
|
||||
documents: &Documents,
|
||||
syntax: &Syntax,
|
||||
moves: &[FileMove],
|
||||
cancelled: &(dyn Fn() -> bool + Sync),
|
||||
) -> WorkspaceEdit {
|
||||
let root = &project.root;
|
||||
let roots = project.roots();
|
||||
let renames: Vec<(String, String)> = moves
|
||||
.iter()
|
||||
.filter_map(|m| {
|
||||
let is_dir = m.from.is_dir();
|
||||
if !is_dir && (!is_python(&m.from) || m.from.file_stem().is_some_and(|s| s == "__init__")) {
|
||||
return None;
|
||||
}
|
||||
let old = python_module(root, &roots, &m.from, is_dir)?;
|
||||
let new = python_module(root, &roots, &m.to, is_dir)?;
|
||||
(old != new).then_some((old, new))
|
||||
})
|
||||
.collect();
|
||||
// (old, new, root the old module is imported from)
|
||||
let mut renames: Vec<(String, String, String)> = Vec::new();
|
||||
for m in moves {
|
||||
let is_dir = m.from.is_dir();
|
||||
let module = if is_dir {
|
||||
has_python(&m.from)
|
||||
} else {
|
||||
let stub_only = m.from.extension().is_some_and(|e| e == "pyi")
|
||||
&& !moves.iter().any(|o| *o.from == m.from.with_extension("py"));
|
||||
// A stub may describe a compiled module that stays where it is.
|
||||
is_python(&m.from) && !stub_only && m.from.file_stem().is_some_and(|s| s != "__init__")
|
||||
};
|
||||
if !module {
|
||||
continue;
|
||||
}
|
||||
let (Some((old, base)), Some((new, _))) =
|
||||
(python_module(root, roots, &m.from, is_dir), python_module(root, roots, &m.to, is_dir))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if old != new && !renames.iter().any(|r| r.0 == old) {
|
||||
renames.push((old, new, base));
|
||||
}
|
||||
}
|
||||
if renames.is_empty() {
|
||||
return WorkspaceEdit::default();
|
||||
}
|
||||
let names: Vec<&str> = renames.iter().map(|(old, _)| old.rsplit('.').next().unwrap_or(old)).collect();
|
||||
// `import utils` in `backend/app.py` means `backend/utils.py`, not `backend/tests/utils.py`.
|
||||
let shadowed = |base: &str, module: &str| {
|
||||
let p = root.join(base).join(module.replace('.', "/"));
|
||||
p.with_extension("py").is_file() || p.with_extension("pyi").is_file() || p.is_dir()
|
||||
};
|
||||
let names: Vec<&str> = renames.iter().map(|(old, ..)| old.rsplit('.').next().unwrap_or(old)).collect();
|
||||
let found: Mutex<Vec<(PathBuf, Vec<ide_core::TextEdit>)>> = Mutex::new(Vec::new());
|
||||
ide_vfs::walk_files(root, &project.exclude_globs(), |path| {
|
||||
ide_vfs::walk_files(root, excludes, |path| {
|
||||
if cancelled() || !is_python(path) {
|
||||
return;
|
||||
}
|
||||
let moved = moved_path(path, moves);
|
||||
let text = match project.documents.text_of(path) {
|
||||
Some(t) => t,
|
||||
None => match std::fs::read_to_string(path) {
|
||||
Ok(t) => t,
|
||||
Err(_) => return,
|
||||
},
|
||||
};
|
||||
if moved == path && !names.iter().any(|n| text.contains(n)) {
|
||||
return;
|
||||
if moved == path {
|
||||
let Ok(bytes) = std::fs::read(path) else { return };
|
||||
let raw = String::from_utf8_lossy(&bytes);
|
||||
if !names.iter().any(|n| raw.contains(n)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Through the documents layer: unsaved edits, BOM and encodings as the edits will see them.
|
||||
let Ok(text) = read_text(documents, path) else { return };
|
||||
let Some(rel) = rel_path(root, path) else { return };
|
||||
let base = python_root(roots, &rel);
|
||||
let visible: Vec<(String, String)> = renames
|
||||
.iter()
|
||||
.filter(|(old, _, from)| from == base || !shadowed(base, old))
|
||||
.map(|(old, new, _)| (old.clone(), new.clone()))
|
||||
.collect();
|
||||
let edits = syntax.python_import_edits(
|
||||
&text,
|
||||
&python_package(root, &roots, path),
|
||||
&python_package(root, &roots, &moved),
|
||||
&renames,
|
||||
&python_package(root, roots, path),
|
||||
&python_package(root, roots, &moved),
|
||||
&visible,
|
||||
);
|
||||
if !edits.is_empty() {
|
||||
found.lock().push((path.to_path_buf(), edits));
|
||||
@@ -213,7 +280,6 @@ ide_command::domain!(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_workspace::roots::SourceFolder;
|
||||
|
||||
#[test]
|
||||
fn python_module_names_follow_the_roots() {
|
||||
@@ -223,7 +289,7 @@ mod tests {
|
||||
vec![folder("src", RootKind::Source), folder("tests", RootKind::Test)],
|
||||
&Default::default(),
|
||||
);
|
||||
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir);
|
||||
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir).map(|(m, _)| m);
|
||||
assert_eq!(name("src/tasks/models.py", false).as_deref(), Some("tasks.models"));
|
||||
assert_eq!(name("src/tasks/__init__.py", false).as_deref(), Some("tasks"));
|
||||
assert_eq!(name("src/tasks", true).as_deref(), Some("tasks"));
|
||||
@@ -234,4 +300,54 @@ mod tests {
|
||||
assert_eq!(python_package(root, &roots, &root.join("src/tasks/cli.py")), "tasks");
|
||||
assert_eq!(python_package(root, &roots, &root.join("src/tasks/__init__.py")), "tasks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_imports_in_a_mixed_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let write = |p: &str, text: &str| {
|
||||
let path = root.join(p);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
};
|
||||
write("backend/pyproject.toml", "[project]\nname = \"b\"\n");
|
||||
write("backend/utils.py", "");
|
||||
write("backend/app.py", "import utils\nfrom api import routes\n");
|
||||
write("backend/api/__init__.py", "");
|
||||
write("backend/api/routes.py", "");
|
||||
write("backend/bom.py", "\u{feff}from api import routes\n");
|
||||
write("backend/tests/utils.py", "");
|
||||
write("backend/tests/test_a.py", "import utils\n");
|
||||
write("backend/native/_ext.pyi", "");
|
||||
write("backend/uses_ext.py", "from native import _ext\n");
|
||||
write("frontend/package.json", "{}");
|
||||
write("frontend/src/api/index.js", "");
|
||||
let roots = ProjectRoots::compute(ide_workspace::roots::detect(root), &Default::default());
|
||||
let documents = Documents::new(
|
||||
std::sync::Arc::new(|_| {}),
|
||||
Box::new(|_: &Path, _: Option<&str>| ide_core::LanguageId::new("python")),
|
||||
);
|
||||
let edits = |from: &str, to: &str| {
|
||||
let moves = vec![FileMove { from: root.join(from).into(), to: root.join(to).into() }];
|
||||
let edit = python_import_edits(root, &roots, &[], &documents, &Syntax::new(), &moves, &|| false);
|
||||
edit.files
|
||||
.into_iter()
|
||||
.filter_map(|f| match f {
|
||||
FileEdit::Edit { path, edits, .. } => Some((rel_path(root, &path).unwrap(), edits)),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// Not Python: a JavaScript folder of the same name.
|
||||
assert!(edits("frontend/src/api", "frontend/src/client").is_empty());
|
||||
// Same-named modules of different roots.
|
||||
let files = edits("backend/tests/utils.py", "backend/tests/helpers.py");
|
||||
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/tests/test_a.py"]);
|
||||
// A BOM doesn't shift the edit.
|
||||
let files = edits("backend/api", "backend/web");
|
||||
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/app.py", "backend/bom.py"]);
|
||||
assert_eq!(files[1].1[0].range.start, ide_core::Pos { line: 0, col: 5 });
|
||||
// A stub without its module.
|
||||
assert!(edits("backend/native/_ext.pyi", "backend/native/_ext2.pyi").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -334,10 +334,19 @@ pub async fn run_start(
|
||||
Some(agent) => agent.wrap_output(on_output),
|
||||
None => on_output,
|
||||
};
|
||||
// `execute_run_configuration` asked the Run tool window to start it.
|
||||
let mcp = crate::mcp::run::configs::config_run_launch(&config);
|
||||
let on_output = match &mcp {
|
||||
Some(mcp) => mcp.wrap_output(on_output),
|
||||
None => on_output,
|
||||
};
|
||||
let result = start_inner(host, window, config, on_output, agent.as_ref(), &cancel).await;
|
||||
if let Some(agent) = &agent {
|
||||
agent.started(&result);
|
||||
}
|
||||
if let Some(mcp) = &mcp {
|
||||
mcp.started(&result);
|
||||
}
|
||||
if let Some(id) = request {
|
||||
host.end_request(id);
|
||||
}
|
||||
@@ -429,6 +438,7 @@ async fn start_inner(
|
||||
encoding: Some(settings.console.encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths: Vec::new(),
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
},
|
||||
sink,
|
||||
Box::new(move |c| on_output(c)),
|
||||
@@ -445,6 +455,7 @@ async fn start_inner(
|
||||
python_paths: Vec::new(),
|
||||
// A folder on this machine: not in the container.
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
};
|
||||
project.require_trust()?;
|
||||
return host.processes.start(
|
||||
@@ -493,7 +504,7 @@ async fn start_inner(
|
||||
}
|
||||
// A Python configuration pointing at a missing interpreter fails in the depth of
|
||||
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "doctest" | "django-test");
|
||||
if is_python && Path::new(&config.command).components().count() > 1 {
|
||||
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
|
||||
@@ -542,6 +553,7 @@ async fn start_inner(
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths,
|
||||
ruby_reporter: ruby_reporter_dir(host, &config),
|
||||
plots: if is_python { super::plots::prepare(host, &project) } else { None },
|
||||
};
|
||||
project.require_trust()?;
|
||||
if config.kind == "go" && matches!(config.args.first().map(String::as_str), Some("mod" | "work")) {
|
||||
|
||||
@@ -110,8 +110,8 @@ pub(crate) fn search_project(
|
||||
_ => true,
|
||||
};
|
||||
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
let defaults = project.documents.file_defaults();
|
||||
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
|
||||
// Search's UTF-8 fast path does not need to resolve the configured encoding.
|
||||
let fallback = |path: &Path| project.documents.configured_encoding_for(path);
|
||||
let mut total = SearchSummary::default();
|
||||
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
|
||||
let mut remaining = query.clone();
|
||||
|
||||
@@ -11,7 +11,7 @@ use ide_spell::{Region, RegionKind, SpellScope, Speller, Typo};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Languages checked as prose (all text but code spans).
|
||||
const PROSE: &[&str] = &["plaintext", "markdown", "restructuredtext", "asciidoc", "latex"];
|
||||
const PROSE: &[&str] = &["plaintext", "markdown", "mdx", "restructuredtext", "asciidoc", "latex"];
|
||||
|
||||
/// Custom dictionary paths: `~/…` from home, relative ones from the project root.
|
||||
fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
|
||||
|
||||
@@ -85,6 +85,8 @@ pub struct Project {
|
||||
pub(crate) git_metadata: Option<Arc<ide_vcs::MetadataWatch>>,
|
||||
/// Picks up data sources edited on disk outside the Database tool window.
|
||||
_db_sources_watch: Option<ide_db::SourcesWatch>,
|
||||
/// The Plots tool window's folder watch, started by the first Python run ([`crate::ops::plots`]).
|
||||
pub(crate) plots_watch: Mutex<Option<notify::RecommendedWatcher>>,
|
||||
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
|
||||
/// nothing indexed, no language servers, repositories or project services.
|
||||
pub light: bool,
|
||||
@@ -211,6 +213,10 @@ impl Host {
|
||||
crate::ts_code_style::configure(cfg, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
|
||||
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
|
||||
// After the global plugins: they keep the IDE's copies.
|
||||
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
|
||||
let container_python = effective.languages.python.run_target().is_some();
|
||||
crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective);
|
||||
// Attached dependency projects are source, so basedpyright/Pyright should
|
||||
@@ -360,8 +366,13 @@ impl Host {
|
||||
}
|
||||
{
|
||||
let settings = settings.clone();
|
||||
let data_dir = self.local_data_dir.clone();
|
||||
lsp.set_servers_hook(Box::new(move |language, defined| {
|
||||
ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective())
|
||||
let mut servers = ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective());
|
||||
if language.as_str() == "css" && ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit").is_none() {
|
||||
ide_sdk::apply::drop_css_modules_route(&mut servers);
|
||||
}
|
||||
servers
|
||||
}));
|
||||
}
|
||||
{
|
||||
@@ -452,7 +463,9 @@ impl Host {
|
||||
phpstan.files_removed(batch.removed.iter());
|
||||
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
|
||||
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed))
|
||||
|| ts_config_changed(changed.iter().chain(&batch.removed))
|
||||
{
|
||||
lsp.reconfigure_soon();
|
||||
}
|
||||
// Not while loading: a first `use flake` may write `flake.lock` itself.
|
||||
@@ -702,6 +715,7 @@ impl Host {
|
||||
_scratch_watcher: scratch_watcher,
|
||||
git_metadata,
|
||||
_db_sources_watch: db_sources_watch,
|
||||
plots_watch: Mutex::default(),
|
||||
files_events_active,
|
||||
light: false,
|
||||
});
|
||||
@@ -762,6 +776,12 @@ impl Host {
|
||||
if let Some(cmd) = post_start {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
if project.is_trusted() {
|
||||
let p = project.clone();
|
||||
self.runtime.spawn_blocking(move || {
|
||||
crate::github_auth::apply_to_project(&p);
|
||||
});
|
||||
}
|
||||
crate::ops::sdk::container_python::ensure(self, &project);
|
||||
Ok(project)
|
||||
}
|
||||
@@ -966,6 +986,7 @@ impl Host {
|
||||
_scratch_watcher: None,
|
||||
git_metadata: None,
|
||||
_db_sources_watch: None,
|
||||
plots_watch: Mutex::default(),
|
||||
files_events_active: Arc::new(AtomicBool::new(false)),
|
||||
light: true,
|
||||
root: dir,
|
||||
@@ -1034,9 +1055,8 @@ fn db_sources_watch(
|
||||
let Some(db) = weak.upgrade() else { return };
|
||||
let sink = sink.clone();
|
||||
runtime.spawn(async move {
|
||||
if db.reconcile_sources().await {
|
||||
sink.emit(IdeEvent::DbSourcesChanged);
|
||||
}
|
||||
db.reconcile_sources().await;
|
||||
sink.emit(IdeEvent::DbSourcesChanged);
|
||||
});
|
||||
}))
|
||||
.inspect_err(|e| tracing::warn!("{}", e.message))
|
||||
@@ -1524,8 +1544,7 @@ impl Project {
|
||||
}
|
||||
|
||||
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
|
||||
let defaults = self.documents.file_defaults();
|
||||
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
|
||||
let charset = self.documents.detect_encoding(path, bytes);
|
||||
self.vcs_text_encoding(path, charset)
|
||||
}
|
||||
|
||||
@@ -1884,7 +1903,9 @@ fn content_root_watcher(
|
||||
index.ignore_rules_changed(&batch.ignore_rules);
|
||||
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
|
||||
// A workspace member's PHP language level follows its own composer.json.
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed))
|
||||
|| ts_config_changed(changed.iter().chain(&batch.removed))
|
||||
{
|
||||
lsp.reconfigure_soon();
|
||||
}
|
||||
if let Some(bridge) = &kotlin_bridge {
|
||||
@@ -1906,6 +1927,17 @@ fn content_root_watcher(
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// A tsconfig.json / jsconfig.json (or a `tsconfig.*.json` one extends) changed: the tsserver
|
||||
/// plugins it declares are part of vtsls' configuration.
|
||||
fn ts_config_changed<'a>(mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
|
||||
paths.any(|p| {
|
||||
let name = p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
|
||||
!p.components().any(|c| c.as_os_str() == "node_modules")
|
||||
&& (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
|
||||
&& name.ends_with(".json")
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the `composer.json` of `root` is among `paths`: the PHP language level follows it
|
||||
/// (`ide_sdk::php`).
|
||||
fn composer_changed<'a>(root: &Path, mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
|
||||
@@ -2731,9 +2763,20 @@ mod agent_worktree_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod composer_tests {
|
||||
use super::composer_changed;
|
||||
use super::{composer_changed, ts_config_changed};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[test]
|
||||
fn tsconfig_and_jsconfig_files_count_outside_node_modules() {
|
||||
let changed = |p: &str| ts_config_changed([PathBuf::from(p)].iter());
|
||||
for yes in ["/p/tsconfig.json", "/p/apps/web/jsconfig.json", "/p/tsconfig.base.json"] {
|
||||
assert!(changed(yes), "{yes}");
|
||||
}
|
||||
for no in ["/p/package.json", "/p/tsconfig.ts", "/p/node_modules/x/tsconfig.json"] {
|
||||
assert!(!changed(no), "{no}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_roots_own_composer_json_counts() {
|
||||
let root = Path::new("/work/app");
|
||||
|
||||
@@ -364,6 +364,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
|
||||
| IdeEvent::UpdateAvailable { .. } => false,
|
||||
IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. } => trusted,
|
||||
IdeEvent::DbSourcesChanged
|
||||
| IdeEvent::PlotAdded { .. }
|
||||
| IdeEvent::ProjectTrustChanged { .. }
|
||||
| IdeEvent::Direnv { .. }
|
||||
| IdeEvent::FlutterDevices { .. }
|
||||
|
||||
@@ -282,11 +282,18 @@ impl crate::Host {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
self.environment.direnv_opened(&project.root, &project.sink);
|
||||
{
|
||||
let p = project.clone();
|
||||
self.runtime.spawn_blocking(move || {
|
||||
crate::github_auth::apply_to_project(&p);
|
||||
});
|
||||
}
|
||||
project.lsp.set_execution_allowed(true);
|
||||
project.lsp.prewarm_java_configuration();
|
||||
} else {
|
||||
self.environment.project_closed();
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
project.agents.shutdown();
|
||||
project.flutter.stop();
|
||||
project.devtools.stop();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation, Imports) as the TypeScript
|
||||
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
|
||||
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
|
||||
//! quick fixes, auto-imports, refactorings and organize imports.
|
||||
@@ -48,12 +48,7 @@ pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &
|
||||
.and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}"))))
|
||||
.unwrap_or_default();
|
||||
let section = section(language, code_style.languages.get(language), &pairs);
|
||||
if !section.is_empty() {
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
}
|
||||
if layer.is_empty() {
|
||||
return;
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
let mut merged = Value::Object(layer);
|
||||
if let Some(own) = cfg.settings.take() {
|
||||
@@ -96,10 +91,30 @@ fn section(
|
||||
if !format.is_empty() {
|
||||
section.insert("format".into(), Value::Object(format));
|
||||
}
|
||||
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
|
||||
// vtsls reads VS Code's names (`quoteStyle`, `importModuleSpecifier`), typescript-language-server
|
||||
// tsserver's (`quotePreference`, `importModuleSpecifierPreference`).
|
||||
let mut preferences = Map::new();
|
||||
if let Some(quotes) = quotes {
|
||||
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": quotes }));
|
||||
preferences.insert("quoteStyle".into(), json!(quotes));
|
||||
preferences.insert("quotePreference".into(), json!(quotes));
|
||||
}
|
||||
let paths = ["shortest", "relative", "non-relative", "project-relative"];
|
||||
if let Some(paths) = pick(style.and_then(|s| s.import_module_specifier.as_ref()), &paths) {
|
||||
preferences.insert("importModuleSpecifier".into(), json!(paths));
|
||||
preferences.insert("importModuleSpecifierPreference".into(), json!(paths));
|
||||
}
|
||||
let endings = ["auto", "minimal", "index", "js"];
|
||||
if let Some(ending) = pick(style.and_then(|s| s.import_module_specifier_ending.as_ref()), &endings) {
|
||||
preferences.insert("importModuleSpecifierEnding".into(), json!(ending));
|
||||
}
|
||||
// Sent even when empty: vtsls has no default for these, so a list left out keeps tsserver's
|
||||
// previous one, and clearing it would only apply after a restart. `[]` excludes nothing.
|
||||
let none = Vec::new();
|
||||
let patterns = style.map_or(&none, |s| &s.auto_import_file_exclude_patterns);
|
||||
let regexes = style.map_or(&none, |s| &s.auto_import_specifier_exclude_regexes);
|
||||
preferences.insert("autoImportFileExcludePatterns".into(), json!(patterns));
|
||||
preferences.insert("autoImportSpecifierExcludeRegexes".into(), json!(regexes));
|
||||
section.insert("preferences".into(), Value::Object(preferences));
|
||||
section
|
||||
}
|
||||
|
||||
@@ -133,9 +148,17 @@ mod tests {
|
||||
"typescript": {
|
||||
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
|
||||
// The server's own settings win.
|
||||
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
|
||||
"preferences": {
|
||||
"quoteStyle": "double",
|
||||
"quotePreference": "single",
|
||||
"autoImportFileExcludePatterns": [],
|
||||
"autoImportSpecifierExcludeRegexes": [],
|
||||
},
|
||||
},
|
||||
"javascript": {
|
||||
"format": { "semicolons": "insert" },
|
||||
"preferences": { "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] },
|
||||
},
|
||||
"javascript": { "format": { "semicolons": "insert" } },
|
||||
})
|
||||
);
|
||||
|
||||
@@ -144,7 +167,52 @@ mod tests {
|
||||
assert_eq!(eslint.settings, None);
|
||||
let mut untouched = server("vtsls");
|
||||
configure(&mut untouched, dir.path(), &Settings::default());
|
||||
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
|
||||
// Nothing set: the server's defaults, and empty exclusion lists so that clearing one reaches
|
||||
// a running server.
|
||||
let empty = json!({ "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] });
|
||||
let empty = json!({ "typescript": { "preferences": empty }, "javascript": { "preferences": empty } });
|
||||
assert_eq!(untouched.settings, Some(empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_style_reaches_the_preferences_of_each_language() {
|
||||
let mut settings = Settings::default();
|
||||
let ts = LanguageCodeStyle {
|
||||
import_module_specifier: Some("relative".into()),
|
||||
import_module_specifier_ending: Some("index".into()),
|
||||
auto_import_file_exclude_patterns: vec!["**/index.ts".into()],
|
||||
auto_import_specifier_exclude_regexes: vec!["^node:".into()],
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("typescript".into(), ts);
|
||||
let js = LanguageCodeStyle {
|
||||
import_module_specifier: Some("non-relative".into()),
|
||||
// Not a tsserver value: left out.
|
||||
import_module_specifier_ending: Some("ts".into()),
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("javascript".into(), js);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
assert_eq!(
|
||||
cfg.settings.unwrap(),
|
||||
json!({
|
||||
"typescript": { "preferences": {
|
||||
"importModuleSpecifier": "relative",
|
||||
"importModuleSpecifierPreference": "relative",
|
||||
"importModuleSpecifierEnding": "index",
|
||||
"autoImportFileExcludePatterns": ["**/index.ts"],
|
||||
"autoImportSpecifierExcludeRegexes": ["^node:"],
|
||||
} },
|
||||
"javascript": { "preferences": {
|
||||
"importModuleSpecifier": "non-relative",
|
||||
"importModuleSpecifierPreference": "non-relative",
|
||||
"autoImportFileExcludePatterns": [],
|
||||
"autoImportSpecifierExcludeRegexes": [],
|
||||
} },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -178,6 +246,6 @@ mod tests {
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
let s = cfg.settings.unwrap();
|
||||
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
|
||||
assert_eq!(s.get("javascript"), None);
|
||||
assert_eq!(s["javascript"].get("format"), None);
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,15 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = tmp.path();
|
||||
let host = Arc::new(Host::new(common::host_config(base)));
|
||||
let root = base.join("data/consoles/db/pg");
|
||||
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
|
||||
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
|
||||
};
|
||||
assert!(db::db_consoles(&host, "pg".into(), false).unwrap().is_empty());
|
||||
// The first new console is the default one, then console_1, console_2…
|
||||
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql"]);
|
||||
let first = db::db_consoles(&host, "pg".into(), true).unwrap();
|
||||
assert_eq!(names(first.clone()), ["console.sql"]);
|
||||
assert_eq!(first[0].0, root.join("console.sql"));
|
||||
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql", "console_1.sql"]);
|
||||
let all = db::db_consoles(&host, "pg".into(), true).unwrap();
|
||||
assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]);
|
||||
@@ -26,3 +29,13 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
|
||||
assert!(db::db_consoles(&host, "pg:other".into(), false).unwrap().is_empty());
|
||||
assert!(db::db_consoles(&host, "../x".into(), true).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn consoles_root_is_the_directory_listed_in_the_project_view() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = tmp.path();
|
||||
let host = Arc::new(Host::new(common::host_config(base)));
|
||||
let root = db::db_consoles_dir(&host).unwrap();
|
||||
assert_eq!(root.0, base.join("data/consoles/db"));
|
||||
assert!(root.0.is_dir());
|
||||
}
|
||||
@@ -542,6 +542,23 @@ impl Smoke {
|
||||
self.restore(doc, &before).await;
|
||||
}
|
||||
|
||||
/// Completion at the end of the typed line, once it offers the auto-import `control`, has
|
||||
/// none labelled `label`.
|
||||
async fn not_offered(&self, typed: Typed, label: &str, control: &str) {
|
||||
let (doc, pos, before) = self.type_line(typed).await;
|
||||
self.retry("completion without the item", self.warm_up, || async {
|
||||
let list = ops::lsp::lsp_completion(&self.host, WINDOW, RequestId(7), doc, pos, None).await;
|
||||
let labels: Vec<String> = match list {
|
||||
Ok(l) => l.items.into_iter().map(|i| i.label).collect(),
|
||||
Err(e) => vec![e.to_string()],
|
||||
};
|
||||
let has = |name: &str| labels.iter().any(|l| l == name);
|
||||
if has(control) && !has(label) { Ok(()) } else { Err(labels) }
|
||||
})
|
||||
.await;
|
||||
self.restore(doc, &before).await;
|
||||
}
|
||||
|
||||
async fn organize_imports(&self, import: Typed, expect: Imports) {
|
||||
let (doc, _, before) = self.type_line(import).await;
|
||||
let typed = import.text.trim();
|
||||
@@ -696,6 +713,71 @@ async fn typescript() {
|
||||
smoke("typescript", TYPESCRIPT).await;
|
||||
}
|
||||
|
||||
/// Code Style › TypeScript › Imports (#6072): each change reaches the running vtsls, and its
|
||||
/// auto-imports follow it: relative or path alias, `/index` or not, and excluded files and
|
||||
/// specifiers left out.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "language smoke: needs vtsls"]
|
||||
async fn typescript_import_style() {
|
||||
let checks = Checks {
|
||||
files: &[
|
||||
(
|
||||
"tsconfig.json",
|
||||
r#"{"compilerOptions": {"module": "ESNext", "moduleResolution": "Bundler", "strict": true,
|
||||
"noEmit": true, "allowImportingTsExtensions": true, "paths": {"@/*": ["./src/*"]}},
|
||||
"include": ["src"]}"#,
|
||||
),
|
||||
("src/lib/alpha.ts", "export function alphaHelper(): number {\n return 1;\n}\n"),
|
||||
// Never excluded, and matching what is typed (tsserver offers only those): the
|
||||
// auto-import candidates are in the completion list.
|
||||
("src/lib/betaWord.ts", "export function betaWord(): number {\n return 3;\n}\n"),
|
||||
("src/lib/hints.ts", "export function alphaHint(): number {\n return 4;\n}\n"),
|
||||
("src/app/components/index.ts", "export function betaWidget(): number {\n return 2;\n}\n"),
|
||||
("src/app/main.ts", "export const ready = true;\n"),
|
||||
("src/app/other.ts", "export const other = true;\n"),
|
||||
("src/app/third.ts", "export const third = true;\n"),
|
||||
("src/app/fourth.ts", "export const fourth = true;\n"),
|
||||
("src/app/fifth.ts", "export const fifth = true;\n"),
|
||||
],
|
||||
..TYPESCRIPT
|
||||
};
|
||||
let smoke = Smoke::start("typescript", &checks).await;
|
||||
let set = |key: &str, value: &str| {
|
||||
let scope = ide_workspace::settings::SettingsScope::Project;
|
||||
let key = format!("editor.codeStyle.languages.typescript.{key}");
|
||||
ops::project::settings_set(&smoke.host, WINDOW, scope, key, value.into()).unwrap();
|
||||
};
|
||||
let alpha = typed("src/app/main.ts", "export const ready", "alphaH");
|
||||
let beta = typed("src/app/main.ts", "export const ready", "betaW");
|
||||
let import = |typed, label, result| AutoImport { typed, label, result };
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
set("importModuleSpecifier", r#""non-relative""#);
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
set("importModuleSpecifierEnding", r#""index""#);
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
|
||||
set("importModuleSpecifierEnding", r#""minimal""#);
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
|
||||
// tsserver keeps the auto-import candidates of the file it last completed in until the
|
||||
// program changes; other files see an exclusion at once.
|
||||
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#);
|
||||
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
|
||||
smoke.not_offered(typed("src/app/third.ts", "export const third", "alphaH"), "alphaHelper", "alphaHint").await;
|
||||
|
||||
// Emptied lists reach the server too: the symbols are offered again.
|
||||
set("autoImportFileExcludePatterns", "[]");
|
||||
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
set("autoImportSpecifierExcludeRegexes", "[]");
|
||||
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
}
|
||||
|
||||
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
|
||||
#[cfg(unix)]
|
||||
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
|
||||
|
||||
@@ -731,6 +731,38 @@ async fn reformat_uses_the_formatter_chain_and_preserves_a_dirty_buffer() {
|
||||
assert!(p.documents.is_dirty(doc.id).unwrap());
|
||||
}
|
||||
|
||||
/// Answers `execute_run_configuration`'s window requests the way the Run tool window does:
|
||||
/// starts the configuration in a tab and says whether it started. Returns what it started.
|
||||
fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>> {
|
||||
let started = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let (host, events, out) = (h.host.clone(), h.events.clone(), started.clone());
|
||||
tokio::spawn(async move {
|
||||
let mut handled = std::collections::HashSet::new();
|
||||
loop {
|
||||
let request = events.lock().unwrap().iter().find_map(|e| match e {
|
||||
IdeEvent::McpRequest { id, request: ide_core::event::McpUiRequest::RunConfiguration { config } }
|
||||
if !handled.contains(id) =>
|
||||
{
|
||||
Some((*id, config.clone()))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let Some((id, config)) = request else {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
continue;
|
||||
};
|
||||
handled.insert(id);
|
||||
let config: ide_run::RunConfig = serde_json::from_value(config).unwrap();
|
||||
out.lock().unwrap().push(config.clone());
|
||||
let result =
|
||||
ide_host::ops::run::run_start(&host, "main", config, ide_host::ops::Channel::new(|_| {}), None).await;
|
||||
let error = result.err().map(|e| e.message);
|
||||
let _ = host.mcp_requests.answer("main", id, error.is_none(), error);
|
||||
}
|
||||
});
|
||||
started
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
let h = Harness::new();
|
||||
@@ -765,6 +797,7 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
assert!(error.contains("denied by the user"));
|
||||
assert!(h.host.processes.list().is_empty());
|
||||
h.events.lock().unwrap().clear();
|
||||
let tabs = config_run_window(&h);
|
||||
let run = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
|
||||
let allow = async {
|
||||
let id = h.request().await;
|
||||
@@ -773,6 +806,39 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
let (result, ()) = tokio::join!(run, allow);
|
||||
assert_eq!(result["exitCode"], 7);
|
||||
assert!(result["output"].as_str().unwrap().contains("captured-output"));
|
||||
// It ran in a Run tool window tab, as the user's Run would.
|
||||
let tabs = tabs.lock().unwrap();
|
||||
assert_eq!(tabs.len(), 1);
|
||||
assert_eq!(tabs[0].name, "MCP test");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let config = ide_run::RunConfig {
|
||||
id: "test".into(),
|
||||
name: "MCP test".into(),
|
||||
kind: "shell".into(),
|
||||
command: if cfg!(windows) { "echo windowless& exit 3" } else { "echo windowless; exit 3" }.into(),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
h.host
|
||||
.global_settings
|
||||
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
|
||||
.unwrap();
|
||||
let result = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})).await;
|
||||
assert_eq!(result["exitCode"], 3, "{result}");
|
||||
assert!(result["output"].as_str().unwrap().contains("windowless"));
|
||||
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -795,6 +861,7 @@ async fn a_configuration_left_running_is_stopped_by_its_run_id() {
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let _tabs = config_run_window(&h);
|
||||
let run = h.json("execute_run_configuration", json!({"configurationName":"Server","waitForExit":false}));
|
||||
let allow = async {
|
||||
let id = h.request().await;
|
||||
|
||||
@@ -429,9 +429,10 @@ fn gutter_actions_see_the_editors_window_project() {
|
||||
assert_eq!(actions.len(), 1);
|
||||
actions[0].1.argument.clone().unwrap()
|
||||
};
|
||||
// The outer project's window: the file is its, though the inner project holds it too.
|
||||
assert_eq!(argument(Some(&outer)), outer.to_string_lossy());
|
||||
assert_eq!(argument(Some(&inner)), inner.to_string_lossy());
|
||||
// The outer project's window: the file is its, though the inner project holds it too. Compared
|
||||
// as paths: the plugin sees Windows paths `/`-separated.
|
||||
assert_eq!(Path::new(&argument(Some(&outer))), outer);
|
||||
assert_eq!(Path::new(&argument(Some(&inner))), inner);
|
||||
// No window, or a root that is no open project: no invoking project.
|
||||
assert_eq!(argument(None), "gutter");
|
||||
assert_eq!(argument(Some(&tmp.path().join("elsewhere"))), "gutter");
|
||||
|
||||
@@ -52,7 +52,8 @@ fn the_plugins_configuration_completes_only_the_argument_under_the_caret() {
|
||||
let config = "plugin:test.run-anything:tasks";
|
||||
// Not provided until its program is approved.
|
||||
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 1).is_err());
|
||||
p.choose_program(ID, "process:task", Some(&root), Some(Path::new("/bin/echo"))).unwrap();
|
||||
// Any approved executable will do; the test binary exists on every host.
|
||||
p.choose_program(ID, "process:task", Some(&root), Some(&std::env::current_exe().unwrap())).unwrap();
|
||||
assert!(p.run_detection().detect(&root).iter().any(|c| c.id == config));
|
||||
let complete = |text: &str, caret: u32| -> Vec<(String, String, u32, u32)> {
|
||||
p.run_configuration_complete("main", &root, config, "arguments", text, caret)
|
||||
|
||||
@@ -6794,6 +6794,8 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
let mut req = vec![0; len];
|
||||
let _ = reader.read_exact(&mut req);
|
||||
let body = "plain ok";
|
||||
// Recorded before the reply: the client may assert as soon as it reads it.
|
||||
seen.lock().push("served".into());
|
||||
let _ = writer.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
|
||||
@@ -6801,7 +6803,6 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
seen.lock().push("served".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ mod common;
|
||||
|
||||
use ide_core::{Pos, RequestId};
|
||||
use ide_host::{Host, ops};
|
||||
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery};
|
||||
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery, SearchScope};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
|
||||
@@ -145,9 +145,10 @@ async fn replace_all_covers_matches_past_the_limit() {
|
||||
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let scope = base.join("scope");
|
||||
let root = scope.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt", "stale.txt"] {
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
|
||||
std::fs::write(root.join(name), "TOKEN\n").unwrap();
|
||||
}
|
||||
let host = Host::new(common::host_config(&base));
|
||||
@@ -157,14 +158,18 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
project.documents.open(&root.join("previewed.txt")).unwrap();
|
||||
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
|
||||
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
|
||||
// Open and clean, but changed on disk before the watcher reported it.
|
||||
let stale = project.documents.open(&root.join("stale.txt")).unwrap().id;
|
||||
std::fs::write(root.join("stale.txt"), "TOKEN\nexternal\n").unwrap();
|
||||
// Search the parent folder so Replace All also covers a clean buffer outside the project watch.
|
||||
let stale_path = scope.join("stale.txt");
|
||||
std::fs::write(&stale_path, "TOKEN\n").unwrap();
|
||||
let stale = project.documents.open(&stale_path).unwrap().id;
|
||||
std::fs::write(&stale_path, "TOKEN\nexternal\n").unwrap();
|
||||
let mut search = query("TOKEN", false);
|
||||
search.scope = SearchScope::Directory { path: scope.into() };
|
||||
ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query("TOKEN", false),
|
||||
search,
|
||||
"DONE".into(),
|
||||
false,
|
||||
vec![],
|
||||
@@ -178,7 +183,8 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
assert_eq!(disk("closed.txt"), "DONE\n");
|
||||
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
|
||||
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
|
||||
assert_eq!(disk("stale.txt"), "TOKEN\nexternal\n", "the external change is kept");
|
||||
assert_eq!(std::fs::read_to_string(&stale_path).unwrap(), "TOKEN\nexternal\n", "the external change is kept");
|
||||
assert_eq!(project.documents.text_snapshot(stale).unwrap().text, "DONE\n");
|
||||
assert!(project.documents.is_dirty(stale).unwrap(), "the replacement stays unsaved");
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
@@ -80,14 +80,23 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
assert_eq!(opened["name"], "demo");
|
||||
assert_eq!(opened["trusted"], false);
|
||||
invoke(&peer, "index_status", json!({})).await.unwrap();
|
||||
let metrics = invoke(&peer, "host_metrics", json!({ "includeProcesses": true })).await.unwrap();
|
||||
assert!(metrics["cpuCores"].as_u64().unwrap() >= 1);
|
||||
assert_eq!(metrics["processes"][0]["label"], "Backend");
|
||||
assert_eq!(invoke(&peer, "lsp_servers", json!({})).await.unwrap(), json!([]));
|
||||
invoke(&peer, "lsp_resend_diagnostics", json!({})).await.unwrap();
|
||||
let files = invoke(&peer, "find_files", json!({"query": "main", "limit": 10})).await.unwrap();
|
||||
assert!(files.is_array());
|
||||
for command in
|
||||
["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start", "agent_refresh_models"]
|
||||
{
|
||||
let error = invoke(&peer, command, json!({})).await.unwrap_err();
|
||||
for (command, args) in [
|
||||
("build_sync", json!({})),
|
||||
("run_start", json!({})),
|
||||
("sdk_locate_tools", json!({})),
|
||||
("notebook_execute", json!({})),
|
||||
("debug_start", json!({})),
|
||||
("agent_refresh_models", json!({})),
|
||||
("host_end_process", json!({ "pid": 1 })),
|
||||
] {
|
||||
let error = invoke(&peer, command, args).await.unwrap_err();
|
||||
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
|
||||
}
|
||||
let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) };
|
||||
@@ -271,6 +280,9 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(env["DOCKER_HOST"], "unix:///run/user/1/docker.sock");
|
||||
// Services › Docker commands are served by the project host too.
|
||||
assert!(Dispatcher::standard().commands().contains(&"docker_snapshot"));
|
||||
assert_eq!(invoke(&peer, "docker_settings", json!({})).await.unwrap()["connections"], json!([]));
|
||||
|
||||
// Real project-host ignore writes travel through the remote command dispatcher.
|
||||
assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
|
||||
@@ -391,6 +403,8 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"http_curl",
|
||||
"http_environment_file",
|
||||
"http_variable_definitions",
|
||||
"db_source_folders",
|
||||
"db_save_source_folders",
|
||||
"db_sources",
|
||||
"db_save_sources",
|
||||
"db_set_password",
|
||||
@@ -420,6 +434,7 @@ async fn local_deployment_runs_on_the_project_host() {
|
||||
"db_table_page",
|
||||
"db_apply_edits",
|
||||
"db_console_path",
|
||||
"db_consoles_dir",
|
||||
"db_consoles",
|
||||
"ssh_test",
|
||||
"ssh_set_secret",
|
||||
|
||||
@@ -50,3 +50,25 @@ async fn find_in_files_decodes_closed_files_with_the_project_encoding() {
|
||||
project.documents.set_file_defaults(defaults);
|
||||
assert!(find(&host, "中文搜索验证").await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn find_in_files_decodes_closed_files_with_the_editorconfig_charset() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
std::fs::write(root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
|
||||
std::fs::write(root.join("A.java"), b"// a\xe7\xe3o \xa4 needle\n").unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
let mut defaults = project.documents.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
project.documents.set_file_defaults(defaults);
|
||||
|
||||
let files = find(&host, "ação €").await;
|
||||
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(files[0].matches[0].text, "// ação € needle", "the text the editor shows");
|
||||
assert_eq!(find(&host, "needle").await[0].matches[0].text, "// ação € needle");
|
||||
}
|
||||
@@ -29,7 +29,9 @@ pub use syntax::{
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
pub use syntax::{
|
||||
MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases,
|
||||
MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule,
|
||||
PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases, resolve_fixture,
|
||||
visible_fixtures,
|
||||
};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
|
||||
@@ -89,12 +89,42 @@ fn has_toml_table(file: &Path, table: &str) -> bool {
|
||||
table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table)
|
||||
}
|
||||
|
||||
/// `file` parses as JSON and has the dotted `key` with a value other than `null`:
|
||||
/// an object (`eslintConfig`) or a dependency's version (`dependencies.tailwindcss`).
|
||||
/// `file` parses as JSON (with comments: `tsconfig.json`) and has the dotted `key` with a value
|
||||
/// other than `null` or `false`: an object (`eslintConfig`), a dependency's version
|
||||
/// (`dependencies.tailwindcss`) or a switch that is on (`cmkOptions.enabled`).
|
||||
fn has_json_key(file: &Path, key: &str) -> bool {
|
||||
let Ok(text) = std::fs::read_to_string(file) else { return false };
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
|
||||
key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(|v| !v.is_null())
|
||||
json_key(file, key, 0).is_some_and(|v| !v.is_null() && v != serde_json::Value::Bool(false))
|
||||
}
|
||||
|
||||
/// The dotted `key` of the JSON `file`. A tsconfig.json / jsconfig.json without it inherits it
|
||||
/// through `extends` from a local file (`./base`, `../tsconfig.base.json`), the first one defining
|
||||
/// it winning, as CSS Modules Kit reads `cmkOptions`.
|
||||
fn json_key(file: &Path, key: &str, depth: usize) -> Option<serde_json::Value> {
|
||||
// ponytail: package `extends` (`@tsconfig/node20`) are not resolved; only local files.
|
||||
const MAX_DEPTH: usize = 8;
|
||||
let text = std::fs::read_to_string(file).ok()?;
|
||||
let value = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text)).ok()?;
|
||||
if let Some(v) = key.split('.').try_fold(&value, |v, key| v.get(key)) {
|
||||
return Some(v.clone());
|
||||
}
|
||||
let name = file.file_name()?.to_string_lossy();
|
||||
if depth >= MAX_DEPTH || !(name.starts_with("tsconfig") || name.starts_with("jsconfig")) {
|
||||
return None;
|
||||
}
|
||||
let extends = match value.get("extends")? {
|
||||
serde_json::Value::String(s) => vec![s.as_str()],
|
||||
serde_json::Value::Array(a) => a.iter().filter_map(serde_json::Value::as_str).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
extends.into_iter().filter(|e| e.starts_with("./") || e.starts_with("../")).find_map(|e| {
|
||||
let base = file.parent()?.join(e);
|
||||
let base = if base.is_file() {
|
||||
base
|
||||
} else {
|
||||
base.with_file_name(format!("{}.json", base.file_name()?.to_string_lossy()))
|
||||
};
|
||||
json_key(&base, key, depth + 1)
|
||||
})
|
||||
}
|
||||
|
||||
/// `path` is (or, after its creation or removal, was) a root marker of the
|
||||
@@ -191,6 +221,28 @@ mod tests {
|
||||
std::fs::write(dir.join("package.json"), r#"{"eslintConfig": null}"#).unwrap();
|
||||
assert!(!has_marker(dir, "package.json#eslintConfig"));
|
||||
assert!(is_marker_path(&dir.join("package.json"), marker));
|
||||
// tsconfig.json is JSON with comments; a switch that is off is no marker.
|
||||
let cmk = "tsconfig.json#cmkOptions.enabled";
|
||||
let tsconfig =
|
||||
|enabled: &str| format!("{{\n // CSS Modules Kit\n \"cmkOptions\": {{ \"enabled\": {enabled} }},\n}}");
|
||||
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
|
||||
assert!(has_marker(dir, cmk));
|
||||
std::fs::write(dir.join("tsconfig.json"), tsconfig("false")).unwrap();
|
||||
assert!(!has_marker(dir, cmk));
|
||||
// Inherited through a local `extends`, which the file itself can turn off.
|
||||
std::fs::create_dir_all(dir.join("app")).unwrap();
|
||||
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
|
||||
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": ["@tsconfig/strictest", "../tsconfig"] }"#)
|
||||
.unwrap();
|
||||
assert!(has_marker(&dir.join("app"), cmk));
|
||||
std::fs::write(
|
||||
dir.join("app/tsconfig.json"),
|
||||
r#"{ "extends": "../tsconfig.json", "cmkOptions": { "enabled": false } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!has_marker(&dir.join("app"), cmk));
|
||||
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": "./tsconfig.json" }"#).unwrap();
|
||||
assert!(!has_marker(&dir.join("app"), cmk), "a cycle ends");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -63,6 +63,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("lua", include_str!("../../../languages/lua.toml")),
|
||||
("makefile", include_str!("../../../languages/makefile.toml")),
|
||||
("markdown", include_str!("../../../languages/markdown.toml")),
|
||||
("mdx", include_str!("../../../languages/mdx.toml")),
|
||||
("nix", include_str!("../../../languages/nix.toml")),
|
||||
("objective-c", include_str!("../../../languages/objective-c.toml")),
|
||||
("objective-cpp", include_str!("../../../languages/objective-cpp.toml")),
|
||||
@@ -1073,6 +1074,8 @@ mod tests {
|
||||
assert_eq!(detect("shop/templates/shop/product_list.html"), "django-html");
|
||||
assert_eq!(detect("shop/templates/shop/email/order.txt"), "django-html");
|
||||
assert_eq!(detect("pages/promo.html"), "html");
|
||||
// No `[debugger]` of its own: `find_config` would take it for debugpy instead of Python's.
|
||||
assert!(reg.get(&LanguageId::new("django-html")).unwrap().debugger.is_none());
|
||||
}
|
||||
|
||||
/// #4061: the project root is canonical; a template reached under another
|
||||
@@ -1281,6 +1284,7 @@ mod tests {
|
||||
("Views/MainWindow.axaml", "axaml"),
|
||||
("MainWindow.xaml", "xml"),
|
||||
("README.md", "markdown"),
|
||||
("Intro.mdx", "mdx"),
|
||||
("Dockerfile", "dockerfile"),
|
||||
("Dockerfile.dev", "dockerfile"),
|
||||
("Makefile", "makefile"),
|
||||
@@ -1362,6 +1366,22 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indented_sass_has_its_own_server() {
|
||||
let reg = reg();
|
||||
let names = |lang: &str| -> Vec<String> {
|
||||
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
|
||||
};
|
||||
assert_eq!(names("sass"), ["some-sass-language-server"]);
|
||||
let sass = ®.get(&LanguageId::new("sass")).unwrap().language_servers[0];
|
||||
assert_eq!(sass.settings.as_ref().and_then(|s| s.get("somesass")), Some(&serde_json::json!({})));
|
||||
for lang in ["scss", "css", "less"] {
|
||||
let names = names(lang);
|
||||
assert_eq!(names[0], "vscode-css-language-server", "{lang}");
|
||||
assert!(!names.iter().any(|n| n == "some-sass-language-server"), "{lang}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn astro_server_leaves_typescript_sdk_resolution_to_the_launcher() {
|
||||
let reg = reg();
|
||||
|
||||
@@ -13,6 +13,7 @@ mod literals;
|
||||
mod outline;
|
||||
mod php_align;
|
||||
mod python_facts;
|
||||
mod python_fixtures;
|
||||
mod python_imports;
|
||||
mod rearrange;
|
||||
mod rst;
|
||||
@@ -35,6 +36,10 @@ pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
|
||||
pub use outline::{merge_kinds, merge_visibility};
|
||||
pub use php_align::PhpAlignment;
|
||||
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression};
|
||||
pub use python_fixtures::{
|
||||
PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule, resolve_fixture,
|
||||
visible_fixtures,
|
||||
};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -0,0 +1,564 @@
|
||||
//! pytest fixtures in one Python module: the fixtures it defines (`@pytest.fixture`), the
|
||||
//! places it names one (a test's or fixture's parameters, `usefixtures("x")`,
|
||||
//! `getfixturevalue("x")`) and the plugin modules it loads (`pytest_plugins`). From the
|
||||
//! syntax tree only; [`resolve_fixture`] then picks the definition pytest uses, given the
|
||||
//! modules a test sees, nearest first.
|
||||
|
||||
use super::lines::LineIndex;
|
||||
use crate::{LanguageId, Syntax};
|
||||
use ide_core::{Pos, Range};
|
||||
use tree_sitter::{Node, Tree};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PytestModule {
|
||||
pub fixtures: Vec<PytestFixture>,
|
||||
pub uses: Vec<PytestFixtureUse>,
|
||||
/// Where a fixture name may be typed: completion offers the visible fixtures there.
|
||||
pub slots: Vec<PytestFixtureSlot>,
|
||||
/// Modules named by a module-level `pytest_plugins`, as written (`pkg.fixtures`).
|
||||
pub plugins: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PytestFixture {
|
||||
/// The name tests ask for: the `name=` argument, else the function's name.
|
||||
pub name: String,
|
||||
/// That name in the source: the function name, or the `name=` string's content.
|
||||
pub selection: Range,
|
||||
/// The class whose method it is; only that class's tests see it.
|
||||
pub class: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PytestFixtureUseKind {
|
||||
Parameter,
|
||||
UseFixtures,
|
||||
GetFixtureValue,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PytestFixtureUse {
|
||||
pub name: String,
|
||||
pub range: Range,
|
||||
pub kind: PytestFixtureUseKind,
|
||||
pub class: Option<String>,
|
||||
/// The fixture whose parameter this is: `def tasks(tasks)` asks for the next `tasks` outward.
|
||||
pub in_fixture: Option<String>,
|
||||
/// For a parameter: the names in the function's body that read it (attribute names and
|
||||
/// keyword argument names left out), which a rename of the fixture renames too.
|
||||
pub body: Vec<Range>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PytestFixtureSlot {
|
||||
/// A test's or fixture's parameter list, or the content of a `usefixtures` /
|
||||
/// `getfixturevalue` string (empty strings included).
|
||||
pub range: Range,
|
||||
pub class: Option<String>,
|
||||
}
|
||||
|
||||
impl PytestModule {
|
||||
/// The use whose name covers `pos` (its end included, where a caret after the name sits).
|
||||
pub fn use_at(&self, pos: Pos) -> Option<&PytestFixtureUse> {
|
||||
self.uses.iter().find(|u| u.range.start <= pos && pos <= u.range.end)
|
||||
}
|
||||
|
||||
/// The fixture whose name (function name or `name=` string) covers `pos`.
|
||||
pub fn definition_at(&self, pos: Pos) -> Option<usize> {
|
||||
self.fixtures.iter().position(|f| f.selection.start <= pos && pos <= f.selection.end)
|
||||
}
|
||||
|
||||
/// The slot holding `pos`.
|
||||
pub fn slot_at(&self, pos: Pos) -> Option<&PytestFixtureSlot> {
|
||||
self.slots.iter().filter(|s| s.range.start <= pos && pos <= s.range.end).min_by_key(|s| s.range.end)
|
||||
}
|
||||
}
|
||||
|
||||
impl Syntax {
|
||||
/// The pytest fixtures a Python `text` defines and names; empty for other languages.
|
||||
pub fn pytest_module(&self, lang: &LanguageId, text: &str) -> PytestModule {
|
||||
self.analyze(lang, text, |g, tree, text| (g.spec.name == "python").then(|| extract(tree, text)))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The fixture pytest uses for a name asked in `layers[0]` (the module), `class` being the
|
||||
/// asking test's class, the later layers being the `conftest.py` files from the module's
|
||||
/// folder upward, then plugins and pytest's own modules. `overriding`: the asker is a fixture
|
||||
/// of that same name, which gets the next definition outward. Returns (layer, fixture) indexes.
|
||||
pub fn resolve_fixture(
|
||||
layers: &[&PytestModule],
|
||||
name: &str,
|
||||
class: Option<&str>,
|
||||
overriding: bool,
|
||||
) -> Option<(usize, usize)> {
|
||||
visible(layers, class).filter(|&(l, f)| layers[l].fixtures[f].name == name).nth(usize::from(overriding))
|
||||
}
|
||||
|
||||
/// The fixtures a test of `class` in `layers[0]` sees, nearest first, one per name.
|
||||
pub fn visible_fixtures(layers: &[&PytestModule], class: Option<&str>) -> Vec<(usize, usize)> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
visible(layers, class).filter(|&(l, f)| seen.insert(layers[l].fixtures[f].name.as_str())).collect()
|
||||
}
|
||||
|
||||
/// Every fixture visible from `class` in `layers[0]`, nearest first: the class's own, then
|
||||
/// the module's, then each later layer's module-level ones. Within one scope the last
|
||||
/// definition of a name wins, as Python rebinds it.
|
||||
fn visible<'a>(layers: &'a [&'a PytestModule], class: Option<&'a str>) -> impl Iterator<Item = (usize, usize)> + 'a {
|
||||
let scopes = layers.iter().enumerate().flat_map(move |(l, m)| {
|
||||
let own = (l == 0).then_some(class).flatten().map(|c| (l, m, Some(c)));
|
||||
own.into_iter().chain(std::iter::once((l, m, None)))
|
||||
});
|
||||
scopes.flat_map(|(l, m, scope)| {
|
||||
let mut picked: Vec<(usize, usize)> = Vec::new();
|
||||
for (f, fixture) in m.fixtures.iter().enumerate().rev() {
|
||||
if fixture.class.as_deref() == scope && !picked.iter().any(|&(_, p)| m.fixtures[p].name == fixture.name) {
|
||||
picked.push((l, f));
|
||||
}
|
||||
}
|
||||
picked.reverse();
|
||||
picked
|
||||
})
|
||||
}
|
||||
|
||||
fn extract(tree: &Tree, text: &str) -> PytestModule {
|
||||
let idx = LineIndex::new(text);
|
||||
let mut out = PytestModule::default();
|
||||
let root = tree.root_node();
|
||||
let mut cursor = root.walk();
|
||||
for node in root.named_children(&mut cursor) {
|
||||
statement(node, None, text, &idx, &mut out);
|
||||
}
|
||||
// `usefixtures` / `getfixturevalue` calls wherever they are.
|
||||
let mut walker = root.walk();
|
||||
visit(&mut walker, &mut |node| {
|
||||
if node.kind() == "call" {
|
||||
fixture_call(node, text, &idx, &mut out);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// A top-level statement, or one in a class body (`class` set).
|
||||
fn statement(node: Node, class: Option<&str>, text: &str, idx: &LineIndex, out: &mut PytestModule) {
|
||||
let (definition, decorators) = match node.kind() {
|
||||
"decorated_definition" => {
|
||||
let mut c = node.walk();
|
||||
let decorators: Vec<Node> = node.children(&mut c).filter(|n| n.kind() == "decorator").collect();
|
||||
let Some(definition) = node.child_by_field_name("definition") else { return };
|
||||
(definition, decorators)
|
||||
}
|
||||
_ => (node, Vec::new()),
|
||||
};
|
||||
match definition.kind() {
|
||||
"function_definition" => function(definition, &decorators, class, &[], text, idx, out),
|
||||
"class_definition" if class.is_none() => {
|
||||
let Some(name) = definition.child_by_field_name("name") else { return };
|
||||
let name = text_of(name, text);
|
||||
let Some(body) = definition.child_by_field_name("body") else { return };
|
||||
// `@pytest.mark.parametrize` on the class names arguments of every test in it.
|
||||
let class_args = parametrized(&decorators, text, idx);
|
||||
let mut c = body.walk();
|
||||
for child in body.named_children(&mut c) {
|
||||
let (def, decs) = match child.kind() {
|
||||
"decorated_definition" => {
|
||||
let mut c2 = child.walk();
|
||||
let decs: Vec<Node> = child.children(&mut c2).filter(|n| n.kind() == "decorator").collect();
|
||||
match child.child_by_field_name("definition") {
|
||||
Some(d) => (d, decs),
|
||||
None => continue,
|
||||
}
|
||||
}
|
||||
_ => (child, Vec::new()),
|
||||
};
|
||||
if def.kind() == "function_definition" {
|
||||
function(def, &decs, Some(&name), &class_args, text, idx, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
"expression_statement" if class.is_none() => plugins(definition, text, idx, &mut out.plugins),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn function(
|
||||
def: Node,
|
||||
decorators: &[Node],
|
||||
class: Option<&str>,
|
||||
class_args: &[String],
|
||||
text: &str,
|
||||
idx: &LineIndex,
|
||||
out: &mut PytestModule,
|
||||
) {
|
||||
let Some(name_node) = def.child_by_field_name("name") else { return };
|
||||
let name = text_of(name_node, text);
|
||||
let fixture = decorators.iter().find_map(|d| fixture_decorator(*d, text, idx));
|
||||
let is_test = name.starts_with("test") && class.is_none_or(|c| c.starts_with("Test"));
|
||||
if fixture.is_none() && !is_test {
|
||||
return;
|
||||
}
|
||||
let fixture_name = fixture.as_ref().and_then(|f| f.as_ref().map(|(n, _)| n.clone())).unwrap_or(name.clone());
|
||||
if let Some(f) = &fixture {
|
||||
let selection = match f {
|
||||
Some((_, string)) => *string,
|
||||
None => idx.range(name_node.start_byte(), name_node.end_byte()),
|
||||
};
|
||||
out.fixtures.push(PytestFixture { name: fixture_name.clone(), selection, class: class.map(str::to_owned) });
|
||||
}
|
||||
let Some(params) = def.child_by_field_name("parameters") else { return };
|
||||
out.slots.push(PytestFixtureSlot {
|
||||
range: idx.range(params.start_byte(), params.end_byte()),
|
||||
class: class.map(str::to_owned),
|
||||
});
|
||||
// Arguments `parametrize` supplies are no fixtures (unless indirect).
|
||||
let mut skip: Vec<String> = parametrized(decorators, text, idx);
|
||||
skip.extend_from_slice(class_args);
|
||||
let mut c = params.walk();
|
||||
for (i, param) in params.named_children(&mut c).enumerate() {
|
||||
let ident = match param.kind() {
|
||||
"identifier" => param,
|
||||
"typed_parameter" => match param.named_child(0) {
|
||||
Some(n) if n.kind() == "identifier" => n,
|
||||
_ => continue,
|
||||
},
|
||||
// Defaulted parameters, `*args`, `**kwargs`: no fixtures.
|
||||
_ => continue,
|
||||
};
|
||||
let param_name = text_of(ident, text);
|
||||
if (i == 0 && class.is_some() && (param_name == "self" || param_name == "cls")) || skip.contains(¶m_name) {
|
||||
continue;
|
||||
}
|
||||
let body = def.child_by_field_name("body").map(|b| reads_of(b, ¶m_name, text, idx)).unwrap_or_default();
|
||||
out.uses.push(PytestFixtureUse {
|
||||
name: param_name,
|
||||
range: idx.range(ident.start_byte(), ident.end_byte()),
|
||||
kind: PytestFixtureUseKind::Parameter,
|
||||
class: class.map(str::to_owned),
|
||||
in_fixture: fixture.is_some().then(|| fixture_name.clone()),
|
||||
body,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifiers `name` in `body`, except attribute names (`x.name`) and keyword argument
|
||||
/// names (`f(name=…)`). A nested function that rebinds the name is not told apart.
|
||||
fn reads_of(body: Node, name: &str, text: &str, idx: &LineIndex) -> Vec<Range> {
|
||||
let mut out = Vec::new();
|
||||
let mut cursor = body.walk();
|
||||
visit(&mut cursor, &mut |n| {
|
||||
if n.kind() != "identifier" || text.get(n.byte_range()) != Some(name) {
|
||||
return;
|
||||
}
|
||||
let field_of = |parent: Node, field: &str| parent.child_by_field_name(field).is_some_and(|c| c.id() == n.id());
|
||||
if let Some(parent) = n.parent()
|
||||
&& ((parent.kind() == "attribute" && field_of(parent, "attribute"))
|
||||
|| (parent.kind() == "keyword_argument" && field_of(parent, "name")))
|
||||
{
|
||||
return;
|
||||
}
|
||||
out.push(idx.range(n.start_byte(), n.end_byte()));
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// `Some(None)` for `@pytest.fixture` / `@fixture(...)`, `Some(Some((name, range)))` with a
|
||||
/// `name="…"` argument, `None` for any other decorator.
|
||||
fn fixture_decorator(decorator: Node, text: &str, idx: &LineIndex) -> Option<Option<(String, Range)>> {
|
||||
let expr = decorator.named_child(0)?;
|
||||
let (callee, args) = match expr.kind() {
|
||||
"call" => (expr.child_by_field_name("function")?, expr.child_by_field_name("arguments")),
|
||||
_ => (expr, None),
|
||||
};
|
||||
let callee = text_of(callee, text);
|
||||
if callee != "fixture" && !callee.ends_with(".fixture") {
|
||||
return None;
|
||||
}
|
||||
let named = args.and_then(|args| {
|
||||
let mut c = args.walk();
|
||||
args.named_children(&mut c).find_map(|a| {
|
||||
if a.kind() != "keyword_argument" || a.child_by_field_name("name").map(|n| text_of(n, text))? != "name" {
|
||||
return None;
|
||||
}
|
||||
string_content(a.child_by_field_name("value")?, text, idx)
|
||||
})
|
||||
});
|
||||
Some(named)
|
||||
}
|
||||
|
||||
/// The argument names of `@pytest.mark.parametrize("a, b", …)` decorators that are passed
|
||||
/// directly (no `indirect=`).
|
||||
fn parametrized(decorators: &[Node], text: &str, idx: &LineIndex) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for d in decorators {
|
||||
let Some(call) = d.named_child(0).filter(|n| n.kind() == "call") else { continue };
|
||||
let Some(callee) = call.child_by_field_name("function") else { continue };
|
||||
if !text_of(callee, text).ends_with("parametrize") {
|
||||
continue;
|
||||
}
|
||||
let Some(args) = call.child_by_field_name("arguments") else { continue };
|
||||
let mut c = args.walk();
|
||||
let all: Vec<Node> = args.named_children(&mut c).collect();
|
||||
let indirect = all.iter().any(|a| {
|
||||
a.kind() == "keyword_argument"
|
||||
&& a.child_by_field_name("name").is_some_and(|n| text_of(n, text) == "indirect")
|
||||
&& a.child_by_field_name("value").is_some_and(|v| text_of(v, text) != "False")
|
||||
});
|
||||
if indirect {
|
||||
continue;
|
||||
}
|
||||
let first = all.iter().find(|a| a.kind() != "keyword_argument");
|
||||
let names: Vec<String> = match first {
|
||||
Some(n) if n.kind() == "string" => string_content(*n, text, idx)
|
||||
.map(|(s, _)| s.split(',').map(|p| p.trim().to_owned()).collect())
|
||||
.unwrap_or_default(),
|
||||
Some(n) if matches!(n.kind(), "list" | "tuple") => {
|
||||
let mut c = n.walk();
|
||||
n.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s)).collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
out.extend(names.into_iter().filter(|n| !n.is_empty()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `usefixtures("a", "b")` and `request.getfixturevalue("a")`.
|
||||
fn fixture_call(call: Node, text: &str, idx: &LineIndex, out: &mut PytestModule) {
|
||||
let Some(callee) = call.child_by_field_name("function") else { return };
|
||||
let callee_text = text_of(callee, text);
|
||||
let kind = if callee_text == "usefixtures" || callee_text.ends_with(".usefixtures") {
|
||||
PytestFixtureUseKind::UseFixtures
|
||||
} else if callee.kind() == "attribute"
|
||||
&& callee.child_by_field_name("attribute").is_some_and(|a| text_of(a, text) == "getfixturevalue")
|
||||
{
|
||||
PytestFixtureUseKind::GetFixtureValue
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
let Some(args) = call.child_by_field_name("arguments") else { return };
|
||||
let class = enclosing_class(call, text);
|
||||
let mut c = args.walk();
|
||||
for (i, arg) in args.named_children(&mut c).enumerate() {
|
||||
if kind == PytestFixtureUseKind::GetFixtureValue && i > 0 {
|
||||
break;
|
||||
}
|
||||
let Some((name, range)) = string_content(arg, text, idx) else { continue };
|
||||
out.slots.push(PytestFixtureSlot { range, class: class.clone() });
|
||||
if !name.is_empty() {
|
||||
out.uses.push(PytestFixtureUse {
|
||||
name,
|
||||
range,
|
||||
kind,
|
||||
class: class.clone(),
|
||||
in_fixture: None,
|
||||
body: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The top-level class a node is in, if any.
|
||||
fn enclosing_class(node: Node, text: &str) -> Option<String> {
|
||||
let mut at = node.parent();
|
||||
let mut class = None;
|
||||
while let Some(n) = at {
|
||||
if n.kind() == "class_definition" {
|
||||
class = n.child_by_field_name("name").map(|c| text_of(c, text));
|
||||
}
|
||||
at = n.parent();
|
||||
}
|
||||
class
|
||||
}
|
||||
|
||||
/// `pytest_plugins = "a"`, `= ["a", "b"]` or `= ("a",)`.
|
||||
fn plugins(statement: Node, text: &str, idx: &LineIndex, out: &mut Vec<String>) {
|
||||
let Some(assign) = statement.named_child(0).filter(|n| n.kind() == "assignment") else { return };
|
||||
if assign.child_by_field_name("left").map(|l| text_of(l, text)).as_deref() != Some("pytest_plugins") {
|
||||
return;
|
||||
}
|
||||
let Some(right) = assign.child_by_field_name("right") else { return };
|
||||
match right.kind() {
|
||||
"string" => out.extend(string_content(right, text, idx).map(|(s, _)| s)),
|
||||
"list" | "tuple" => {
|
||||
let mut c = right.walk();
|
||||
out.extend(right.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The content of a plain string literal and its range (between the quotes); none for
|
||||
/// f-strings, byte strings and concatenations.
|
||||
fn string_content(node: Node, text: &str, idx: &LineIndex) -> Option<(String, Range)> {
|
||||
if node.kind() != "string" {
|
||||
return None;
|
||||
}
|
||||
let mut c = node.walk();
|
||||
let parts: Vec<Node> = node.children(&mut c).collect();
|
||||
let start = parts.iter().find(|p| p.kind() == "string_start")?;
|
||||
let end = parts.iter().find(|p| p.kind() == "string_end")?;
|
||||
if text_of(*start, text).chars().any(|ch| matches!(ch, 'f' | 'F' | 'b' | 'B')) {
|
||||
return None;
|
||||
}
|
||||
if parts.iter().any(|p| p.kind() == "interpolation" || p.kind() == "escape_sequence") {
|
||||
return None;
|
||||
}
|
||||
let (from, to) = (start.end_byte(), end.start_byte());
|
||||
Some((text.get(from..to)?.to_owned(), idx.range(from, to)))
|
||||
}
|
||||
|
||||
fn text_of(node: Node, text: &str) -> String {
|
||||
text.get(node.byte_range()).unwrap_or_default().to_owned()
|
||||
}
|
||||
|
||||
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::*;
|
||||
|
||||
fn module(src: &str) -> PytestModule {
|
||||
static S: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
|
||||
S.get_or_init(Syntax::new).pytest_module(&LanguageId::new("python"), src)
|
||||
}
|
||||
|
||||
fn names(m: &PytestModule) -> Vec<String> {
|
||||
m.fixtures
|
||||
.iter()
|
||||
.map(|f| format!("{}{}", f.class.as_deref().map(|c| format!("{c}.")).unwrap_or_default(), f.name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn uses(m: &PytestModule) -> Vec<String> {
|
||||
m.uses.iter().map(|u| format!("{:?} {}", u.kind, u.name)).collect()
|
||||
}
|
||||
|
||||
const TEST_MODULE: &str = r#"import pytest
|
||||
from pytest import fixture
|
||||
|
||||
pytest_plugins = ["pkg.fixtures", "other"]
|
||||
pytestmark = pytest.mark.usefixtures("db")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tasks(tmp_path):
|
||||
return []
|
||||
|
||||
|
||||
@fixture(scope="module", name="client")
|
||||
def make_client(tasks, request):
|
||||
return request.getfixturevalue("server")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("title, expected", [("a", "a")])
|
||||
def test_add(tasks, title, expected, monkeypatch, flag=False, *args):
|
||||
pass
|
||||
|
||||
|
||||
def helper(tasks):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("client", "")
|
||||
class TestTasks:
|
||||
@pytest.fixture
|
||||
def tasks(self, tasks):
|
||||
return tasks
|
||||
|
||||
def test_one(self, tasks: list, capsys):
|
||||
pass
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn reads_definitions_uses_and_plugins() {
|
||||
let m = module(TEST_MODULE);
|
||||
assert_eq!(names(&m), ["tasks", "client", "TestTasks.tasks"]);
|
||||
assert_eq!(m.plugins, ["pkg.fixtures", "other"]);
|
||||
assert_eq!(
|
||||
uses(&m),
|
||||
[
|
||||
"Parameter tmp_path",
|
||||
"Parameter tasks",
|
||||
"Parameter request",
|
||||
"Parameter tasks",
|
||||
"Parameter monkeypatch",
|
||||
"Parameter tasks",
|
||||
"Parameter tasks",
|
||||
"Parameter capsys",
|
||||
"UseFixtures db",
|
||||
"GetFixtureValue server",
|
||||
"UseFixtures client",
|
||||
]
|
||||
);
|
||||
// `name=` is found by its string; the overriding class fixture knows it overrides.
|
||||
let client = &m.fixtures[1];
|
||||
assert_eq!((client.selection.start.line, client.selection.start.col), (12, 31));
|
||||
let own = m.uses.iter().find(|u| u.class.as_deref() == Some("TestTasks") && u.in_fixture.is_some()).unwrap();
|
||||
assert_eq!(own.in_fixture.as_deref(), Some("tasks"));
|
||||
// The empty `usefixtures` string is still a place to complete.
|
||||
assert!(m.slots.iter().any(|s| s.range.start == s.range.end));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_nearest_first_and_overrides_outward() {
|
||||
let m = module(TEST_MODULE);
|
||||
let conftest = module(
|
||||
"import pytest\n\n@pytest.fixture\ndef tasks():\n return [1]\n\n@pytest.fixture\ndef db():\n pass\n",
|
||||
);
|
||||
let builtins = module("from _pytest.fixtures import fixture\n\n@fixture\ndef tmp_path():\n pass\n");
|
||||
let layers = [&m, &conftest, &builtins];
|
||||
// In the class: its own `tasks`; at module level: the module's.
|
||||
assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), false), Some((0, 2)));
|
||||
assert_eq!(resolve_fixture(&layers, "tasks", None, false), Some((0, 0)));
|
||||
// The class fixture's `tasks` parameter: the module's; the module's own: conftest's.
|
||||
assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), true), Some((0, 0)));
|
||||
assert_eq!(resolve_fixture(&layers, "tasks", None, true), Some((1, 0)));
|
||||
assert_eq!(resolve_fixture(&layers, "db", None, false), Some((1, 1)));
|
||||
assert_eq!(resolve_fixture(&layers, "tmp_path", None, false), Some((2, 0)));
|
||||
assert_eq!(resolve_fixture(&layers, "missing", None, false), None);
|
||||
// Completion: one entry per name, nearest first; another class's fixtures are hidden.
|
||||
let visible: Vec<&str> =
|
||||
visible_fixtures(&layers, None).iter().map(|&(l, f)| layers[l].fixtures[f].name.as_str()).collect();
|
||||
assert_eq!(visible, ["tasks", "client", "db", "tmp_path"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_knows_its_reads_in_the_body() {
|
||||
let m = module("def test_a(tasks):\n tasks.add(tasks=tasks)\n other.tasks = len(tasks)\n");
|
||||
let u = &m.uses[0];
|
||||
let reads: Vec<(u32, u32)> = u.body.iter().map(|r| (r.start.line, r.start.col)).collect();
|
||||
assert_eq!(reads, [(1, 4), (1, 20), (2, 22)]);
|
||||
assert_eq!(m.definition_at(Pos::new(0, 6)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_definition_replaces_an_earlier_one() {
|
||||
let m = module("import pytest\n\n@pytest.fixture\ndef a():\n pass\n\n@pytest.fixture\ndef a():\n pass\n");
|
||||
assert_eq!(resolve_fixture(&[&m], "a", None, false), Some((0, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_use_and_slot_at_a_position() {
|
||||
let m = module(TEST_MODULE);
|
||||
// `def test_add(tasks, …` is on line 18; the caret right after `tasks`.
|
||||
let at = m.use_at(Pos::new(18, 18)).unwrap();
|
||||
assert_eq!(at.name, "tasks");
|
||||
assert!(m.slot_at(Pos::new(18, 13)).is_some());
|
||||
assert!(m.use_at(Pos::new(22, 11)).is_none(), "a plain function's parameters are no fixtures");
|
||||
}
|
||||
}
|
||||
@@ -38,27 +38,85 @@ struct Rewrite<'a> {
|
||||
impl Rewrite<'_> {
|
||||
fn run(mut self, tree: &Tree) -> Vec<TextEdit> {
|
||||
let mut imports = Vec::new();
|
||||
let mut chains = Vec::new();
|
||||
let mut idents = Vec::new();
|
||||
collect(tree.root_node(), &mut |n| match n.kind() {
|
||||
"import_statement" | "import_from_statement" => imports.push(n),
|
||||
"attribute" if !inside_import(n) => chains.push(n),
|
||||
"identifier" if !inside_import(n) => idents.push(n),
|
||||
_ => {}
|
||||
});
|
||||
let mut renamed: Vec<(String, String)> = Vec::new();
|
||||
// Unaliased `import a.b` that change: (name node, old, new). They bind `a`, used as `a.b.x`.
|
||||
let mut dotted: Vec<(Node, String, String)> = Vec::new();
|
||||
let mut kept: Vec<String> = Vec::new();
|
||||
for node in imports {
|
||||
if node.kind() == "import_statement" {
|
||||
self.import(node, &mut renamed);
|
||||
self.import(node, &mut dotted, &mut kept);
|
||||
} else {
|
||||
self.import_from(node);
|
||||
}
|
||||
}
|
||||
// `import a.b` is used as `a.b.x`: those chains follow the import.
|
||||
for node in chains {
|
||||
let t = self.src(node);
|
||||
if let Some((_, new)) = renamed.iter().find(|(old, _)| *old == t) {
|
||||
self.edit(node, new.clone());
|
||||
if dotted.is_empty() {
|
||||
return self.finish();
|
||||
}
|
||||
let root_of = |s: &str| s.split('.').next().unwrap_or_default().to_owned();
|
||||
let mut needed: Vec<(usize, String)> = Vec::new();
|
||||
for id in idents {
|
||||
let name = self.src(id);
|
||||
if !dotted.iter().any(|(_, old, _)| root_of(old) == name) || is_attribute_field(id) {
|
||||
continue;
|
||||
}
|
||||
// `a`, `a.b`, `a.b.x`: one edit per expression, on the longest prefix that moved.
|
||||
let mut spine = vec![id];
|
||||
while let Some(p) = spine
|
||||
.last()
|
||||
.and_then(|n| n.parent())
|
||||
.filter(|p| p.kind() == "attribute" && p.child_by_field_name("object") == spine.last().copied())
|
||||
{
|
||||
spine.push(p);
|
||||
}
|
||||
let key = |n: Node| self.src(n).chars().filter(|c| !c.is_whitespace()).collect::<String>();
|
||||
// ponytail: a bare `pkg` (no attribute) is never rewritten, it may be a parameter or a
|
||||
// local of the same name.
|
||||
if let Some((node, new)) =
|
||||
spine.iter().skip(1).rev().find_map(|&n| Some((n, map_module(&key(n), self.moves)?)))
|
||||
{
|
||||
self.edit(node, new);
|
||||
continue;
|
||||
}
|
||||
// A use the rewritten imports no longer bind (`pkg.helper()` after `import pkg.models` moved).
|
||||
if spine.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let used = key(*spine.last().unwrap_or(&id));
|
||||
for (i, (_, old, new)) in dotted.iter().enumerate() {
|
||||
let common: Vec<&str> = old
|
||||
.split('.')
|
||||
.zip(used.split('.'))
|
||||
.take(old.split('.').count() - 1)
|
||||
.take_while(|(a, b)| a == b)
|
||||
.map(|(a, _)| a)
|
||||
.collect();
|
||||
if common.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let prefix = common.join(".");
|
||||
let covered = |m: &String| *m == prefix || m.starts_with(&format!("{prefix}."));
|
||||
let gone = map_module(&prefix, self.moves).is_some();
|
||||
if !gone && !covered(new) && !kept.iter().any(covered) && !needed.contains(&(i, prefix.clone())) {
|
||||
needed.push((i, prefix));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, (node, _, new)) in dotted.iter().enumerate() {
|
||||
let extra: String = needed.iter().filter(|(j, _)| *j == i).map(|(_, p)| format!(", {p}")).collect();
|
||||
self.edits.push(TextEdit {
|
||||
range: self.idx.range(node.start_byte(), node.end_byte()),
|
||||
new_text: format!("{new}{extra}"),
|
||||
});
|
||||
}
|
||||
self.finish()
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Vec<TextEdit> {
|
||||
self.edits.sort_by_key(|e| (e.range.start.line, e.range.start.col));
|
||||
self.edits
|
||||
}
|
||||
@@ -72,7 +130,7 @@ impl Rewrite<'_> {
|
||||
}
|
||||
|
||||
/// `import a.b`, `import a.b as c`.
|
||||
fn import(&mut self, node: Node, renamed: &mut Vec<(String, String)>) {
|
||||
fn import<'t>(&mut self, node: Node<'t>, dotted: &mut Vec<(Node<'t>, String, String)>, kept: &mut Vec<String>) {
|
||||
let mut cursor = node.walk();
|
||||
for item in node.children_by_field_name("name", &mut cursor) {
|
||||
let (name, aliased) = match item.kind() {
|
||||
@@ -83,12 +141,16 @@ impl Rewrite<'_> {
|
||||
_ => (item, false),
|
||||
};
|
||||
let old = self.src(name).to_owned();
|
||||
let Some(new) = map_module(&old, self.moves) else { continue };
|
||||
let Some(new) = map_module(&old, self.moves) else {
|
||||
if !aliased {
|
||||
kept.push(old);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
if aliased {
|
||||
self.edit(name, new);
|
||||
} else if old.contains('.') {
|
||||
renamed.push((old, new.clone()));
|
||||
self.edit(name, new);
|
||||
dotted.push((name, old, new));
|
||||
} else {
|
||||
// The bound name stays, so the rest of the file needs no change.
|
||||
self.edit(name, format!("{new} as {old}"));
|
||||
@@ -166,18 +228,20 @@ impl Rewrite<'_> {
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (item, text) in &in_place {
|
||||
self.edit(*item, text.clone());
|
||||
}
|
||||
if moved.is_empty() {
|
||||
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
|
||||
self.edit(module, m);
|
||||
}
|
||||
for (item, text) in in_place {
|
||||
self.edit(item, text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// ponytail: a split statement loses a multi-line names list's layout; fine for the rare
|
||||
// "some names of one `from` moved elsewhere" case.
|
||||
let indent = line_indent(self.text, node.start_byte());
|
||||
// Names imported from elsewhere now go to statements of their own, after this one (or
|
||||
// after `;` when the statement shares its line: `try: from a import b, c`).
|
||||
let line_start = self.text[..node.start_byte()].rfind('\n').map_or(0, |i| i + 1);
|
||||
let before = &self.text[line_start..node.start_byte()];
|
||||
let sep = if before.trim().is_empty() { format!("\n{before}") } else { "; ".to_owned() };
|
||||
let mut parents: Vec<&str> = Vec::new();
|
||||
for m in &moved {
|
||||
if !parents.contains(&m.1.as_str()) {
|
||||
@@ -194,28 +258,46 @@ impl Rewrite<'_> {
|
||||
format!("from {from} import {}", items.join(", "))
|
||||
});
|
||||
}
|
||||
let kept: Vec<String> = names
|
||||
.iter()
|
||||
.filter(|n| !moved.iter().any(|m| m.0 == **n))
|
||||
.map(|n| in_place.iter().find(|(i, _)| i == n).map_or_else(|| self.src(*n).to_owned(), |(_, t)| t.clone()))
|
||||
.collect();
|
||||
let sep = format!("\n{indent}");
|
||||
if kept.is_empty() {
|
||||
let is_moved = |n: &Node| moved.iter().any(|m| m.0 == *n);
|
||||
let Some(last_kept) = names.iter().rposition(|n| !is_moved(n)) else {
|
||||
self.edit(node, added.join(&sep));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
|
||||
self.edit(module, m);
|
||||
}
|
||||
let (first, last) = (names[0], names[names.len() - 1]);
|
||||
let range = self.idx.range(first.start_byte(), last.end_byte());
|
||||
self.edits.push(TextEdit { range, new_text: kept.join(", ") });
|
||||
let mut trailing_done = false;
|
||||
for (i, item) in names.iter().enumerate().filter(|(_, n)| is_moved(n)) {
|
||||
let (start, end) = if let Some(line) = self.own_lines(*item) {
|
||||
line
|
||||
} else if i < last_kept {
|
||||
(item.start_byte(), names[i + 1].start_byte())
|
||||
} else if !trailing_done {
|
||||
trailing_done = true;
|
||||
(names[last_kept].end_byte(), names[names.len() - 1].end_byte())
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
self.edits.push(TextEdit { range: self.idx.range(start, end), new_text: String::new() });
|
||||
}
|
||||
let end = self.idx.pos(node.end_byte());
|
||||
self.edits.push(TextEdit {
|
||||
range: ide_core::Range { start: end, end },
|
||||
new_text: format!("{sep}{}", added.join(&sep)),
|
||||
});
|
||||
}
|
||||
|
||||
/// The whole lines of an import list item that has them to itself (` models, # noqa`).
|
||||
fn own_lines(&self, item: Node) -> Option<(usize, usize)> {
|
||||
let start = self.text[..item.start_byte()].rfind('\n').map_or(0, |i| i + 1);
|
||||
if !self.text[start..item.start_byte()].trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let end = self.text[item.end_byte()..].find('\n').map_or(self.text.len(), |i| item.end_byte() + i + 1);
|
||||
let rest = self.text[item.end_byte()..end].trim_start();
|
||||
let rest = rest.strip_prefix(',').unwrap_or(rest).trim();
|
||||
(rest.is_empty() || rest.starts_with('#')).then_some((start, end))
|
||||
}
|
||||
}
|
||||
|
||||
fn collect<'t>(node: Node<'t>, f: &mut impl FnMut(Node<'t>)) {
|
||||
@@ -236,9 +318,9 @@ fn inside_import(mut n: Node) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn line_indent(text: &str, byte: usize) -> &str {
|
||||
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
|
||||
&text[start..byte]
|
||||
/// `x` in `obj.x`.
|
||||
fn is_attribute_field(n: Node) -> bool {
|
||||
n.parent().is_some_and(|p| p.kind() == "attribute" && p.child_by_field_name("attribute") == Some(n))
|
||||
}
|
||||
|
||||
fn join(a: &str, b: &str) -> String {
|
||||
@@ -288,6 +370,11 @@ mod tests {
|
||||
let moves: Vec<(String, String)> = moves.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
|
||||
let mut edits = Syntax::new().python_import_edits(text, package, new_package, &moves);
|
||||
edits.sort_by_key(|e| std::cmp::Reverse((e.range.start.line, e.range.start.col)));
|
||||
// Like `ide-text`, which rejects a set of overlapping edits.
|
||||
for w in edits.windows(2) {
|
||||
let (later, earlier) = (&w[0].range, &w[1].range);
|
||||
assert!((earlier.end.line, earlier.end.col) <= (later.start.line, later.start.col), "overlap: {edits:?}");
|
||||
}
|
||||
let mut out = text.to_owned();
|
||||
for e in edits {
|
||||
let (s, t) = (byte_at(&out, e.range.start).unwrap(), byte_at(&out, e.range.end).unwrap());
|
||||
@@ -388,6 +475,64 @@ mod tests {
|
||||
assert_eq!(apply(src, "pkg", "pkg", RENAME), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_chains_get_one_edit() {
|
||||
let src = "import pkg.models\nimport pkg.models.sub\npkg.models.sub.f()\npkg.models.g()\n";
|
||||
assert_eq!(
|
||||
apply(src, "", "", &[("pkg", "lib.pkg")]),
|
||||
"import lib.pkg.models\nimport lib.pkg.models.sub\nlib.pkg.models.sub.f()\nlib.pkg.models.g()\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_uses_of_the_old_prefix_keep_their_binding() {
|
||||
let moves = &[("pkg.models", "core.models")];
|
||||
assert_eq!(
|
||||
apply("import pkg.models\n\npkg.models.Task()\npkg.helper()\n", "", "", moves),
|
||||
"import core.models, pkg\n\ncore.models.Task()\npkg.helper()\n"
|
||||
);
|
||||
let moves = &[("a.b.c", "a.x.c")];
|
||||
assert_eq!(
|
||||
apply("import a.b.c\na.b.c.f()\na.b.g()\n", "", "", moves),
|
||||
"import a.x.c, a.b\na.x.c.f()\na.b.g()\n"
|
||||
);
|
||||
// Inside a moved package the other uses follow it.
|
||||
assert_eq!(
|
||||
apply("import pkg.models\npkg.helper()\n", "", "", &[("pkg", "lib.pkg")]),
|
||||
"import lib.pkg.models\nlib.pkg.helper()\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_names_are_left_alone() {
|
||||
let src = "import pkg.models\ndef f(pkg):\n return pkg.models.x\n";
|
||||
assert_eq!(
|
||||
apply(src, "", "", &[("pkg", "lib.pkg")]),
|
||||
"import lib.pkg.models\ndef f(pkg):\n return lib.pkg.models.x\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_statements_stay_valid() {
|
||||
let moves = &[("pkg.models", "core.models")];
|
||||
assert_eq!(
|
||||
apply("try: from pkg import cli, models\nexcept ImportError: pass\n", "", "", moves),
|
||||
"try: from pkg import cli; from core import models\nexcept ImportError: pass\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply("import os; from pkg import cli, models\n", "", "", moves),
|
||||
"import os; from pkg import cli; from core import models\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply("from pkg import (\n models, # noqa: F401\n cli, # used below\n)\n", "", "", moves),
|
||||
"from pkg import (\n cli, # used below\n)\nfrom core import models\n"
|
||||
);
|
||||
assert_eq!(
|
||||
apply("from pkg import (\n cli, # used below\n models,\n)\n", "", "", moves),
|
||||
"from pkg import (\n cli, # used below\n)\nfrom core import models\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helpers() {
|
||||
assert_eq!(resolve(1, "m", "a.b").as_deref(), Some("a.b.m"));
|
||||
|
||||
@@ -28,6 +28,7 @@ percent-encoding = "2"
|
||||
zip.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
ide-sdk.workspace = true
|
||||
tempfile.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util"] }
|
||||
|
||||
Loaded 100 of 742 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача