дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 14:44:34 +02:00
Порівняти коміти
181
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
b0033a869d | ||
|
|
4ed4ced5b1 | ||
|
|
7668e4a5ba | ||
|
|
4a6e0dfac1 | ||
|
|
11e8f8a101 | ||
|
|
7a27f285e6 | ||
|
|
f21ae03bdd | ||
|
|
5dacbcd0cd | ||
|
|
281c2ff1e5 | ||
|
|
4276250056 | ||
|
|
ba04491ace | ||
|
|
660a311f21 | ||
|
|
92bf9354fe | ||
|
|
54da9c2c12 | ||
|
|
9ba3150998 | ||
|
|
190e5639f1 | ||
|
|
5f782e9c5d | ||
|
|
10fe5d21af | ||
|
|
16c30e819c | ||
|
|
43c8699beb | ||
|
|
071fbf7639 | ||
|
|
bde1e5f7a0 | ||
|
|
c1e8864138 | ||
|
|
5966d193c4 | ||
|
|
6d38521498 | ||
|
|
52e6a0f84b | ||
|
|
72873981aa | ||
|
|
d44a104ff8 | ||
|
|
23ea9cf07d | ||
|
|
cea3f4ac9c | ||
|
|
aee715f797 | ||
|
|
711349c6c1 | ||
|
|
9b2d783322 | ||
|
|
72ae354d29 | ||
|
|
dd8de05013 | ||
|
|
a547c8cdee | ||
|
|
a74d5b5dbb | ||
|
|
b895093f6b | ||
|
|
cbb9079577 | ||
|
|
44418411b8 | ||
|
|
5e23076766 | ||
|
|
689d3fd877 | ||
|
|
608ab44fca | ||
|
|
41545d38e5 | ||
|
|
4f86211dd6 | ||
|
|
203e4fbcb2 | ||
|
|
869e52f837 | ||
|
|
02e4c9c7a2 | ||
|
|
61be657209 | ||
|
|
52294c51c2 | ||
|
|
222d0b5ee3 | ||
|
|
cd8f29ea63 | ||
|
|
ba94abcb8b | ||
|
|
937eb0c3a0 | ||
|
|
b2d03ac5f0 | ||
|
|
4e735eadcb | ||
|
|
50ba6b5c56 | ||
|
|
36910712d1 | ||
|
|
5b99b8b5ab | ||
|
|
f3874b9b2e | ||
|
|
18b87b066b | ||
|
|
41a76ca0d7 | ||
|
|
1bf29ab3d7 | ||
|
|
49b52a8bfa | ||
|
|
77342b8e71 | ||
|
|
369ff7cec8 | ||
|
|
4016c410db | ||
|
|
3c3d02d7be | ||
|
|
2f66eb0503 | ||
|
|
63db10a688 | ||
|
|
1dd3d64781 | ||
|
|
8ac194cf50 | ||
|
|
3b488a7824 | ||
|
|
b5e89aace0 | ||
|
|
81c95b2ab7 | ||
|
|
f7b5cc388c | ||
|
|
277d0e9d1e | ||
|
|
d6adb7aa40 | ||
|
|
6e5e482410 | ||
|
|
cc02c2fe40 | ||
|
|
74a3f6470a | ||
|
|
4c8c078666 | ||
|
|
e672b14d52 | ||
|
|
c0300f8959 | ||
|
|
11cf9864a1 | ||
|
|
04a4d98d68 | ||
|
|
9a984f64a3 | ||
|
|
e35a607556 | ||
|
|
3fa990fce2 | ||
|
|
11e520dedb | ||
|
|
a0c0b69b4a | ||
|
|
b89128649f | ||
|
|
9973cad74c | ||
|
|
8cb7a2fe06 | ||
|
|
5d867d7d2d | ||
|
|
70f6678271 | ||
|
|
530388a79d | ||
|
|
98cb85003a | ||
|
|
dfae46868c | ||
|
|
635da15486 | ||
|
|
249d0526f0 | ||
|
|
181bbdfdc2 | ||
|
|
c7172184ad | ||
|
|
8380732e60 | ||
|
|
42fcbb336a | ||
|
|
93a450aa8c | ||
|
|
8e0a36fb1c | ||
|
|
11da3ecce7 | ||
|
|
53d295d785 | ||
|
|
9f1380cf04 | ||
|
|
338e1a5b02 | ||
|
|
092cde1319 | ||
|
|
fc1e1838ca | ||
|
|
9a9a536525 | ||
|
|
2d7928374e | ||
|
|
58eb5ae667 | ||
|
|
0698ebb9b0 | ||
|
|
647e564127 | ||
|
|
edd2e90b9b | ||
|
|
5bfefff5e1 | ||
|
|
49097bf5c0 | ||
|
|
09a44bebbe | ||
|
|
7237a37104 | ||
|
|
c864cec32f | ||
|
|
f7f2efaace | ||
|
|
e8cb141d86 | ||
|
|
3eb6933644 | ||
|
|
72669a04c2 | ||
|
|
0b9c675172 | ||
|
|
5188a34e3d | ||
|
|
8d26a9b483 | ||
|
|
267a61c581 | ||
|
|
21dfa8dd10 | ||
|
|
0cfabdbbbd | ||
|
|
485d7bf99d | ||
|
|
53a1e9255e | ||
|
|
40ab249cb8 | ||
|
|
9da3d6d9b5 | ||
|
|
0df7cb1da2 | ||
|
|
ee9b50179e | ||
|
|
baab92c804 | ||
|
|
2b7a18ffd7 | ||
|
|
f47a83828c | ||
|
|
4d5ee2d01c | ||
|
|
2ecb44098a | ||
|
|
b1039bc175 | ||
|
|
182c7c1dbb | ||
|
|
c8dc613485 | ||
|
|
88a6bbca14 | ||
|
|
b9e555300f | ||
|
|
7ff223001b | ||
|
|
cc9279a6d6 | ||
|
|
1cfbb24b31 | ||
|
|
a8a0cdb315 | ||
|
|
8ab776ada6 | ||
|
|
88b463d888 | ||
|
|
ac88059d0f | ||
|
|
a09c9aa9ad | ||
|
|
7fef1e10a8 | ||
|
|
1748c98ac8 | ||
|
|
399ae25ab6 | ||
|
|
f28dd8125b | ||
|
|
d5f7e0a99b | ||
|
|
a66c9e6d05 | ||
|
|
59bcf7eac5 | ||
|
|
fe21c67537 | ||
|
|
c085f52b59 | ||
|
|
0104ed63c1 | ||
|
|
a441b2a906 | ||
|
|
c4f7fec86c | ||
|
|
37a8aae018 | ||
|
|
acc48a4816 | ||
|
|
8301326289 | ||
|
|
4c71299745 | ||
|
|
08249ca5fd | ||
|
|
edd6746439 | ||
|
|
695424beb2 | ||
|
|
9943d71d02 | ||
|
|
e03c5507f7 | ||
|
|
745099feaa | ||
|
|
6894d0a4e3 |
No files matched your search
@@ -34,6 +34,7 @@ on:
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/core/cm/inlineBg.ts"
|
||||
- "src/editor/core/cm/localAppearance.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
@@ -109,7 +110,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-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|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|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$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|localAppearance)|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
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
name: Nightly
|
||||
|
||||
# Builds main every night, when it has moved since the last nightly, into a prerelease
|
||||
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
|
||||
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
|
||||
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
|
||||
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 18 * * *" # 02:00 Beijing
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: "Build even when main has not changed since the last nightly"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nightly
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
if: github.repository == 'l0ng-ai/openidea'
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
tag: ${{ steps.tag.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with: { ref: main, fetch-depth: 0 }
|
||||
- id: changed
|
||||
env:
|
||||
FORCE: ${{ inputs.force == true }}
|
||||
run: |
|
||||
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
|
||||
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
|
||||
echo "::notice::main has not changed since $last"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Version commit and tag
|
||||
id: tag
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
env:
|
||||
BUILD: ${{ github.run_number }}
|
||||
run: |
|
||||
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add -A
|
||||
git commit -q -m "chore: v$version"
|
||||
git tag "v$version"
|
||||
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
|
||||
git push origin "refs/tags/v$version"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
release:
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.tag != ''
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/release.yml
|
||||
with:
|
||||
tag: ${{ needs.prepare.outputs.tag }}
|
||||
nightly: true
|
||||
secrets: inherit
|
||||
|
||||
# Points the nightly channel at the new nightly and drops the old ones.
|
||||
channel:
|
||||
needs: [prepare, release]
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
TAG: ${{ needs.prepare.outputs.tag }}
|
||||
steps:
|
||||
- name: Nightly manifest
|
||||
run: |
|
||||
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
|
||||
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
|
||||
exit 0
|
||||
fi
|
||||
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
|
||||
if gh release view nightly >/dev/null 2>&1; then
|
||||
gh release edit nightly --notes "$notes"
|
||||
else
|
||||
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
|
||||
fi
|
||||
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
|
||||
- name: Drop old nightlies
|
||||
run: |
|
||||
gh release list --limit 200 --json tagName,createdAt \
|
||||
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
|
||||
while read -r old; do
|
||||
gh release delete "$old" --cleanup-tag --yes
|
||||
done
|
||||
@@ -7,17 +7,23 @@ on:
|
||||
tag:
|
||||
description: "Tag to release (e.g. v0.1.0); must already exist"
|
||||
required: true
|
||||
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
|
||||
# official plugins, the CNB mirror or the Homebrew cask.
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
nightly: { type: boolean, default: false }
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.event.inputs.tag || github.ref_name }}
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
TAG: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
TAG: ${{ inputs.tag || github.ref_name }}
|
||||
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
|
||||
|
||||
# The jobs that read a signing key or token, here and in the workflows called below, run in
|
||||
@@ -52,6 +58,8 @@ jobs:
|
||||
fi
|
||||
- id: release
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
env:
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
with:
|
||||
script: |
|
||||
const tag = process.env.TAG;
|
||||
@@ -63,8 +71,13 @@ jobs:
|
||||
core.setOutput("id", existing.id);
|
||||
return;
|
||||
}
|
||||
// Prereleases are skipped: the notes span stable release to stable release.
|
||||
const previous = releases.find((r) => !r.draft && !r.prerelease);
|
||||
// Prereleases are skipped: the notes span stable release to stable release. A
|
||||
// nightly's span from the newest published release, nightly or stable (not the
|
||||
// rolling `nightly` release, which only holds the channel's manifest).
|
||||
const nightly = process.env.NIGHTLY === "true";
|
||||
const previous = releases.find(
|
||||
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
|
||||
);
|
||||
const { data: notes } = await github.rest.repos.generateReleaseNotes({
|
||||
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
|
||||
});
|
||||
@@ -80,7 +93,7 @@ jobs:
|
||||
needs: create-release
|
||||
uses: ./.github/workflows/release-build.yml
|
||||
with:
|
||||
tag: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
tag: ${{ inputs.tag || github.ref_name }}
|
||||
release_id: ${{ needs.create-release.outputs.release_id }}
|
||||
secrets: inherit
|
||||
|
||||
@@ -102,10 +115,14 @@ jobs:
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
steps:
|
||||
- id: key
|
||||
run: |
|
||||
if [ -z "$SIGNING_KEY" ]; then
|
||||
if [ "$NIGHTLY" = true ]; then
|
||||
echo "a nightly does not publish the official plugins"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$SIGNING_KEY" ]; then
|
||||
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
@@ -178,13 +195,15 @@ jobs:
|
||||
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
|
||||
cnb-mirror:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
@@ -15,6 +15,7 @@
|
||||
"src/editor/core/cm/jsp/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"src/editor/core/cm/django/parser*.ts",
|
||||
"src/editor/core/cm/freemarker/parser*.ts",
|
||||
"plugins/themes.md",
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
|
||||
@@ -152,7 +152,10 @@
|
||||
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
|
||||
"excludeFiles": ["e2e/**"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
"no-await-in-loop": "error",
|
||||
"react/no-array-index-key": "error",
|
||||
"react/jsx-no-constructed-context-values": "error",
|
||||
"react/no-object-type-as-default-prop": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
Створено
+63
-50
@@ -252,9 +252,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "async-executor"
|
||||
version = "1.14.0"
|
||||
version = "1.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
|
||||
checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37"
|
||||
dependencies = [
|
||||
"async-task",
|
||||
"concurrent-queue",
|
||||
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4173,6 +4173,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1 0.10.7",
|
||||
"specta",
|
||||
"sqlx",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
@@ -4183,7 +4184,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4195,7 +4196,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4207,7 +4208,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4225,7 +4226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4239,7 +4240,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4250,7 +4251,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4261,7 +4262,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4283,7 +4284,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4296,7 +4297,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4326,7 +4327,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4365,7 +4366,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4378,7 +4379,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4392,7 +4393,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4412,7 +4413,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4423,7 +4424,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4435,7 +4436,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4447,7 +4448,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4466,7 +4467,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4549,7 +4550,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"http",
|
||||
@@ -4572,7 +4573,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4595,7 +4596,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4607,7 +4608,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4623,7 +4624,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4632,7 +4633,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4643,7 +4644,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4684,6 +4685,7 @@ dependencies = [
|
||||
"tree-sitter-make",
|
||||
"tree-sitter-md",
|
||||
"tree-sitter-nix",
|
||||
"tree-sitter-objc",
|
||||
"tree-sitter-ocaml",
|
||||
"tree-sitter-php",
|
||||
"tree-sitter-prisma-io",
|
||||
@@ -4702,7 +4704,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4732,7 +4734,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4751,7 +4753,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4776,7 +4778,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4798,7 +4800,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4812,7 +4814,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4832,7 +4834,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4858,7 +4860,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4874,7 +4876,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4900,7 +4902,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4921,7 +4923,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4934,7 +4936,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4959,7 +4961,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4972,7 +4974,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4987,7 +4989,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -5001,7 +5003,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -5014,7 +5016,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -5041,7 +5043,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5063,7 +5065,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5090,7 +5092,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5106,7 +5108,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5116,6 +5118,7 @@ dependencies = [
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -6754,7 +6757,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -10641,6 +10644,16 @@ dependencies = [
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-objc"
|
||||
version = "3.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ca8bb556423fc176f0535e79d525f783a6684d3c9da81bf9d905303c129e1d2"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-ocaml"
|
||||
version = "0.26.0"
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
## Community
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
|
||||
## Topluluk
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
@@ -69,7 +69,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
|
||||
## 社区
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
|
||||
@@ -18,6 +18,7 @@ ide-tools = { path = "../ide-tools" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
toml.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
|
||||
//!
|
||||
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
|
||||
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
|
||||
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), Codex
|
||||
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in
|
||||
//! `<home>/.codex/session_index.jsonl`).
|
||||
//! `<home>/.codex/session_index.jsonl`), and Copilot
|
||||
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
|
||||
|
||||
use super::native::claude::history;
|
||||
use serde::Serialize;
|
||||
@@ -17,7 +18,7 @@ use std::path::{Path, PathBuf};
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExternalSession {
|
||||
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
|
||||
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
|
||||
pub provider: String,
|
||||
/// The id resuming it names (`--resume`, `thread/resume`).
|
||||
pub session_id: String,
|
||||
@@ -26,6 +27,9 @@ pub struct ExternalSession {
|
||||
pub cwd: Option<String>,
|
||||
/// File modification time, ms since the epoch.
|
||||
pub updated_ms: f64,
|
||||
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
|
||||
/// apps write the same session, so forking a copy is the safe choice.
|
||||
pub in_use: bool,
|
||||
}
|
||||
|
||||
/// Modification time of `path` in ms, else 0.
|
||||
@@ -123,6 +127,7 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&path),
|
||||
in_use: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -193,6 +198,7 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
|
||||
session_id,
|
||||
cwd,
|
||||
updated_ms: mtime(path),
|
||||
in_use: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -246,6 +252,289 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
sessions
|
||||
}
|
||||
|
||||
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
|
||||
fn is_yaml_block_header(raw: &str) -> bool {
|
||||
let mut chars = raw.chars();
|
||||
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
|
||||
fn parse_yaml_inline_value(raw: &str) -> String {
|
||||
if raw.starts_with('"') {
|
||||
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
|
||||
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
|
||||
raw[1..raw.len() - 1].replace("''", "'")
|
||||
} else {
|
||||
raw.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
|
||||
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
|
||||
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
|
||||
let mut metadata = HashMap::new();
|
||||
while let Some(line) = lines.next() {
|
||||
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let Some((key, raw)) = line.split_once(':') else { continue };
|
||||
let key = key.trim();
|
||||
let raw = raw.trim();
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if is_yaml_block_header(raw) {
|
||||
let folded = raw.starts_with('>');
|
||||
let mut block = Vec::new();
|
||||
while let Some(next) = lines.peek() {
|
||||
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
|
||||
block.push(lines.next().unwrap_or_default());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
while block.last().is_some_and(|l| l.trim().is_empty()) {
|
||||
block.pop();
|
||||
}
|
||||
let indent = block
|
||||
.iter()
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
let sep = if folded { " " } else { "\n" };
|
||||
let joined = block
|
||||
.iter()
|
||||
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
|
||||
.collect::<Vec<_>>()
|
||||
.join(sep);
|
||||
if !joined.trim().is_empty() {
|
||||
metadata.insert(key.to_owned(), joined);
|
||||
}
|
||||
} else if !raw.is_empty() {
|
||||
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
|
||||
}
|
||||
}
|
||||
(!metadata.is_empty()).then_some(metadata)
|
||||
}
|
||||
|
||||
/// The first real prompt in a Copilot event log, used when an old or unnamed session has no title.
|
||||
fn copilot_prompt(path: &Path) -> Option<String> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
std::io::BufReader::new(file)
|
||||
.lines()
|
||||
.take(400)
|
||||
.filter_map(|line| line.ok())
|
||||
.filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
|
||||
.find_map(|event| {
|
||||
(event.get("type").and_then(serde_json::Value::as_str) == Some("user.message"))
|
||||
.then(|| event.pointer("/data/content").and_then(serde_json::Value::as_str).map(str::trim))
|
||||
.flatten()
|
||||
.filter(|text| !text.is_empty())
|
||||
.map(short)
|
||||
})
|
||||
}
|
||||
|
||||
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
|
||||
/// ordered oldest-first so a newer database wins when two editions share a session.
|
||||
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
|
||||
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
|
||||
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
|
||||
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
|
||||
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
|
||||
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
|
||||
&& !bases.contains(&dir)
|
||||
{
|
||||
bases.push(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut dbs = Vec::new();
|
||||
for base in bases {
|
||||
for app in ["Code", "Code - Insiders"] {
|
||||
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
|
||||
}
|
||||
}
|
||||
for server in [".vscode-server", ".vscode-server-insiders"] {
|
||||
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
|
||||
}
|
||||
dbs.retain(|p| p.is_file());
|
||||
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
|
||||
dbs
|
||||
}
|
||||
|
||||
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
|
||||
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
|
||||
}
|
||||
|
||||
fn pick_vscode_chat_title(
|
||||
scs_title: Option<&str>,
|
||||
scs_source: Option<&str>,
|
||||
metadata_json: Option<&str>,
|
||||
payload_json: Option<&str>,
|
||||
) -> Option<String> {
|
||||
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, scs_source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
for blob in [metadata_json, payload_json].into_iter().flatten() {
|
||||
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
|
||||
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
|
||||
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
|
||||
if let Some(t) = summary.filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The rows of one `agent-host.db` that map a backing Copilot session (`sdkSessionId`) to its
|
||||
/// title. Read through a read-only connection that sets no `journal_mode` or other write pragma,
|
||||
/// so VS Code's database is never changed. An unknown schema (a newer VS Code) reads nothing.
|
||||
async fn read_vscode_chat_rows(path: &Path) -> Vec<[Option<String>; 5]> {
|
||||
use sqlx::{Connection, Row};
|
||||
const FULL_QUERY: &str = "\
|
||||
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
|
||||
FROM chats_v2 c \
|
||||
LEFT JOIN session_chat_state scs \
|
||||
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
|
||||
LEFT JOIN sessions_v2 s \
|
||||
ON s.session_uri = c.owner_session_uri \
|
||||
WHERE c.tombstoned = 0 \
|
||||
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
|
||||
const FALLBACK_QUERY: &str = "SELECT provider_data, NULL, NULL, metadata, NULL FROM chats_v2 WHERE tombstoned = 0";
|
||||
|
||||
let options = sqlx::sqlite::SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.read_only(true)
|
||||
.create_if_missing(false)
|
||||
.busy_timeout(std::time::Duration::from_millis(200));
|
||||
let Ok(mut conn) = sqlx::SqliteConnection::connect_with(&options).await else { return Vec::new() };
|
||||
let rows = match sqlx::query(FULL_QUERY).fetch_all(&mut conn).await {
|
||||
Ok(rows) => rows,
|
||||
Err(_) => sqlx::query(FALLBACK_QUERY).fetch_all(&mut conn).await.unwrap_or_default(),
|
||||
};
|
||||
let _ = conn.close().await;
|
||||
rows.iter().map(|row| std::array::from_fn(|i| row.try_get::<Option<String>, _>(i).ok().flatten())).collect()
|
||||
}
|
||||
|
||||
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
|
||||
/// sessions (`sdkSessionId` → summary or user rename). VS Code keeps these in its own
|
||||
/// `agent-host.db` rather than in Copilot's `workspace.yaml`, so without them a renamed chat
|
||||
/// would be listed under its first prompt. Best-effort: any failure leaves the CLI titles.
|
||||
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
let Some(home) = home else { return HashMap::new() };
|
||||
let dbs = vscode_agent_host_dbs(home);
|
||||
if dbs.is_empty() {
|
||||
return HashMap::new();
|
||||
}
|
||||
// Callers are sync and may run on a runtime thread or none: a private runtime on its own
|
||||
// thread works from either without blocking a runtime worker.
|
||||
let rows: Vec<[Option<String>; 5]> = std::thread::scope(|scope| {
|
||||
scope
|
||||
.spawn(|| {
|
||||
let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
|
||||
return Vec::new();
|
||||
};
|
||||
rt.block_on(async {
|
||||
let mut all = Vec::new();
|
||||
for path in &dbs {
|
||||
all.extend(read_vscode_chat_rows(path).await);
|
||||
}
|
||||
all
|
||||
})
|
||||
})
|
||||
.join()
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let mut titles = HashMap::new();
|
||||
for [pdata, scs_title, scs_source, metadata, payload] in rows {
|
||||
let Some(pdata) = pdata else { continue };
|
||||
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
|
||||
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(title) =
|
||||
pick_vscode_chat_title(scs_title.as_deref(), scs_source.as_deref(), metadata.as_deref(), payload.as_deref())
|
||||
{
|
||||
titles.insert(sdk_id.to_owned(), title);
|
||||
}
|
||||
}
|
||||
titles
|
||||
}
|
||||
|
||||
/// Whether a live process holds the Copilot session in `dir`. Copilot writes `inuse.<pid>.lock`
|
||||
/// while a CLI or SDK host (such as VS Code) has the session open; a crash leaves a stale one,
|
||||
/// so only a lock whose process still runs counts.
|
||||
fn copilot_session_in_use(dir: &Path) -> bool {
|
||||
std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| {
|
||||
let name = entry.file_name();
|
||||
let Some(pid) = name
|
||||
.to_str()
|
||||
.and_then(|n| n.strip_prefix("inuse."))
|
||||
.and_then(|n| n.strip_suffix(".lock"))
|
||||
.and_then(|n| n.parse::<u32>().ok())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
ide_core::process::process_alive(pid)
|
||||
})
|
||||
}
|
||||
|
||||
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
|
||||
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
|
||||
/// Directories without an event log are unfinished sessions and are not listed.
|
||||
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
|
||||
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let dir = entry.path();
|
||||
let events = dir.join("events.jsonl");
|
||||
if !events.is_file() {
|
||||
return None;
|
||||
}
|
||||
let metadata = copilot_metadata(&dir.join("workspace.yaml"))?;
|
||||
let session_id = metadata.get("id").cloned().or_else(|| entry.file_name().to_str().map(str::to_owned))?;
|
||||
let cwd = metadata.get("cwd").cloned().or_else(|| metadata.get("git_root").cloned());
|
||||
if !in_project(cwd.as_deref(), root) {
|
||||
return None;
|
||||
}
|
||||
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
|
||||
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
|
||||
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
|
||||
let title = raw_name
|
||||
.map(short)
|
||||
.or_else(|| copilot_prompt(&events))
|
||||
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
|
||||
let session = ExternalSession {
|
||||
provider: "copilot".to_owned(),
|
||||
session_id,
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&events),
|
||||
in_use: copilot_session_in_use(&dir),
|
||||
};
|
||||
Some((session, cli_user_named))
|
||||
})
|
||||
.collect();
|
||||
if !pending.is_empty() {
|
||||
let vscode_titles = vscode_copilot_titles(home);
|
||||
for (session, cli_user_named) in &mut pending {
|
||||
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
|
||||
session.title = short(title);
|
||||
}
|
||||
}
|
||||
}
|
||||
pending.into_iter().map(|(s, _)| s).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -344,6 +633,111 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
|
||||
}
|
||||
|
||||
fn exec_sqlite(path: &Path, sql: &'static str) {
|
||||
use sqlx::Connection;
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
rt.block_on(async {
|
||||
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
|
||||
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
|
||||
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
|
||||
conn.close().await.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let copilot_home = tmp.path().join(".copilot");
|
||||
let session = copilot_home.join("session-state/copilot-1");
|
||||
write(
|
||||
&session.join("events.jsonl"),
|
||||
&[
|
||||
json!({"type": "session.start", "data": {}}),
|
||||
json!({"type": "user.message", "data": {"content": "fix the parser"}}),
|
||||
],
|
||||
);
|
||||
std::fs::write(
|
||||
session.join("workspace.yaml"),
|
||||
"id: copilot-1\ncwd: /work/app/api\nname: \"Fix parser\\nand tests\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let block_scalar = copilot_home.join("session-state/copilot-block");
|
||||
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
block_scalar.join("workspace.yaml"),
|
||||
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
|
||||
write(
|
||||
&vscode_renamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
|
||||
);
|
||||
std::fs::write(
|
||||
vscode_renamed.join("workspace.yaml"),
|
||||
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
|
||||
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
vscode_placeholder.join("workspace.yaml"),
|
||||
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let unnamed = copilot_home.join("session-state/copilot-2");
|
||||
write(
|
||||
&unnamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
|
||||
);
|
||||
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
|
||||
// A live holder marks the session in use; a lock left by a process that exited does not.
|
||||
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
|
||||
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
|
||||
|
||||
let empty = copilot_home.join("session-state/copilot-empty");
|
||||
std::fs::create_dir_all(&empty).unwrap();
|
||||
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
|
||||
|
||||
let other = copilot_home.join("session-state/copilot-other");
|
||||
write(
|
||||
&other.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
|
||||
);
|
||||
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
|
||||
|
||||
exec_sqlite(
|
||||
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
|
||||
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
|
||||
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
|
||||
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
|
||||
);
|
||||
|
||||
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
|
||||
assert_eq!(sessions.len(), 5);
|
||||
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
|
||||
let named = by_id.remove("copilot-1").unwrap();
|
||||
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
|
||||
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
|
||||
assert!(named.in_use);
|
||||
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
|
||||
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
|
||||
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
|
||||
let unnamed = by_id.remove("copilot-2").unwrap();
|
||||
assert_eq!(unnamed.title, "add a regression test");
|
||||
assert!(!unnamed.in_use);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1409,19 +1409,23 @@ impl AgentManager {
|
||||
out.extend(external::claude_sessions(&dir, &root));
|
||||
}
|
||||
let home = self.shared.paths.home_dir.clone().or_else(home_dir);
|
||||
if let Some(home) = home {
|
||||
if let Some(home) = home.as_deref() {
|
||||
out.extend(external::codex_sessions(&home.join(".codex"), &root));
|
||||
}
|
||||
if let Some(spec) = self.shared.spec("copilot")
|
||||
&& let Some(dir) = native::copilot::config_dir(&spec.env, home.as_deref())
|
||||
{
|
||||
out.extend(external::copilot_sessions(&dir, home.as_deref(), &root));
|
||||
}
|
||||
let known = self.imported_session_ids();
|
||||
out.retain(|s| !known.contains(&s.session_id));
|
||||
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
out.truncate(50);
|
||||
out
|
||||
}
|
||||
|
||||
/// Imports an external session as a task, loading it in the background to show its history (#312).
|
||||
pub fn import_session(&self, provider: &str, session_id: &str) -> IdeResult<AgentTask> {
|
||||
if !matches!(provider, "claude" | "codex") {
|
||||
if !matches!(provider, "claude" | "codex" | "copilot") {
|
||||
return Err(IdeError::invalid(format!("cannot import {provider} sessions")));
|
||||
}
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
@@ -1488,9 +1492,21 @@ impl AgentManager {
|
||||
pending_native_fork: None,
|
||||
};
|
||||
let handle = Task::restore(file, self.shared.clone());
|
||||
self.tasks.write().insert(task.id.clone(), handle.clone());
|
||||
let epoch = {
|
||||
let mut tasks = self.tasks.write();
|
||||
let epoch = self.shared.shutdown_epoch();
|
||||
tasks.insert(task.id.clone(), handle.clone());
|
||||
epoch
|
||||
};
|
||||
handle.emit_task();
|
||||
handle.persist();
|
||||
// Loading the session replays its history into the task, so it shows before a first message.
|
||||
self.shared.runtime.spawn(async move {
|
||||
match handle.ensure_session(epoch).await {
|
||||
Ok(_) => handle.release_when_idle(),
|
||||
Err(e) => tracing::info!("agent task {}: loading the imported session failed: {e}", handle.id),
|
||||
}
|
||||
});
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
@@ -1498,7 +1514,7 @@ impl AgentManager {
|
||||
/// recording as the agent's own fork, under an id the host chooses. The session must
|
||||
/// belong to this project and have been recorded in `cwd`.
|
||||
pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult<AgentTask> {
|
||||
if !matches!(provider, "claude" | "codex") {
|
||||
if !matches!(provider, "claude" | "codex" | "copilot") {
|
||||
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
|
||||
}
|
||||
if !canonical_uuid(session_id) {
|
||||
@@ -1526,7 +1542,7 @@ impl AgentManager {
|
||||
let config = self.shared.known_config(&spec.id);
|
||||
let now = now_ms();
|
||||
let id = uuid::Uuid::new_v4().simple().to_string();
|
||||
// The host names the fork's session id for claude; codex assigns its own.
|
||||
// The host names the fork's session id for claude; codex and Copilot assign their own.
|
||||
let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string());
|
||||
let task = AgentTask {
|
||||
project_root: Some(IpcPath(root)),
|
||||
@@ -2034,46 +2050,63 @@ impl AgentManager {
|
||||
return Err(IdeError::invalid("wait until the agent is done"));
|
||||
}
|
||||
let epoch = self.shared.shutdown_epoch();
|
||||
let live = source.ensure_session(epoch).await.map_err(IdeError::internal)?;
|
||||
// A Codex fork must be opened by its own task: the creating app-server owns its writer.
|
||||
// It can also fork a recorded thread whose writer is held by another process.
|
||||
let codex_source = {
|
||||
let s = source.state.lock();
|
||||
(s.task.provider == "codex").then(|| s.session_id.clone()).flatten()
|
||||
};
|
||||
let live = if codex_source.is_none() {
|
||||
Some(source.ensure_session(epoch).await.map_err(IdeError::internal)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
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) {
|
||||
let capabilities = live.as_ref().map(|l| l.capabilities).unwrap_or(source.state.lock().task.capabilities);
|
||||
if !capabilities.fork || (keep < total && !capabilities.rollback) {
|
||||
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
|
||||
}
|
||||
let (cwd, provider_id, mcp_overrides, project_root) = {
|
||||
let s = source.state.lock();
|
||||
let t = &s.task;
|
||||
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
|
||||
};
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
|
||||
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
|
||||
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
|
||||
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
|
||||
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
|
||||
let reply: Value = live
|
||||
.peer
|
||||
.request(
|
||||
"session/fork",
|
||||
{
|
||||
let mut params = session_params(
|
||||
&cwd_s,
|
||||
&mcp_servers,
|
||||
skills_delivery.as_ref(),
|
||||
memory_delivery.as_ref(),
|
||||
&roots,
|
||||
);
|
||||
params["sessionId"] = json!(live.session);
|
||||
params
|
||||
},
|
||||
None,
|
||||
let session = if let Some(live) = &live {
|
||||
let (cwd, provider_id, mcp_overrides, project_root) = {
|
||||
let s = source.state.lock();
|
||||
let t = &s.task;
|
||||
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
|
||||
};
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
|
||||
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
|
||||
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
|
||||
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
|
||||
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
|
||||
let reply: Value = live
|
||||
.peer
|
||||
.request(
|
||||
"session/fork",
|
||||
{
|
||||
let mut params = session_params(
|
||||
&cwd_s,
|
||||
&mcp_servers,
|
||||
skills_delivery.as_ref(),
|
||||
memory_delivery.as_ref(),
|
||||
&roots,
|
||||
);
|
||||
params["sessionId"] = json!(live.session);
|
||||
params
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(source.describe(e)))?;
|
||||
Some(
|
||||
reply
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
|
||||
.to_owned(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(source.describe(e)))?;
|
||||
let session = reply
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| IdeError::internal("the agent returned no session"))?
|
||||
.to_owned();
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let file = {
|
||||
let s = source.state.lock();
|
||||
let mut entries = s.history.conversation.main.entries.clone();
|
||||
@@ -2099,7 +2132,7 @@ impl AgentManager {
|
||||
};
|
||||
TaskFile {
|
||||
task,
|
||||
session_id: Some(session),
|
||||
session_id: session,
|
||||
entries,
|
||||
wanted: s.wanted.clone(),
|
||||
pending_model: None,
|
||||
@@ -2114,12 +2147,19 @@ impl AgentManager {
|
||||
pending_rollback: total - keep,
|
||||
title_renamed: s.title_renamed,
|
||||
ephemeral: s.ephemeral,
|
||||
pending_native_fork: None,
|
||||
pending_native_fork: codex_source.map(|source| ForkStart { source, target: None }),
|
||||
}
|
||||
};
|
||||
// Copying may have started the source's agent: it stops again once idle.
|
||||
source.release_when_idle();
|
||||
if live.is_some() {
|
||||
source.release_when_idle();
|
||||
}
|
||||
let task = Task::restore(file, self.shared.clone());
|
||||
if live.is_none() {
|
||||
// Establish the fork before returning so its snapshot cannot drift while the source continues.
|
||||
task.ensure_session(epoch).await.map_err(IdeError::internal)?;
|
||||
task.release_when_idle();
|
||||
}
|
||||
self.tasks.write().insert(task.id.clone(), task.clone());
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
@@ -2762,7 +2802,6 @@ impl AgentManager {
|
||||
}
|
||||
s.task.title = title;
|
||||
s.title_renamed = true;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
@@ -3126,7 +3165,6 @@ impl AgentManager {
|
||||
let changed = s.task.mcp_overrides != cleaned;
|
||||
if changed {
|
||||
s.task.mcp_overrides = cleaned;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
(changed, s.busy, !s.background_tasks.is_empty(), s.snapshot())
|
||||
};
|
||||
@@ -3158,7 +3196,6 @@ impl AgentManager {
|
||||
let changed = s.task.skill_overrides != cleaned;
|
||||
if changed {
|
||||
s.task.skill_overrides = cleaned;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
|
||||
};
|
||||
@@ -3194,7 +3231,6 @@ impl AgentManager {
|
||||
let changed = s.task.memory_overrides != next_boxed;
|
||||
if changed {
|
||||
s.task.memory_overrides = next_boxed;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
(changed, s.busy, !s.background_tasks.is_empty(), s.task.clone())
|
||||
};
|
||||
@@ -4937,6 +4973,19 @@ impl Task {
|
||||
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
return Err(SessionOpenError { message, allow_acp_fallback: false });
|
||||
}
|
||||
// A writer conflict is temporary: retrying must retain the original session ID.
|
||||
if spec.driver == provider::Driver::Codex
|
||||
&& matches!(&e, RpcError::Server { message, .. } if message.contains("already has an active writer"))
|
||||
{
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
"Couldn't reopen this conversation's {} session: {}",
|
||||
spec.name,
|
||||
self.describe(e)
|
||||
),
|
||||
allow_acp_fallback: false,
|
||||
});
|
||||
}
|
||||
if pending_model.is_some() {
|
||||
return Err(SessionOpenError {
|
||||
message: format!(
|
||||
|
||||
@@ -37,6 +37,15 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
|
||||
const EARLY_CANCEL: Duration = Duration::from_secs(2);
|
||||
const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
|
||||
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
|
||||
env.iter()
|
||||
.find(|(key, _)| key == "COPILOT_HOME")
|
||||
.map(|(_, value)| PathBuf::from(value))
|
||||
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
|
||||
.or_else(|| home.map(|home| home.join(".copilot")))
|
||||
}
|
||||
|
||||
/// Pre-session discovery result for `Shared::fetch_settings`.
|
||||
pub(crate) struct Discovered {
|
||||
pub commands: Vec<Value>,
|
||||
@@ -551,6 +560,7 @@ impl CopilotShim {
|
||||
"initialize" => self.initialize().await,
|
||||
"session/new" => self.new_session(¶ms).await,
|
||||
"session/load" => self.load_session(¶ms).await,
|
||||
"session/fork" => self.fork_session(¶ms).await,
|
||||
"session/set_config_option" => self.set_config(¶ms).await,
|
||||
"session/prompt" => self.prompt(¶ms, false).await,
|
||||
"_openidea/steer" => self.prompt(¶ms, true).await,
|
||||
@@ -569,7 +579,7 @@ impl CopilotShim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
|
||||
"sessionCapabilities": { "close": {}, "list": {} },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
},
|
||||
"agentInfo": {
|
||||
@@ -649,6 +659,25 @@ impl CopilotShim {
|
||||
|
||||
async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session_id = str_param(params, "sessionId")?.to_owned();
|
||||
let loaded = self.resume_session(params, &session_id).await?;
|
||||
let actual_id = loaded.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
|
||||
self.replay_history(&actual_id).await;
|
||||
Ok(loaded)
|
||||
}
|
||||
|
||||
async fn fork_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
|
||||
let source = str_param(params, "sessionId")?;
|
||||
let forked = self.call("sessions.fork", json!({ "sessionId": source })).await?;
|
||||
let target = forked
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|id| !id.is_empty())
|
||||
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Copilot fork returned no sessionId"))?
|
||||
.to_owned();
|
||||
self.resume_session(params, &target).await
|
||||
}
|
||||
|
||||
async fn resume_session(self: &Arc<Self>, params: &Value, session_id: &str) -> Result<Value, ResponseError> {
|
||||
let cwd = str_param(params, "cwd")?;
|
||||
let catalog = self.models().await?;
|
||||
let defaults = fetch_user_defaults(self.copilot(), &self.args).await;
|
||||
@@ -675,7 +704,8 @@ impl CopilotShim {
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": actual_id })).await {
|
||||
if let Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
|
||||
let _ = settings.set(&catalog, MODEL, model_id);
|
||||
}
|
||||
@@ -686,7 +716,6 @@ impl CopilotShim {
|
||||
let _ = settings.set(&catalog, CONTEXT_TIER, tier);
|
||||
}
|
||||
}
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
|
||||
let options = models::config_options(&catalog, &settings);
|
||||
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
|
||||
self.publish_commands(&actual_id, cwd);
|
||||
@@ -697,6 +726,28 @@ impl CopilotShim {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn replay_history(&self, session_id: &str) {
|
||||
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
|
||||
Ok(history) => history,
|
||||
Err(error) => {
|
||||
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let events = history.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
let updates = {
|
||||
let mut state = self.state.lock();
|
||||
let Some(entry) = state.sessions.get_mut(session_id) else { return };
|
||||
events
|
||||
.iter()
|
||||
.flat_map(|event| entry.translator.translate_history(session_id, event, None).updates)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for (target_session, update) in updates {
|
||||
self.send_update(&target_session, update);
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
|
||||
let shim = self.clone();
|
||||
let sid = session_id.to_owned();
|
||||
|
||||
@@ -115,6 +115,18 @@ fn sample_price_units() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_copilot_home_from_agent_env_or_user_home() {
|
||||
let home = std::path::Path::new("/home/test");
|
||||
assert_eq!(
|
||||
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
|
||||
Some(std::path::Path::new("/custom/copilot"))
|
||||
);
|
||||
if std::env::var_os("COPILOT_HOME").is_none() {
|
||||
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_an_enabled_auto_only_catalog() {
|
||||
let list = json!({
|
||||
@@ -434,6 +446,39 @@ impl Handler for FakeCopilotServer {
|
||||
"skills.discover" => Ok(json!({ "skills": [] })),
|
||||
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
|
||||
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
|
||||
"sessions.fork" => Ok(json!({ "sessionId": "cop-sess-fork" })),
|
||||
"session.getMessages" => Ok(json!({
|
||||
"events": [
|
||||
{
|
||||
"type": "user.message",
|
||||
"data": { "content": "Fix the parser" }
|
||||
},
|
||||
{
|
||||
"type": "assistant.message",
|
||||
"data": {
|
||||
"messageId": "history-message",
|
||||
"reasoningText": "Inspect the grammar first.",
|
||||
"content": "I fixed the parser."
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool.execution_start",
|
||||
"data": {
|
||||
"toolCallId": "history-tool",
|
||||
"toolName": "view",
|
||||
"arguments": { "path": "/tmp/parser.rs" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool.execution_complete",
|
||||
"data": {
|
||||
"toolCallId": "history-tool",
|
||||
"success": true,
|
||||
"result": { "content": "fn parse() {}" }
|
||||
}
|
||||
}
|
||||
]
|
||||
})),
|
||||
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
|
||||
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
|
||||
"session.mode.set" => Ok(json!({})),
|
||||
@@ -674,6 +719,81 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_loads_and_replays_copilot_history() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates.clone(), move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
|
||||
let loaded: Value = client
|
||||
.request("session/load", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(loaded["sessionId"], "cop-sess-1");
|
||||
|
||||
assert!(
|
||||
server
|
||||
.calls
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|(method, params)| { method == "session.getMessages" && params["sessionId"] == "cop-sess-1" })
|
||||
);
|
||||
let seen = updates.0.lock();
|
||||
assert!(
|
||||
seen.iter().any(|u| u["sessionUpdate"] == "user_message_chunk" && u["content"]["text"] == "Fix the parser")
|
||||
);
|
||||
assert!(
|
||||
seen.iter().any(
|
||||
|u| u["sessionUpdate"] == "agent_thought_chunk" && u["content"]["text"] == "Inspect the grammar first."
|
||||
)
|
||||
);
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "I fixed the parser.")
|
||||
);
|
||||
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call" && u["toolCallId"] == "history-tool"));
|
||||
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "history-tool"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forks_copilot_sessions_and_resumes_the_new_id() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let forked: Value = client
|
||||
.request("session/fork", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(forked["sessionId"], "cop-sess-fork");
|
||||
let calls = server.calls.lock();
|
||||
assert!(calls.iter().any(|(method, params)| method == "sessions.fork" && params["sessionId"] == "cop-sess-1"));
|
||||
assert!(calls.iter().any(|(method, params)| method == "session.resume" && params["sessionId"] == "cop-sess-fork"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
|
||||
let server =
|
||||
|
||||
@@ -370,6 +370,55 @@ impl EventTranslator {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Translates one persisted Copilot event returned by `session.getMessages`. The live
|
||||
/// event stream omits historical user messages and emits reasoning deltas, while the
|
||||
/// persisted form has complete user and assistant messages.
|
||||
pub fn translate_history(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
|
||||
let event_type = str_of(event, "type").unwrap_or_default();
|
||||
let data = event.get("data").unwrap_or(&Value::Null);
|
||||
if event_type == "user.message" {
|
||||
let Some(text) = str_of(data, "content").map(str::trim).filter(|text| !text.is_empty()) else {
|
||||
return Translated { updates: Vec::new(), terminal: None };
|
||||
};
|
||||
let target_session = str_of(event, "agentId")
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(|id| format!("{main_session}:sub:{id}"))
|
||||
.unwrap_or_else(|| main_session.to_owned());
|
||||
return Translated {
|
||||
updates: vec![(
|
||||
target_session,
|
||||
json!({
|
||||
"sessionUpdate": "user_message_chunk",
|
||||
"content": { "type": "text", "text": text },
|
||||
}),
|
||||
)],
|
||||
terminal: None,
|
||||
};
|
||||
}
|
||||
|
||||
let mut translated = self.translate(main_session, event, fallback_limit);
|
||||
if event_type == "assistant.message"
|
||||
&& !(data.get("parentToolCallId").and_then(Value::as_str).is_some() && str_of(event, "agentId").is_none())
|
||||
&& let Some(reasoning) = str_of(data, "reasoningText").map(str::trim).filter(|text| !text.is_empty())
|
||||
{
|
||||
let target_session = str_of(event, "agentId")
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(|id| format!("{main_session}:sub:{id}"))
|
||||
.unwrap_or_else(|| main_session.to_owned());
|
||||
translated.updates.insert(
|
||||
0,
|
||||
(
|
||||
target_session,
|
||||
json!({
|
||||
"sessionUpdate": "agent_thought_chunk",
|
||||
"content": { "type": "text", "text": reasoning },
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
translated
|
||||
}
|
||||
}
|
||||
|
||||
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
|
||||
|
||||
@@ -2191,6 +2191,41 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
|
||||
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
|
||||
}
|
||||
|
||||
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let task = {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
task
|
||||
};
|
||||
let agent = Arc::new(FakeAgent {
|
||||
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
for _ in 0..2 {
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
}
|
||||
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
|
||||
let copy = mgr.fork(&task.id, None).await.unwrap();
|
||||
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
|
||||
let copy_handle = mgr.task(©.id).unwrap();
|
||||
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
|
||||
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
|
||||
mgr.prompt(©.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, ©.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn text(t: &str) -> AgentPrompt {
|
||||
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
|
||||
}
|
||||
@@ -3241,6 +3276,58 @@ fn plant_codex_session(root: &Path, session_id: &str) {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Plants a recorded Copilot session below the test home.
|
||||
fn plant_copilot_session(root: &Path, session_id: &str) {
|
||||
let dir = root.join(".copilot").join("session-state").join(session_id);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("workspace.yaml"),
|
||||
format!("id: {session_id}\ncwd: {}\nname: Fix the Copilot parser\n", root.to_string_lossy()),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("events.jsonl"),
|
||||
format!(
|
||||
"{}\n",
|
||||
json!({
|
||||
"type": "user.message",
|
||||
"data": {"content": "fix the Copilot parser"}
|
||||
})
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn imports_copilot_sessions_and_loads_their_history() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let sessions = mgr.external_sessions();
|
||||
assert!(sessions.iter().any(|session| session.provider == "copilot" && session.session_id == NATIVE_SOURCE));
|
||||
let task = mgr.import_session("copilot", NATIVE_SOURCE).unwrap();
|
||||
assert_eq!(task.provider, "copilot");
|
||||
|
||||
for _ in 0..200 {
|
||||
if agent.calls.lock().iter().any(|call| call == "session/load")
|
||||
&& mgr.entries(&task.id, None).unwrap().len() >= 2
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert!(agent.calls.lock().iter().any(|call| call == "session/load"));
|
||||
assert!(
|
||||
mgr.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|entry| matches!(entry, AgentEntry::User { text, .. } if text == "earlier question"))
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_codex_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3261,6 +3348,28 @@ async fn fork_session_uses_the_id_codex_assigns() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_copilot_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let task = mgr.fork_session("copilot", NATIVE_SOURCE, tmp.path()).unwrap();
|
||||
for _ in 0..200 {
|
||||
if !agent.forks.lock().is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let forks = agent.forks.lock().clone();
|
||||
assert_eq!(forks.len(), 1);
|
||||
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
|
||||
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "copilot names its own fork");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_invalid_input_before_starting() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -6928,3 +7037,36 @@ async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_e
|
||||
mgr2.shutdown();
|
||||
mgr3.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn metadata_edits_do_not_bump_updated_ms() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let fixed_ms = 1_234.0;
|
||||
handle.state.lock().task.updated_ms = fixed_ms;
|
||||
|
||||
mgr.rename(&task.id, "Custom Title").unwrap();
|
||||
assert_eq!(handle.state.lock().task.updated_ms, fixed_ms);
|
||||
|
||||
let after_mcp = mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false)])).unwrap();
|
||||
assert_eq!(after_mcp.updated_ms, fixed_ms);
|
||||
|
||||
let after_skill =
|
||||
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
|
||||
assert_eq!(after_skill.updated_ms, fixed_ms);
|
||||
|
||||
let after_memory = mgr
|
||||
.set_memory_overrides(
|
||||
&task.id,
|
||||
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(after_memory.updated_ms, fixed_ms);
|
||||
}
|
||||
@@ -85,13 +85,26 @@ gradle.projectsEvaluated {{
|
||||
|
||||
pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &str) -> IdeResult<()> {
|
||||
let output = PathBuf::from(fs::read_to_string(cache.join("resource-output.txt"))?.trim());
|
||||
if !output.is_absolute() || !output.is_dir() {
|
||||
return Err(IdeError::invalid("The resource build did not report an output directory"));
|
||||
let invalid_output = "The resource build did not report an output directory";
|
||||
if !output.is_absolute() {
|
||||
return Err(IdeError::invalid(invalid_output));
|
||||
}
|
||||
let output = dunce::canonicalize(output)?;
|
||||
let output = match fs::metadata(&output) {
|
||||
Ok(metadata) if metadata.is_dir() => Some(dunce::canonicalize(output)?),
|
||||
// Gradle's processResources can succeed with NO-SOURCE and never create its destination.
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
|
||||
_ => return Err(IdeError::invalid(invalid_output)),
|
||||
};
|
||||
let paths: Vec<_> = class_paths.iter().filter_map(|p| dunce::canonicalize(root.join(p)).ok()).collect();
|
||||
// A separate resource directory is already on the runtime classpath (e.g. build/resources/main).
|
||||
if paths.contains(&output) {
|
||||
if output.as_ref().is_some_and(|dir| paths.contains(dir)) {
|
||||
return Ok(());
|
||||
}
|
||||
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||
.unwrap_or_default();
|
||||
if output.is_none() && previous.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
// jdtls uses bin/main for Gradle, rather than Gradle's build/resources/main.
|
||||
@@ -99,12 +112,10 @@ pub fn publish(root: &Path, cache: &Path, class_paths: &[String], main_class: &s
|
||||
let destination = paths.iter().find(|p| p.join(&class_file).is_file()).ok_or_else(|| {
|
||||
IdeError::invalid("Cannot find the running main class output directory; restart the application")
|
||||
})?;
|
||||
let previous: Vec<String> = fs::read(cache.join("published-resources.json"))
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||
.unwrap_or_default();
|
||||
let mut current = Vec::new();
|
||||
copy_resources(&output, &output, destination, &mut current)?;
|
||||
if let Some(output) = output {
|
||||
copy_resources(&output, &output, destination, &mut current)?;
|
||||
}
|
||||
for rel in previous.iter().filter(|p| !current.contains(p)) {
|
||||
let path = destination.join(rel);
|
||||
if path.is_file() {
|
||||
@@ -220,6 +231,39 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_resource_output_publishes_an_empty_set() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let output = root.join("build/resources/main");
|
||||
let cache = root.join("cache");
|
||||
let runtime = root.join("bin/main");
|
||||
let class_paths = [runtime.to_string_lossy().into_owned()];
|
||||
let resource = "application.properties";
|
||||
fs::create_dir(&cache).unwrap();
|
||||
fs::create_dir_all(runtime.join("example")).unwrap();
|
||||
fs::write(cache.join("resource-output.txt"), output.to_string_lossy().as_bytes()).unwrap();
|
||||
let class = runtime.join("example/Application.class");
|
||||
fs::write(&class, "running").unwrap();
|
||||
|
||||
publish(root, &cache, &class_paths, "example.Application").unwrap();
|
||||
assert!(!output.exists());
|
||||
|
||||
fs::create_dir_all(&output).unwrap();
|
||||
fs::write(output.join(resource), "server.port=8081").unwrap();
|
||||
publish(root, &cache, &class_paths, "example.Application").unwrap();
|
||||
assert!(runtime.join(resource).is_file());
|
||||
|
||||
fs::remove_file(output.join(resource)).unwrap();
|
||||
fs::remove_dir(&output).unwrap();
|
||||
publish(root, &cache, &class_paths, "example.Application").unwrap();
|
||||
assert!(!runtime.join(resource).exists());
|
||||
assert_eq!(fs::read_to_string(class).unwrap(), "running");
|
||||
|
||||
fs::write(output, "not a directory").unwrap();
|
||||
assert!(publish(root, &cache, &class_paths, "example.Application").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_separate_runtime_resource_directories_in_place_and_rejects_jar_only_runs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -17,8 +17,8 @@ pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
has_gradle_file_target, javac_step, maven_system_classpath, module_classpath, module_classpath_without_build,
|
||||
module_classpaths, single_file_classpath, single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
@@ -986,7 +986,7 @@ fn maven_launch_projects<'a>(
|
||||
}
|
||||
projects.push(p);
|
||||
for dep in &p.dependencies {
|
||||
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(upstream) = reactor.iter().find(|u| {
|
||||
|
||||
@@ -180,6 +180,30 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
|
||||
exe.to_owned()
|
||||
}
|
||||
|
||||
/// Existing system-scope dependencies of this module. Maven resolves these from
|
||||
/// their local files and does not pass them transitively to reactor dependents.
|
||||
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
|
||||
let Some(maven) = &model.maven else { return Vec::new() };
|
||||
let module = root.join(module);
|
||||
maven
|
||||
.projects
|
||||
.iter()
|
||||
.find(|p| root.join(&p.dir) == module)
|
||||
.into_iter()
|
||||
.flat_map(|p| &p.system_paths)
|
||||
.filter(|p| p.is_file())
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
|
||||
let system = maven_system_classpath(root, model, module);
|
||||
if system.is_empty() {
|
||||
return classpath;
|
||||
}
|
||||
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
/// Dependency classpath of the module: existing reactor class directories plus
|
||||
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
|
||||
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
|
||||
@@ -233,7 +257,7 @@ pub fn module_classpath_without_build(
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
}
|
||||
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
|
||||
}
|
||||
@@ -270,7 +294,7 @@ pub fn module_classpaths(
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
return Ok(cached.classpath);
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -298,7 +322,7 @@ pub fn module_classpaths(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(classpaths.into_iter().next().unwrap())
|
||||
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
|
||||
}
|
||||
|
||||
/// A module whose classpath the Maven probe resolves, with its cache key and file.
|
||||
@@ -346,7 +370,8 @@ fn classpath(
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
|
||||
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
|
||||
Ok(with_system_classpath(root, model, &target.module, classpath))
|
||||
}
|
||||
|
||||
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
|
||||
@@ -912,6 +937,64 @@ mod tests {
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn system_jars_augment_maven_javac_and_launch_classpaths() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"pom.xml",
|
||||
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
|
||||
<packaging>pom</packaging><modules><module>app</module></modules>
|
||||
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>app</artifactId>
|
||||
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
|
||||
<dependencies>
|
||||
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
|
||||
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
|
||||
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
|
||||
</dependencies></project>"#,
|
||||
);
|
||||
let jars = "app/src/main/resources/lib";
|
||||
write(&root, &format!("{jars}/offline.jar"), "");
|
||||
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
|
||||
// The scope-filtered Maven classpath can contain no dependencies.
|
||||
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
|
||||
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let cache = root.join("cache");
|
||||
let model = crate::load(&root, &cache, None);
|
||||
let module = root.join("app");
|
||||
let file = module.join("src/main/java/demo/Main.java");
|
||||
let jar = root.join(jars).join("offline.jar");
|
||||
let plan = compile_file_plan(&root, &model, &file).unwrap();
|
||||
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
|
||||
let cancel = CancellationToken::new();
|
||||
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
|
||||
assert!(maven_system_classpath(&root, &model, &root).is_empty());
|
||||
|
||||
// Adding a previously absent jar or deleting an old one updates a no-build launch.
|
||||
fs::remove_file(jar).unwrap();
|
||||
write(&root, &format!("{jars}/late.jar"), "");
|
||||
fs::remove_file(root.join("mvnw")).unwrap();
|
||||
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
|
||||
}
|
||||
|
||||
/// Modules launched together resolve their classpaths in one Maven probe and leave
|
||||
/// the others' cached; a probe another module breaks still resolves the first one.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
//! same way into the test output, which also sees the production classes.
|
||||
use super::*;
|
||||
use ide_core::settings::{
|
||||
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings,
|
||||
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, jar_files,
|
||||
split_jar_glob,
|
||||
};
|
||||
use std::fs;
|
||||
|
||||
@@ -104,13 +105,17 @@ fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Ve
|
||||
module_deps.iter().find(|d| d.kind == "library" && d.target == lib.name).map_or(lib.scope, |d| d.scope);
|
||||
if wanted(scope) {
|
||||
for class in &lib.classes {
|
||||
add(class_entry(root, class));
|
||||
for entry in class_entries(root, class) {
|
||||
add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for dep in module_deps.iter().filter(|d| d.kind == "library" && wanted(d.scope)) {
|
||||
if !ps.libraries.iter().any(|l| l.name == dep.target) && !dep.target.trim().is_empty() {
|
||||
add(class_entry(root, &dep.target));
|
||||
for entry in class_entries(root, &dep.target) {
|
||||
add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
|
||||
@@ -133,29 +138,50 @@ fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf {
|
||||
root.join(dir)
|
||||
}
|
||||
|
||||
/// The class archives and folders of a library path (`lib/*.jar` lists the folder's jars).
|
||||
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
|
||||
let entry = class_entry(root, value);
|
||||
match entry.strip_suffix('*') {
|
||||
Some(dir) => {
|
||||
let mut jars: Vec<PathBuf> = fs::read_dir(dir)
|
||||
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jar")).collect())
|
||||
.unwrap_or_default();
|
||||
jars.sort();
|
||||
jars
|
||||
/// The folders under `dir` (itself included) that hold `.jar` files, in walk order.
|
||||
fn jar_dirs(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = Vec::new();
|
||||
for jar in jar_files(dir, true) {
|
||||
if let Some(parent) = jar.parent().filter(|p| !dirs.iter().any(|d| d == p)) {
|
||||
dirs.push(parent.to_path_buf());
|
||||
}
|
||||
None => vec![PathBuf::from(entry)],
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
/// A classpath entry for a library path: a folder of jars (`lib/*`) stays a wildcard javac expands.
|
||||
fn class_entry(root: &Path, value: &str) -> String {
|
||||
let path = root.join(value.trim());
|
||||
let text = path.to_string_lossy().into_owned();
|
||||
if text.ends_with("/*.jar") || text.ends_with("\\*.jar") {
|
||||
return text[..text.len() - 4].to_owned();
|
||||
/// The class archives and folders of a library path (`lib/*.jar`, `lib/**/*.jar`, or a folder
|
||||
/// containing JARs expands to those JARs; a folder without JARs stays a class folder).
|
||||
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
|
||||
if let Some((base, recursive)) = split_jar_glob(value) {
|
||||
return jar_files(&root.join(base), recursive);
|
||||
}
|
||||
text
|
||||
let path = root.join(value.trim());
|
||||
if path.is_dir() {
|
||||
let jars = jar_files(&path, true);
|
||||
if !jars.is_empty() {
|
||||
return jars;
|
||||
}
|
||||
}
|
||||
vec![path]
|
||||
}
|
||||
|
||||
/// Classpath entries for a library path: `lib/*.jar` stays `lib/*` for javac to expand; a
|
||||
/// directory containing JARs expands to `<dir>/*` per folder holding JARs.
|
||||
fn class_entries(root: &Path, value: &str) -> Vec<String> {
|
||||
let wildcard = |dir: &Path| format!("{}{}*", dir.to_string_lossy(), std::path::MAIN_SEPARATOR);
|
||||
if let Some((base, recursive)) = split_jar_glob(value) {
|
||||
let dir = root.join(base);
|
||||
let dirs = if recursive { jar_dirs(&dir) } else { Vec::new() };
|
||||
return if dirs.is_empty() { vec![wildcard(&dir)] } else { dirs.iter().map(|d| wildcard(d)).collect() };
|
||||
}
|
||||
let path = root.join(value.trim());
|
||||
if path.is_dir() {
|
||||
let dirs = jar_dirs(&path);
|
||||
if !dirs.is_empty() {
|
||||
return dirs.iter().map(|d| wildcard(d)).collect();
|
||||
}
|
||||
}
|
||||
vec![path.to_string_lossy().into_owned()]
|
||||
}
|
||||
|
||||
fn classpath(entries: &[String]) -> String {
|
||||
@@ -440,7 +466,10 @@ pub fn structure_web_artifacts(ps: &ProjectStructureSettings) -> Vec<&ArtifactCo
|
||||
ps.artifacts.iter().filter(|a| matches!(a.kind, ArtifactKind::War | ArtifactKind::WarExploded)).collect()
|
||||
}
|
||||
|
||||
/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first.
|
||||
/// A build of `artifact` for Tomcat's deployment, compiling production classes first.
|
||||
/// When `war` is `Some`, packs a WAR archive at that path; when `None`, writes to the
|
||||
/// artifact's own output (`artifact_file`: a `.war` archive for `War`, or the exploded
|
||||
/// directory for `WarExploded`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn structure_war_plan(
|
||||
root: &Path,
|
||||
@@ -449,7 +478,7 @@ pub fn structure_war_plan(
|
||||
jdk: Option<&StructureJdk>,
|
||||
language_level: &str,
|
||||
artifact: &ArtifactConfig,
|
||||
war: &Path,
|
||||
war: Option<&Path>,
|
||||
cache: &Path,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)?
|
||||
@@ -459,7 +488,7 @@ pub fn structure_war_plan(
|
||||
plan.steps.retain(|s| !s.args.iter().any(|a| a.ends_with("test.args")));
|
||||
plan.steps
|
||||
.retain(|s| !matches!(&s.action, Some((Action::CopyResources { to, .. }, _)) if !to.starts_with(&main_out)));
|
||||
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache));
|
||||
plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, war, cache));
|
||||
plan.title = artifact.name.clone();
|
||||
Ok(plan)
|
||||
}
|
||||
@@ -1144,4 +1173,53 @@ mod tests {
|
||||
bad_result.messages
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_jar_directory_libraries_for_javac_and_artifacts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
let cache = tmp.path().join("cache");
|
||||
write(&root.join("src/A.java"), "class A {}");
|
||||
write(&root.join("WebRoot/WEB-INF/lib/gson.jar"), "jar1");
|
||||
write(&root.join("WebRoot/WEB-INF/lib/sub/extra.jar"), "jar2");
|
||||
fs::create_dir_all(root.join("plain-classes")).unwrap();
|
||||
write(&root.join("plain-classes/Helper.class"), "");
|
||||
|
||||
let ps = ProjectStructureSettings {
|
||||
libraries: vec![
|
||||
ProjectLibrary {
|
||||
name: "web-libs".into(),
|
||||
classes: vec!["WebRoot/WEB-INF/lib".into()],
|
||||
..Default::default()
|
||||
},
|
||||
ProjectLibrary { name: "classes".into(), classes: vec!["plain-classes".into()], ..Default::default() },
|
||||
],
|
||||
artifacts: vec![ArtifactConfig {
|
||||
name: "app:war exploded".into(),
|
||||
kind: ArtifactKind::WarExploded,
|
||||
module: ".".into(),
|
||||
output_directory: "out/artifacts/app_war_exploded".into(),
|
||||
main_class: String::new(),
|
||||
include_libraries: vec!["web-libs".into()],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
|
||||
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Artifacts, &cache).unwrap().unwrap();
|
||||
let javac = &plan.steps[0];
|
||||
let cp = &javac.args[javac.args.iter().position(|a| a == "-cp").unwrap() + 1];
|
||||
let sep = std::path::MAIN_SEPARATOR;
|
||||
assert!(cp.contains(&format!("lib{sep}*")), "expected JAR dir wildcard in cp: {cp}");
|
||||
assert!(cp.contains(&format!("sub{sep}*")), "expected nested JAR dir wildcard in cp: {cp}");
|
||||
assert!(cp.contains("plain-classes") && !cp.contains(&format!("plain-classes{sep}*")), "cp={cp}");
|
||||
|
||||
let layout = plan.steps.iter().find_map(|s| match &s.action {
|
||||
Some((Action::Layout { entries, .. }, _)) => Some(entries),
|
||||
_ => None,
|
||||
});
|
||||
let entries = layout.expect("layout step");
|
||||
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/gson.jar")), "{entries:?}");
|
||||
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/extra.jar")), "{entries:?}");
|
||||
assert!(!entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/lib")), "{entries:?}");
|
||||
}
|
||||
}
|
||||
@@ -234,9 +234,7 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
@@ -283,11 +281,28 @@ pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
if i == count {
|
||||
return None;
|
||||
}
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let pool = Pool(entries);
|
||||
Some(Pool(entries))
|
||||
}
|
||||
|
||||
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
|
||||
pub fn class_file_name(data: &[u8]) -> Option<String> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
r.u2()?; // access_flags
|
||||
Some(pool.class(r.u2()?)?.to_owned())
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
let mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
|
||||
@@ -22,7 +22,7 @@ mod incremental;
|
||||
mod javac;
|
||||
mod model;
|
||||
|
||||
pub use classfile::ClassFile;
|
||||
pub use classfile::{ClassFile, class_file_name};
|
||||
pub use javac::{JavacPool, Reply, ServerKey};
|
||||
|
||||
use incremental::{ClassRecord, SetStamp, SetState};
|
||||
|
||||
@@ -69,6 +69,9 @@ pub struct MavenProject {
|
||||
pub aggregated: bool,
|
||||
pub plugins: Vec<MavenPlugin>,
|
||||
pub dependencies: Vec<MavenDependency>,
|
||||
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
|
||||
#[serde(skip)]
|
||||
pub system_paths: Vec<PathBuf>,
|
||||
/// Profile ids declared in this POM.
|
||||
pub profiles: Vec<String>,
|
||||
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
|
||||
@@ -176,6 +179,7 @@ struct RawDep {
|
||||
kind: Option<String>,
|
||||
classifier: Option<String>,
|
||||
scope: Option<String>,
|
||||
system_path: Option<String>,
|
||||
optional: bool,
|
||||
}
|
||||
|
||||
@@ -248,6 +252,7 @@ fn read_dep(e: &Element) -> Option<RawDep> {
|
||||
kind: e.text_of("type"),
|
||||
classifier: e.text_of("classifier"),
|
||||
scope: e.text_of("scope"),
|
||||
system_path: e.text_of("systemPath"),
|
||||
optional: e.text_of("optional").is_some_and(|o| o == "true"),
|
||||
})
|
||||
}
|
||||
@@ -1519,7 +1524,13 @@ pub fn load_with_linked_jdk(
|
||||
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
|
||||
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
|
||||
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
|
||||
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
|
||||
let scope = |d: &RawDep| {
|
||||
d.scope
|
||||
.as_deref()
|
||||
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
|
||||
.map(i)
|
||||
.unwrap_or_else(|| "compile".into())
|
||||
};
|
||||
let dependencies = ctx
|
||||
.deps
|
||||
.iter()
|
||||
@@ -1529,11 +1540,24 @@ pub fn load_with_linked_jdk(
|
||||
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
|
||||
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
|
||||
classifier: d.classifier.clone(),
|
||||
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
|
||||
scope: scope(d),
|
||||
optional: d.optional,
|
||||
..MavenDependency::default()
|
||||
})
|
||||
.collect();
|
||||
let system_paths = ctx
|
||||
.deps
|
||||
.iter()
|
||||
.filter(|d| scope(d) == "system")
|
||||
.filter_map(|d| {
|
||||
let path = d
|
||||
.system_path
|
||||
.as_deref()
|
||||
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
|
||||
let path = i(path);
|
||||
(!path.contains("${") && Path::new(&path).is_absolute()).then(|| PathBuf::from(path))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
|
||||
for a in lifecycle_plugins(&packaging) {
|
||||
@@ -1592,6 +1616,7 @@ pub fn load_with_linked_jdk(
|
||||
aggregated,
|
||||
plugins,
|
||||
dependencies,
|
||||
system_paths,
|
||||
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
|
||||
java_version: jv,
|
||||
command: wrapper(&canonical_root, &dir_canon),
|
||||
|
||||
@@ -314,6 +314,30 @@ pub struct SmartKeysSettings {
|
||||
pub insert_doc_stub: bool,
|
||||
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
|
||||
pub backspace_unindent: String,
|
||||
/// The styles Cycle Identifier Case goes through.
|
||||
pub cycle_case: CycleCaseSettings,
|
||||
}
|
||||
|
||||
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CycleCaseSettings {
|
||||
/// `snake_case`
|
||||
pub snake: bool,
|
||||
/// `SCREAMING_SNAKE_CASE`
|
||||
pub screaming: bool,
|
||||
/// `kebab-case`
|
||||
pub kebab: bool,
|
||||
/// `camelCase`
|
||||
pub camel: bool,
|
||||
/// `PascalCase`
|
||||
pub pascal: bool,
|
||||
}
|
||||
|
||||
impl Default for CycleCaseSettings {
|
||||
fn default() -> Self {
|
||||
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SmartKeysSettings {
|
||||
@@ -335,6 +359,7 @@ impl Default for SmartKeysSettings {
|
||||
smart_indent: true,
|
||||
insert_doc_stub: true,
|
||||
backspace_unindent: "autoindent".into(),
|
||||
cycle_case: CycleCaseSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,10 @@ pub enum McpUiRequest {
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
/// The project is served without a window: the request shows in another project's window,
|
||||
/// which names it and keeps the keyboard focus where it is.
|
||||
#[serde(default)]
|
||||
background: bool,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
|
||||
@@ -1,5 +1,35 @@
|
||||
//! Returning freed heap pages to the OS.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Like [`release_free_pages`], on a background thread once 2 s pass without another call:
|
||||
/// closing a project or a batch of tabs frees memory in bursts, released once.
|
||||
pub fn release_free_pages_soon() {
|
||||
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
debounce(&DUE, Duration::from_secs(2), release_free_pages);
|
||||
}
|
||||
|
||||
/// Runs `run` on a background thread once `delay` passes after the last call.
|
||||
fn debounce(due: &'static Mutex<Option<Instant>>, delay: Duration, run: fn()) {
|
||||
let idle = due.lock().unwrap().replace(Instant::now() + delay).is_none();
|
||||
if idle {
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
let mut slot = due.lock().unwrap();
|
||||
let left = slot.map_or(Duration::ZERO, |at| at.saturating_duration_since(Instant::now()));
|
||||
if left.is_zero() {
|
||||
*slot = None;
|
||||
drop(slot);
|
||||
return run();
|
||||
}
|
||||
drop(slot);
|
||||
std::thread::sleep(left);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
|
||||
/// short-lived allocations (a full index scan); until then they still count towards the
|
||||
/// process's memory footprint.
|
||||
@@ -18,3 +48,45 @@ pub fn release_free_pages() {
|
||||
libc::malloc_trim(0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
|
||||
|
||||
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
static RUNS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
fn count() {
|
||||
RUNS.fetch_add(1, SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_calls_runs_once_after_the_delay() {
|
||||
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
|
||||
let delay = Duration::from_millis(500);
|
||||
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
|
||||
for _ in 0..5 {
|
||||
debounce(&DUE, delay, count);
|
||||
let now = Instant::now();
|
||||
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
|
||||
last = Some(now);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
if last.unwrap().elapsed() < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
// A second run would come within another delay.
|
||||
std::thread::sleep(delay);
|
||||
if widest_gap < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 1);
|
||||
} else {
|
||||
assert!(RUNS.load(SeqCst) >= 1);
|
||||
}
|
||||
release_free_pages_soon();
|
||||
}
|
||||
}
|
||||
@@ -622,6 +622,30 @@ pub fn host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
apply_changes(std::env::vars_os().collect(), &child_env_changes(Some(dir))).into_iter()
|
||||
}
|
||||
|
||||
/// Whether `(key, value)` can go into a Windows environment block (`KEY=VALUE\0`
|
||||
/// entries, then a final `\0`). `CreateProcessW` / `NtCreateUserProcess` returns
|
||||
/// `ERROR_INVALID_PARAMETER` (os error 87) when an entry has an empty name or an
|
||||
/// interior NUL. That happens when a `REG_MULTI_SZ` user environment value is
|
||||
/// loaded into the process or re-read from the registry (#6806): the extra NUL
|
||||
/// is treated as an entry separator and leaves a fragment with no `=`.
|
||||
pub fn is_spawnable_env_pair(key: &OsStr, value: &OsStr) -> bool {
|
||||
!key.is_empty() && !contains_ascii(key, 0) && !contains_ascii(key, b'=') && !contains_ascii(value, 0)
|
||||
}
|
||||
|
||||
fn contains_ascii(s: &OsStr, byte: u8) -> bool {
|
||||
s.as_encoded_bytes().contains(&byte)
|
||||
}
|
||||
|
||||
/// [`host_vars`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars() -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars().filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`host_vars_in`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars_in(dir).filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`std::env::var_os`] as a child should see it (see [`host_env`]), the login shell's value
|
||||
/// included when this process lacks the variable.
|
||||
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
@@ -1176,6 +1200,29 @@ mod tests {
|
||||
set_env_overlay(Vec::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_inside_a_project_gets_its_xcode() {
|
||||
let root = std::path::Path::new("/openidea-test-process/xcode");
|
||||
let xcode = "/Applications/Xcode-beta.app/Contents/Developer";
|
||||
crate::project_env::set_developer_dir(root, Some(xcode.into()));
|
||||
let developer_dir = |cmd: &Command| {
|
||||
cmd.get_envs().find(|(n, _)| *n == "DEVELOPER_DIR").and_then(|(_, v)| v.map(OsStr::to_owned))
|
||||
};
|
||||
// xcodebuild, xcrun, a language server: a `Command` started in the project.
|
||||
let mut tool = Command::new("xcodebuild");
|
||||
prepare(tool.current_dir(root.join("App")));
|
||||
assert_eq!(developer_dir(&tool), Some(xcode.into()));
|
||||
// A terminal: a PTY applies the fixes itself.
|
||||
assert!(host_env_fixes_in(root).contains(&("DEVELOPER_DIR".into(), Some(xcode.into()))));
|
||||
let mut elsewhere = Command::new("xcodebuild");
|
||||
prepare(elsewhere.current_dir("/openidea-test-process/other"));
|
||||
assert_eq!(developer_dir(&elsewhere), None);
|
||||
crate::project_env::set_developer_dir(root, None);
|
||||
let mut tool = Command::new("xcodebuild");
|
||||
prepare(tool.current_dir(root));
|
||||
assert_eq!(developer_dir(&tool), None, "empty: the system default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_inside_a_project_gets_its_environment() {
|
||||
let root = std::path::Path::new("/openidea-test-process/project");
|
||||
@@ -1217,6 +1264,35 @@ mod tests {
|
||||
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
|
||||
}
|
||||
|
||||
fn os_from_bytes(bytes: &[u8]) -> OsString {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
OsString::from_vec(bytes.to_vec())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
OsString::from_wide(&bytes.iter().copied().map(u16::from).collect::<Vec<_>>())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawnable_env_pairs_reject_empty_keys_equals_and_interior_nuls() {
|
||||
let ok_key = OsString::from("PATH");
|
||||
let ok_val = OsString::from("/bin");
|
||||
assert!(is_spawnable_env_pair(&ok_key, &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new(""), &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new("FOO=BAR"), &ok_val));
|
||||
// A REG_MULTI_SZ value's interior NUL would split the environment block,
|
||||
// leaving a fragment with no `=` (#6806). An empty name is also rejected.
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b""), &os_from_bytes(b"132786")));
|
||||
assert!(!is_spawnable_env_pair(&ok_key, &os_from_bytes(b"1788051509\x00132786")));
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b"132786\x00"), &ok_val));
|
||||
assert!(spawnable_host_vars().all(|(k, v)| is_spawnable_env_pair(&k, &v)));
|
||||
assert!(spawnable_host_vars().any(|(k, _)| k == "PATH" || k == "Path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_apply_in_order() {
|
||||
let vars = apply_changes(
|
||||
|
||||
@@ -16,13 +16,21 @@ struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
developer_dir: 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 }
|
||||
Self {
|
||||
root,
|
||||
direnv: Vec::new(),
|
||||
github_token: None,
|
||||
developer_dir: None,
|
||||
changes: Changes::default(),
|
||||
loading: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
@@ -33,11 +41,16 @@ impl Entry {
|
||||
// `.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());
|
||||
// The project's chosen Xcode overrides a `DEVELOPER_DIR` from `.envrc`: it is set for this project only.
|
||||
if let Some(dir) = &self.developer_dir {
|
||||
combined.retain(|(k, _)| k != DEVELOPER_DIR);
|
||||
combined.push((DEVELOPER_DIR.into(), Some(dir.clone())));
|
||||
}
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none() && self.developer_dir.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,6 +157,31 @@ pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
const DEVELOPER_DIR: &str = "DEVELOPER_DIR";
|
||||
|
||||
/// Sets or clears the `DEVELOPER_DIR` (the Xcode `xcrun`, `xcodebuild` and sourcekit-lsp use)
|
||||
/// injected for children started in `root`. Returns whether it changed.
|
||||
pub fn set_developer_dir(root: &Path, dir: Option<OsString>) -> bool {
|
||||
let dir = dir.filter(|d| !d.is_empty());
|
||||
let mut entries = entries();
|
||||
let idx = match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) if entries[idx].developer_dir == dir => return false,
|
||||
Some(idx) => idx,
|
||||
None if dir.is_none() => return false,
|
||||
None => {
|
||||
entries.push(Entry::new(root.to_path_buf()));
|
||||
entries.len() - 1
|
||||
}
|
||||
};
|
||||
let entry = &mut entries[idx];
|
||||
entry.developer_dir = dir;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
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())
|
||||
@@ -202,6 +240,28 @@ mod tests {
|
||||
assert!(for_dir(inner).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_projects_xcode_wins_over_envrc_and_clears() {
|
||||
let root = Path::new("/openidea-test-env/xcode");
|
||||
set(root, vec![change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
|
||||
assert!(set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
|
||||
assert!(!set_developer_dir(root, Some("/Applications/Xcode-beta.app/Contents/Developer".into())));
|
||||
assert_eq!(
|
||||
*for_dir(&root.join("App")),
|
||||
[change("A", Some("1")), change("DEVELOPER_DIR", Some("/Applications/Xcode-beta.app/Contents/Developer"))]
|
||||
);
|
||||
assert!(set_developer_dir(root, None));
|
||||
assert_eq!(*for_dir(root), [change("DEVELOPER_DIR", Some("/envrc")), change("A", Some("1"))]);
|
||||
remove(root);
|
||||
assert!(for_dir(root).is_empty());
|
||||
let alone = Path::new("/openidea-test-env/xcode-alone");
|
||||
assert!(!set_developer_dir(alone, Some("".into())), "empty is the system default");
|
||||
assert!(set_developer_dir(alone, Some("/X".into())));
|
||||
assert_eq!(*for_dir(alone), [change("DEVELOPER_DIR", Some("/X"))]);
|
||||
assert!(set_developer_dir(alone, None));
|
||||
assert!(entries().iter().all(|e| e.root != alone), "an empty entry is dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waiting_ends_once_the_environment_is_read() {
|
||||
let root = Path::new("/openidea-test-env/waiting");
|
||||
|
||||
@@ -203,6 +203,9 @@ pub enum RunTargetKind {
|
||||
Docker,
|
||||
/// A new container of a Compose service (`docker compose run --rm`).
|
||||
Compose,
|
||||
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
|
||||
/// through `/mnt/<drive>`.
|
||||
Wsl,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
|
||||
@@ -215,7 +218,8 @@ pub struct RunTarget {
|
||||
pub name: String,
|
||||
/// [`SshConfiguration::id`] (SSH).
|
||||
pub ssh_config: String,
|
||||
/// Remote folder the project is synchronised to and run from (SSH).
|
||||
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
|
||||
/// path, empty = its `/mnt/<drive>` path (WSL).
|
||||
pub project_root: String,
|
||||
/// Upload changed project files before each run (SSH).
|
||||
pub sync_before_run: bool,
|
||||
@@ -241,6 +245,8 @@ pub struct RunTarget {
|
||||
pub run_options: String,
|
||||
/// Run as the image's user instead of the project folder's owner (Linux).
|
||||
pub image_user: bool,
|
||||
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
|
||||
pub distro: String,
|
||||
}
|
||||
|
||||
/// A plugin-owned argv wrapper for project runs (API 1.4).
|
||||
|
||||
@@ -1452,6 +1452,7 @@ pub struct LanguagesSettings {
|
||||
pub arduino: ArduinoSettings,
|
||||
pub zig: ZigSettings,
|
||||
pub flutter: FlutterSettings,
|
||||
pub swift: SwiftSettings,
|
||||
}
|
||||
|
||||
impl Default for LanguagesSettings {
|
||||
@@ -1485,6 +1486,7 @@ impl Default for LanguagesSettings {
|
||||
arduino: ArduinoSettings::default(),
|
||||
zig: ZigSettings::default(),
|
||||
flutter: FlutterSettings::default(),
|
||||
swift: SwiftSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1769,6 +1771,26 @@ pub struct ZigSettings {
|
||||
pub zig: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SwiftSettings {
|
||||
/// The Xcode (`Xcode.app` or its `Contents/Developer`) whose tools the project's sourcekit-lsp,
|
||||
/// `xcodebuild`, `xcrun` and terminals use, as `DEVELOPER_DIR`. Empty = the `xcode-select` one.
|
||||
pub xcode: String,
|
||||
}
|
||||
|
||||
impl SwiftSettings {
|
||||
/// [`Self::xcode`] as a `DEVELOPER_DIR` value (`Xcode.app` gets `/Contents/Developer`); `None` when unset.
|
||||
pub fn developer_dir(&self) -> Option<std::path::PathBuf> {
|
||||
let xcode = self.xcode.trim();
|
||||
if xcode.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = std::path::Path::new(xcode);
|
||||
Some(if path.extension().is_some_and(|e| e == "app") { path.join("Contents/Developer") } else { path.into() })
|
||||
}
|
||||
}
|
||||
|
||||
/// The Flutter plugin's "Flutter SDK path".
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -1975,6 +1997,10 @@ pub struct TypeScriptSettings {
|
||||
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
|
||||
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
pub tsserver_max_memory: u32,
|
||||
/// tsserver's log (`typescript.tsserver.log`). TypeScript: Open TS Server Log opens it.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = TsServerLog)]
|
||||
pub tsserver_log: TsServerLog,
|
||||
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
/// `tsconfig.json` reports the errors of files that are not open.
|
||||
pub watch_problems: bool,
|
||||
@@ -1982,10 +2008,27 @@ pub struct TypeScriptSettings {
|
||||
|
||||
impl Default for TypeScriptSettings {
|
||||
fn default() -> Self {
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
|
||||
Self {
|
||||
version: "bundled".into(),
|
||||
tsserver_max_memory: 0,
|
||||
tsserver_log: TsServerLog::Off,
|
||||
watch_problems: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// tsserver's log verbosity, as vtsls' `typescript.tsserver.log` spells it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TsServerLog {
|
||||
#[default]
|
||||
Off,
|
||||
Terse,
|
||||
Normal,
|
||||
RequestTime,
|
||||
Verbose,
|
||||
}
|
||||
|
||||
/// Dependency scope for a module dependency or project library (IDEA's Modules › Dependencies).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -2011,6 +2054,37 @@ pub struct ProjectLibrary {
|
||||
pub scope: DependencyScope,
|
||||
}
|
||||
|
||||
/// A library class entry written as a jar glob: `dir/*.jar` → `(dir, false)`, `dir/**/*.jar` → `(dir, true)`.
|
||||
pub fn split_jar_glob(entry: &str) -> Option<(&str, bool)> {
|
||||
let entry = entry.trim();
|
||||
if let Some(base) = entry.strip_suffix("/**/*.jar").or_else(|| entry.strip_suffix(r"\**\*.jar")) {
|
||||
return Some((base, true));
|
||||
}
|
||||
entry.strip_suffix("/*.jar").or_else(|| entry.strip_suffix(r"\*.jar")).map(|base| (base, false))
|
||||
}
|
||||
|
||||
/// The `.jar` files in `dir` (and its subfolders when `recursive`), sorted by name per folder.
|
||||
pub fn jar_files(dir: &std::path::Path, recursive: bool) -> Vec<std::path::PathBuf> {
|
||||
fn walk(dir: &std::path::Path, recursive: bool, out: &mut Vec<std::path::PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
let mut entries: Vec<_> = entries.flatten().collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
match entry.file_type() {
|
||||
Ok(t) if t.is_dir() && recursive => walk(&path, true, out),
|
||||
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")) => {
|
||||
out.push(path)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(dir, recursive, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -2158,6 +2232,20 @@ impl Settings {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_xcode_setting_becomes_a_developer_dir() {
|
||||
let dir = |xcode: &str| SwiftSettings { xcode: xcode.into() }.developer_dir();
|
||||
assert_eq!(dir(""), None);
|
||||
assert_eq!(dir(" "), None);
|
||||
assert_eq!(dir("/Applications/Xcode-beta.app"), Some("/Applications/Xcode-beta.app/Contents/Developer".into()));
|
||||
assert_eq!(
|
||||
dir("/Applications/Xcode.app/Contents/Developer"),
|
||||
Some("/Applications/Xcode.app/Contents/Developer".into())
|
||||
);
|
||||
let s: Settings = serde_json::from_str(r#"{"languages":{"swift":{"xcode":"/X.app"}}}"#).unwrap();
|
||||
assert_eq!(s.languages.swift.xcode, "/X.app");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
|
||||
@@ -2168,6 +2256,20 @@ mod tests {
|
||||
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsserver_log_reads_known_levels_and_drops_anything_else() {
|
||||
let log = |v: &str| {
|
||||
let s: Settings =
|
||||
serde_json::from_str(&format!(r#"{{"languages":{{"typescript":{{"tsserverLog":{v}}}}}}}"#)).unwrap();
|
||||
s.languages.typescript.tsserver_log
|
||||
};
|
||||
assert_eq!(log(r#""requestTime""#), TsServerLog::RequestTime);
|
||||
assert_eq!(log(r#""verbose""#), TsServerLog::Verbose);
|
||||
assert_eq!(log(r#""--trace""#), TsServerLog::Off);
|
||||
assert_eq!(log("3"), TsServerLog::Off);
|
||||
assert_eq!(serde_json::to_value(TsServerLog::RequestTime).unwrap(), "requestTime");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_interpreter_may_name_a_run_target() {
|
||||
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
|
||||
|
||||
@@ -530,6 +530,7 @@ pub struct DebuggerSettings {
|
||||
/// Java: whether to reload changed classes into running debug sessions after compilation.
|
||||
pub hot_swap_after_compile: HotSwapPolicy,
|
||||
pub python: PythonDebuggerSettings,
|
||||
pub cpp: CppDebuggerSettings,
|
||||
}
|
||||
|
||||
impl Default for DebuggerSettings {
|
||||
@@ -552,6 +553,7 @@ impl Default for DebuggerSettings {
|
||||
flutter_hot_reload_on_save: true,
|
||||
hot_swap_after_compile: HotSwapPolicy::Ask,
|
||||
python: PythonDebuggerSettings::default(),
|
||||
cpp: CppDebuggerSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -570,6 +572,14 @@ impl Default for PythonDebuggerSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// C/C++ debugger executables. Empty paths use automatic discovery.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CppDebuggerSettings {
|
||||
pub gdb_executable: String,
|
||||
pub lldb_dap_executable: String,
|
||||
}
|
||||
|
||||
/// Run/Debug configuration behaviour.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -616,6 +626,8 @@ pub struct TerminalSettings {
|
||||
pub close_on_exit: bool,
|
||||
pub mouse_reporting: bool,
|
||||
pub copy_on_selection: bool,
|
||||
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
|
||||
pub osc52_clipboard: bool,
|
||||
pub paste_on_middle_click: bool,
|
||||
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
|
||||
pub right_click_paste: bool,
|
||||
@@ -656,6 +668,7 @@ impl Default for TerminalSettings {
|
||||
close_on_exit: true,
|
||||
mouse_reporting: true,
|
||||
copy_on_selection: false,
|
||||
osc52_clipboard: true,
|
||||
paste_on_middle_click: true,
|
||||
right_click_paste: false,
|
||||
override_ide_shortcuts: true,
|
||||
@@ -800,4 +813,17 @@ mod tests {
|
||||
assert_eq!(serialized["hotSwapAfterCompile"], raw);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
|
||||
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
|
||||
assert!(missing.cpp.gdb_executable.is_empty());
|
||||
assert!(missing.cpp.lldb_dap_executable.is_empty());
|
||||
|
||||
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
|
||||
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
|
||||
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
|
||||
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
|
||||
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,24 @@ pub fn parse(path: &Path) -> Option<WslPath> {
|
||||
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
|
||||
}
|
||||
|
||||
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
|
||||
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
|
||||
/// other network shares and relative paths.
|
||||
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
|
||||
if let Some(w) = parse(path) {
|
||||
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
|
||||
}
|
||||
let s = path.to_string_lossy().replace('\\', "/");
|
||||
let s = s.strip_prefix("//?/").unwrap_or(&s);
|
||||
let mut chars = s.chars();
|
||||
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
|
||||
let rest = chars.as_str().strip_prefix(':')?;
|
||||
if !(rest.is_empty() || rest.starts_with('/')) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
|
||||
}
|
||||
|
||||
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
|
||||
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
|
||||
pub fn is_valid_distro(name: &str) -> bool {
|
||||
@@ -86,6 +104,57 @@ pub fn list_distros() -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Where this machine reads `distro`'s file system.
|
||||
pub fn share_root(distro: &str) -> std::path::PathBuf {
|
||||
format!(r"\\wsl.localhost\{distro}").into()
|
||||
}
|
||||
|
||||
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
|
||||
pub fn path_parts(linux: &str) -> Vec<&str> {
|
||||
let mut parts: Vec<&str> = Vec::new();
|
||||
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
|
||||
if c == ".." {
|
||||
parts.pop();
|
||||
} else {
|
||||
parts.push(c);
|
||||
}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
|
||||
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
|
||||
/// within `linux`, never above the drive or the share.
|
||||
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
|
||||
let parts = path_parts(linux);
|
||||
let base = match parts.as_slice() {
|
||||
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
|
||||
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
|
||||
return parts[2..].iter().fold(base, |p, c| p.join(c));
|
||||
}
|
||||
_ => share_root(distro),
|
||||
};
|
||||
parts.iter().fold(base, |p, c| p.join(c))
|
||||
}
|
||||
|
||||
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
|
||||
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
|
||||
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
|
||||
use crate::cli_process::{CliTool, Decoding};
|
||||
if !is_valid_distro(distro) {
|
||||
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
|
||||
}
|
||||
let mut cmd = std::process::Command::new(EXE);
|
||||
cmd.args(["-d", distro, "--exec"]).args(args);
|
||||
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
|
||||
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
|
||||
if out.success {
|
||||
return Ok(stdout);
|
||||
}
|
||||
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
|
||||
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -103,6 +172,21 @@ mod tests {
|
||||
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_paths_map_onto_the_distro() {
|
||||
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
|
||||
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
|
||||
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
|
||||
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
|
||||
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
|
||||
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
|
||||
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
|
||||
assert_eq!(l(r"\\server\share\a"), None);
|
||||
assert_eq!(l(r"C:relative"), None);
|
||||
assert_eq!(l("app"), None);
|
||||
assert_eq!(l("/home/me"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_root_and_foreign_paths() {
|
||||
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
|
||||
@@ -127,6 +211,14 @@ mod tests {
|
||||
assert!(parse_distro_list(b"").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
|
||||
use std::path::PathBuf;
|
||||
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
|
||||
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
|
||||
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_names_cannot_smuggle_options_or_paths() {
|
||||
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
|
||||
|
||||
@@ -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 and Cobertura XML, SimpleCov, coverage.py data)"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo, xcodebuild) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data, xccov)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -59,7 +59,7 @@ pub(crate) fn parse(text: &str, module: &str, module_dir: &Path) -> Accumulator
|
||||
|
||||
impl Accumulator {
|
||||
/// Removes the branch data of lines whose branches are all taken or all missed.
|
||||
fn drop_unanimous_branches(&mut self) {
|
||||
pub(crate) fn drop_unanimous_branches(&mut self) {
|
||||
for lines in self.files.values_mut() {
|
||||
for acc in lines.values_mut() {
|
||||
let taken = acc.branches.values().filter(|t| **t).count();
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//! | Ruby (rspec, minitest, rake, scripts) | SimpleCov (`coverage/.resultset.json`) | SimpleCov resultset |
|
||||
//! | Go (`go test`) | `-coverprofile` | Go cover profile |
|
||||
//! | Maven / Gradle tests | JaCoCo (plugin goals / an init script) | JaCoCo XML |
|
||||
//! | Xcode tests (`xcodebuild test`) | `-enableCodeCoverage YES` | the result bundle, read with `xccov` |
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
@@ -24,6 +25,7 @@ mod jacoco;
|
||||
mod lcov;
|
||||
mod plan;
|
||||
mod simplecov;
|
||||
mod xccov;
|
||||
|
||||
pub use coveragepy::is_data_file;
|
||||
pub use import::{import, import_data};
|
||||
@@ -94,6 +96,8 @@ pub enum CoverageReportSpec {
|
||||
Jacoco { dir: IpcPath },
|
||||
/// The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o <lcov>`).
|
||||
Exported { runner: String, argv: Vec<String>, cwd: IpcPath, env: BTreeMap<String, String>, lcov: IpcPath },
|
||||
/// An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept.
|
||||
Xccov { bundle: IpcPath, root: IpcPath },
|
||||
}
|
||||
|
||||
/// A command line that installs a missing tool (run in the Run tool window).
|
||||
@@ -234,9 +238,31 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
let text = read_report(lcov)?;
|
||||
Ok(lcov::parse(&text, cwd).finish(runner))
|
||||
}
|
||||
CoverageReportSpec::Xccov { bundle, root } => {
|
||||
if !bundle.exists() {
|
||||
return Err(IdeError::not_found(format!("the run produced no result bundle ({})", bundle.display())));
|
||||
}
|
||||
let report = xccov_json(&["--report", "--json"], bundle)?;
|
||||
let archive = xccov_json(&["--archive", "--json"], bundle)?;
|
||||
Ok(xccov::parse(&report, &archive, root)
|
||||
.map_err(|e| IdeError::invalid(format!("unexpected xccov output: {e}")))?
|
||||
.finish("xccov"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `xcrun xccov view <args> <bundle>`'s output.
|
||||
fn xccov_json(args: &[&str], bundle: &Path) -> IdeResult<String> {
|
||||
let out = ide_core::process::prepare(Command::new("xcrun").args(["xccov", "view"]).args(args).arg(bundle))
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot run xcrun xccov: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let text = ide_core::output_encoding::decode_tool_output(&out.stderr).trim().to_owned();
|
||||
return Err(IdeError::not_found(format!("the result bundle has no coverage data: {text}")));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
}
|
||||
|
||||
fn read_report(path: &Path) -> IdeResult<String> {
|
||||
std::fs::read_to_string(path).map_err(|e| match e.kind() {
|
||||
std::io::ErrorKind::NotFound => {
|
||||
|
||||
@@ -61,6 +61,9 @@ fn ready(
|
||||
/// data; it must exist (the Gradle init script is written there). Probes tools,
|
||||
/// so call it from a blocking thread.
|
||||
pub fn prepare(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared {
|
||||
if config.kind == "xcode-test" {
|
||||
return xcode(root, config, out);
|
||||
}
|
||||
let dir = wrap::run_dir(root, config);
|
||||
let program = program_name(&config.command);
|
||||
let first = config.args.first().map(String::as_str).unwrap_or_default();
|
||||
@@ -336,6 +339,20 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
|
||||
ready("coverage.py", &config, command, args, report)
|
||||
}
|
||||
|
||||
/// `xcodebuild test` with coverage on, into a result bundle of its own (`xcode::prepare_test`
|
||||
/// adds it at launch).
|
||||
fn xcode(root: &Path, config: &RunConfig, out: &Path) -> CoveragePrepared {
|
||||
let mut config = config.clone();
|
||||
if let Some(at) = config.args.iter().position(|a| a == "-enableCodeCoverage") {
|
||||
config.args.drain(at..(at + 2).min(config.args.len()));
|
||||
}
|
||||
config.args.extend([s("-enableCodeCoverage"), s("YES")]);
|
||||
let bundle = out.join("coverage.xcresult");
|
||||
config.extras.params.insert(s(ide_run::xcode::RESULT_BUNDLE_PARAM), path(&bundle));
|
||||
let report = CoverageReportSpec::Xccov { bundle: bundle.into(), root: root.to_path_buf().into() };
|
||||
ready("xccov", &config, config.command.clone(), config.args.clone(), report)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -535,6 +552,23 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xcode_tests_turn_coverage_on_into_their_own_bundle() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = cfg("xcode-test", "xcodebuild", &["test", "-scheme", "App", "-enableCodeCoverage", "NO"]);
|
||||
let p = prepare(dir.path(), &config, dir.path());
|
||||
let (l, report) = launch(&p);
|
||||
assert_eq!(l.args, ["test", "-scheme", "App", "-enableCodeCoverage", "YES"]);
|
||||
let bundle = dir.path().join("coverage.xcresult");
|
||||
assert_eq!(l.extras.params[ide_run::xcode::RESULT_BUNDLE_PARAM], bundle.to_string_lossy());
|
||||
assert!(matches!(report, CoverageReportSpec::Xccov { bundle: b, .. } if (b.as_ref() as &Path) == bundle));
|
||||
|
||||
// A trailing flag without a value is replaced too.
|
||||
let config = cfg("xcode-test", "xcodebuild", &["test", "-enableCodeCoverage"]);
|
||||
let p = prepare(dir.path(), &config, dir.path());
|
||||
assert_eq!(launch(&p).0.args, ["test", "-enableCodeCoverage", "YES"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_commands_are_unsupported() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Xcode coverage (`xcodebuild test -enableCodeCoverage YES`), read from the result bundle:
|
||||
//!
|
||||
//! - `xcrun xccov view --report --json <bundle>`: the targets and their files. Files that only
|
||||
//! test bundles (`*.xctest`) compile are left out.
|
||||
//! - `xcrun xccov view --archive --json <bundle>`: `{ "<path>": [{ line, isExecutable,
|
||||
//! executionCount, subranges? }] }` for every file. A subrange is a region of the line with its
|
||||
//! own count; a covered line with a missed region is partial.
|
||||
|
||||
use crate::Accumulator;
|
||||
use serde::Deserialize;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Report {
|
||||
#[serde(default)]
|
||||
targets: Vec<Target>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Target {
|
||||
#[serde(default)]
|
||||
build_product_path: String,
|
||||
#[serde(default)]
|
||||
files: Vec<ReportFile>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ReportFile {
|
||||
path: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Line {
|
||||
line: u32,
|
||||
is_executable: bool,
|
||||
#[serde(default)]
|
||||
execution_count: u64,
|
||||
#[serde(default)]
|
||||
subranges: Vec<Subrange>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Subrange {
|
||||
column: u32,
|
||||
#[serde(default)]
|
||||
length: u32,
|
||||
#[serde(default)]
|
||||
execution_count: u64,
|
||||
}
|
||||
|
||||
/// `path` inside the project as the project names it: the project and xccov may name it through
|
||||
/// different symlinks (`/tmp` and `/private/tmp`). `None` outside the project and for DerivedData.
|
||||
fn in_project(path: &Path, root: &Path, real_root: &Path) -> Option<PathBuf> {
|
||||
let real;
|
||||
let rel = match path.strip_prefix(root) {
|
||||
Ok(rel) => rel,
|
||||
Err(_) => {
|
||||
real = path.canonicalize().ok()?;
|
||||
real.strip_prefix(real_root).ok()?
|
||||
}
|
||||
};
|
||||
let generated = rel.components().any(|c| matches!(c, Component::Normal(n) if n == "DerivedData" || n == ".build"));
|
||||
(!generated).then(|| root.join(rel))
|
||||
}
|
||||
|
||||
pub(crate) fn parse(report: &str, archive: &str, root: &Path) -> Result<Accumulator, serde_json::Error> {
|
||||
let report: Report = serde_json::from_str(report)?;
|
||||
let archive: BTreeMap<String, Vec<Line>> = serde_json::from_str(archive)?;
|
||||
// App and framework sources: a file listed by an app or framework target counts even when a test
|
||||
// bundle compiles it too (sources added to the test target's membership instead of `@testable`).
|
||||
let is_test_bundle = |t: &Target| {
|
||||
Path::new(&t.build_product_path)
|
||||
.components()
|
||||
.any(|c| matches!(c, Component::Normal(n) if Path::new(n).extension().is_some_and(|e| e == "xctest")))
|
||||
};
|
||||
let real_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
|
||||
// Both views go through `in_project`, so they match however each spells the path.
|
||||
let sources: BTreeSet<PathBuf> = report
|
||||
.targets
|
||||
.iter()
|
||||
.filter(|t| !is_test_bundle(t))
|
||||
.flat_map(|t| &t.files)
|
||||
.filter_map(|f| in_project(Path::new(&f.path), root, &real_root))
|
||||
.collect();
|
||||
let mut acc = Accumulator::default();
|
||||
for (file, lines) in &archive {
|
||||
let Some(path) = in_project(Path::new(file), root, &real_root).filter(|p| sources.contains(p)) else {
|
||||
continue;
|
||||
};
|
||||
acc.file(&path);
|
||||
for l in lines.iter().filter(|l| l.is_executable && l.line > 0) {
|
||||
let n = l.line - 1;
|
||||
acc.line(&path, n, l.execution_count);
|
||||
if !l.subranges.is_empty() {
|
||||
acc.branch(&path, n, "line".into(), l.execution_count > 0);
|
||||
for r in &l.subranges {
|
||||
acc.branch(&path, n, format!("{}+{}", r.column, r.length), r.execution_count > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Regions are not branches: keep only the partial marks of lines with mixed regions.
|
||||
acc.drop_unanimous_branches();
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Captured from `xcodebuild test -enableCodeCoverage YES` (Xcode 27.1) on an app with a unit
|
||||
// test target; paths rewritten to /Users/me.
|
||||
const REPORT: &str = include_str!("../tests/fixtures/xccov-report.json");
|
||||
const ARCHIVE: &str = include_str!("../tests/fixtures/xccov-archive.json");
|
||||
|
||||
#[test]
|
||||
fn reads_app_sources_and_leaves_out_test_bundles() {
|
||||
let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/CovDemo")).unwrap().finish("xccov");
|
||||
assert!(!suite.has_branches);
|
||||
let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect();
|
||||
assert_eq!(
|
||||
names,
|
||||
[Path::new("/Users/me/CovDemo/CovDemo/App.swift"), Path::new("/Users/me/CovDemo/CovDemo/Calculator.swift")]
|
||||
);
|
||||
// xccov's own totals for Calculator.swift: 14 of 17 lines.
|
||||
let calc = &suite.files[1];
|
||||
assert_eq!((calc.lines_total, calc.lines_covered), (17, 14));
|
||||
let at = |n: u32| calc.lines.iter().find(|l| l.line == n).unwrap();
|
||||
// `return nil` (line 8) never ran; `if b == 0 {` (line 7) ran with a missed region.
|
||||
assert_eq!(at(7).hits, 0);
|
||||
assert!(at(6).partial());
|
||||
assert!(!at(1).partial());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_outside_the_project_are_dropped() {
|
||||
let suite = parse(REPORT, ARCHIVE, Path::new("/Users/me/Other")).unwrap().finish("xccov");
|
||||
assert!(suite.files.is_empty());
|
||||
let report = r#"{"targets":[{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/DerivedData/G.swift"},{"path":"/p/A.swift"}]}]}"#;
|
||||
let line = r#"[{"line":1,"isExecutable":true,"executionCount":2}]"#;
|
||||
let archive = format!(r#"{{"/p/DerivedData/G.swift":{line},"/p/A.swift":{line}}}"#);
|
||||
let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov");
|
||||
assert_eq!(suite.files.len(), 1);
|
||||
assert_eq!(suite.files[0].lines[0].hits, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_of_an_app_and_a_test_bundle_counts() {
|
||||
let report = r#"{"targets":[
|
||||
{"buildProductPath":"/d/App.app/App","files":[{"path":"/p/A.swift"}]},
|
||||
{"buildProductPath":"/d/AppTests.xctest/AppTests","files":[{"path":"/p/A.swift"},{"path":"/p/T.swift"}]}]}"#;
|
||||
let line = r#"[{"line":1,"isExecutable":true,"executionCount":1}]"#;
|
||||
let archive = format!(r#"{{"/p/A.swift":{line},"/p/T.swift":{line}}}"#);
|
||||
let suite = parse(report, &archive, Path::new("/p")).unwrap().finish("xccov");
|
||||
let names: Vec<_> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect();
|
||||
assert_eq!(names, [Path::new("/p/A.swift")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn paths_through_another_symlink_map_to_the_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let real = dir.path().canonicalize().unwrap().join("real");
|
||||
std::fs::create_dir_all(&real).unwrap();
|
||||
std::fs::write(real.join("A.swift"), "").unwrap();
|
||||
let link = dir.path().join("link");
|
||||
std::os::unix::fs::symlink(&real, &link).unwrap();
|
||||
let file = real.join("A.swift").to_string_lossy().into_owned();
|
||||
let report =
|
||||
format!(r#"{{"targets":[{{"buildProductPath":"/d/App.app/App","files":[{{"path":"{file}"}}]}}]}}"#);
|
||||
let archive = format!(r#"{{"{file}":[{{"line":1,"isExecutable":true,"executionCount":1}}]}}"#);
|
||||
let suite = parse(&report, &archive, &link).unwrap().finish("xccov");
|
||||
assert_eq!(suite.files.len(), 1);
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, link.join("A.swift"));
|
||||
|
||||
// The report names the file through the symlink, the archive by its real path.
|
||||
let linked = link.join("A.swift").to_string_lossy().into_owned();
|
||||
let report = report.replace(&file, &linked);
|
||||
let suite = parse(&report, &archive, &link).unwrap().finish("xccov");
|
||||
assert_eq!(suite.files.len(), 1);
|
||||
assert_eq!(suite.files[0].lines[0].hits, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
{
|
||||
"/Users/me/CovDemo/CovDemo/App.swift": [
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 1
|
||||
},
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 2
|
||||
},
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 3
|
||||
},
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 4
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 5
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 6
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 7
|
||||
}
|
||||
],
|
||||
"/Users/me/CovDemo/CovDemo/Calculator.swift": [
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 1
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 2
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 3
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 4
|
||||
},
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 5
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 6
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 7,
|
||||
"subranges": [
|
||||
{
|
||||
"column": 19,
|
||||
"executionCount": 0,
|
||||
"length": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"executionCount": 0,
|
||||
"isExecutable": true,
|
||||
"line": 8
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 9,
|
||||
"subranges": [
|
||||
{
|
||||
"column": 1,
|
||||
"executionCount": 0,
|
||||
"length": 9
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 10
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 11
|
||||
},
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 12
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 13
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 14,
|
||||
"subranges": [
|
||||
{
|
||||
"column": 18,
|
||||
"executionCount": 0,
|
||||
"length": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"executionCount": 0,
|
||||
"isExecutable": true,
|
||||
"line": 15
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 16,
|
||||
"subranges": [
|
||||
{
|
||||
"column": 1,
|
||||
"executionCount": 0,
|
||||
"length": 9
|
||||
},
|
||||
{
|
||||
"column": 26,
|
||||
"executionCount": 0,
|
||||
"length": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"executionCount": 0,
|
||||
"isExecutable": true,
|
||||
"line": 17
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 18,
|
||||
"subranges": [
|
||||
{
|
||||
"column": 1,
|
||||
"executionCount": 0,
|
||||
"length": 9
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 19
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 20
|
||||
}
|
||||
],
|
||||
"/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift": [
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 1
|
||||
},
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 2
|
||||
},
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 3
|
||||
},
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 4
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 5
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 6
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 7
|
||||
},
|
||||
{
|
||||
"isExecutable": false,
|
||||
"line": 8
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 9
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 10
|
||||
},
|
||||
{
|
||||
"executionCount": 1,
|
||||
"isExecutable": true,
|
||||
"line": 11
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
{
|
||||
"coveredLines": 28,
|
||||
"executableLines": 31,
|
||||
"lineCoverage": 0.9032258064516129,
|
||||
"targets": [
|
||||
{
|
||||
"buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/CovDemo",
|
||||
"coveredLines": 18,
|
||||
"executableLines": 21,
|
||||
"files": [
|
||||
{
|
||||
"coveredLines": 14,
|
||||
"executableLines": 17,
|
||||
"functions": [
|
||||
{
|
||||
"coveredLines": 3,
|
||||
"executableLines": 3,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 1,
|
||||
"lineNumber": 2,
|
||||
"name": "Calculator.add(_:_:)"
|
||||
},
|
||||
{
|
||||
"coveredLines": 5,
|
||||
"executableLines": 6,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 0.8333333333333334,
|
||||
"lineNumber": 6,
|
||||
"name": "Calculator.divide(_:_:)"
|
||||
},
|
||||
{
|
||||
"coveredLines": 6,
|
||||
"executableLines": 8,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 0.75,
|
||||
"lineNumber": 13,
|
||||
"name": "Calculator.describe(_:)"
|
||||
}
|
||||
],
|
||||
"lineCoverage": 0.8235294117647058,
|
||||
"name": "Calculator.swift",
|
||||
"path": "/Users/me/CovDemo/CovDemo/Calculator.swift"
|
||||
},
|
||||
{
|
||||
"coveredLines": 4,
|
||||
"executableLines": 4,
|
||||
"functions": [
|
||||
{
|
||||
"coveredLines": 3,
|
||||
"executableLines": 3,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 1,
|
||||
"lineNumber": 5,
|
||||
"name": "CovDemoApp.body.getter"
|
||||
},
|
||||
{
|
||||
"coveredLines": 1,
|
||||
"executableLines": 1,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 1,
|
||||
"lineNumber": 6,
|
||||
"name": "closure #1 in CovDemoApp.body.getter"
|
||||
}
|
||||
],
|
||||
"lineCoverage": 1,
|
||||
"name": "App.swift",
|
||||
"path": "/Users/me/CovDemo/CovDemo/App.swift"
|
||||
}
|
||||
],
|
||||
"lineCoverage": 0.8571428571428571,
|
||||
"name": "CovDemo.app"
|
||||
},
|
||||
{
|
||||
"buildProductPath": "/Users/me/Library/Developer/Xcode/DerivedData/CovDemo-abc/Build/Products/Debug-iphonesimulator/CovDemo.app/PlugIns/CovDemoTests.xctest/CovDemoTests",
|
||||
"coveredLines": 10,
|
||||
"executableLines": 10,
|
||||
"files": [
|
||||
{
|
||||
"coveredLines": 10,
|
||||
"executableLines": 10,
|
||||
"functions": [
|
||||
{
|
||||
"coveredLines": 3,
|
||||
"executableLines": 3,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 1,
|
||||
"lineNumber": 5,
|
||||
"name": "CalculatorTests.testAdd()"
|
||||
},
|
||||
{
|
||||
"coveredLines": 1,
|
||||
"executableLines": 1,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 1,
|
||||
"lineNumber": 6,
|
||||
"name": "implicit closure #1 in CalculatorTests.testAdd()"
|
||||
},
|
||||
{
|
||||
"coveredLines": 1,
|
||||
"executableLines": 1,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 1,
|
||||
"lineNumber": 6,
|
||||
"name": "implicit closure #2 in CalculatorTests.testAdd()"
|
||||
},
|
||||
{
|
||||
"coveredLines": 3,
|
||||
"executableLines": 3,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 1,
|
||||
"lineNumber": 9,
|
||||
"name": "CalculatorTests.testDivide()"
|
||||
},
|
||||
{
|
||||
"coveredLines": 1,
|
||||
"executableLines": 1,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 1,
|
||||
"lineNumber": 10,
|
||||
"name": "implicit closure #1 in CalculatorTests.testDivide()"
|
||||
},
|
||||
{
|
||||
"coveredLines": 1,
|
||||
"executableLines": 1,
|
||||
"executionCount": 1,
|
||||
"lineCoverage": 1,
|
||||
"lineNumber": 10,
|
||||
"name": "implicit closure #2 in CalculatorTests.testDivide()"
|
||||
}
|
||||
],
|
||||
"lineCoverage": 1,
|
||||
"name": "CalculatorTests.swift",
|
||||
"path": "/Users/me/CovDemo/CovDemoTests/CalculatorTests.swift"
|
||||
}
|
||||
],
|
||||
"lineCoverage": 1,
|
||||
"name": "CovDemoTests.xctest"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -360,23 +360,63 @@ fn find_binary_in(
|
||||
}
|
||||
|
||||
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
|
||||
/// lldb-dap without putting it on `PATH`.
|
||||
/// lldb-dap without putting it on `PATH`. Elsewhere lldb-dap may carry its LLVM version.
|
||||
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
|
||||
find_binary(command, cwd).or_else(|| xcrun_tool(command))
|
||||
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd)).or_else(|| {
|
||||
(command == "lldb-dap" && !cfg!(windows))
|
||||
.then(|| versioned_lldb_dap(&search_dirs(cwd), Path::new("/usr/lib")))
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// Debian and Ubuntu install LLVM's lldb-dap as `lldb-dap-18` (`lldb-vscode-14` before
|
||||
/// LLVM 18 renamed it; same protocol) on `PATH`, or only as `/usr/lib/llvm-18/bin/lldb-dap`.
|
||||
/// The newest LLVM wins.
|
||||
fn versioned_lldb_dap(dirs: &[PathBuf], lib: &Path) -> Option<PathBuf> {
|
||||
let version = |name: &str| -> Option<u32> {
|
||||
let v = name.strip_prefix("lldb-dap-").or_else(|| name.strip_prefix("lldb-vscode-"))?;
|
||||
v.parse().ok()
|
||||
};
|
||||
let mut found: Vec<(u32, PathBuf)> = Vec::new();
|
||||
for dir in dirs {
|
||||
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
if let Some(v) = path.file_name().and_then(|n| n.to_str()).and_then(version)
|
||||
&& is_executable(&path, false)
|
||||
{
|
||||
found.push((v, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
for entry in std::fs::read_dir(lib).into_iter().flatten().flatten() {
|
||||
let Some(v) = entry.file_name().to_str().and_then(|n| n.strip_prefix("llvm-")?.parse::<u32>().ok()) else {
|
||||
continue;
|
||||
};
|
||||
for name in ["lldb-dap", "lldb-vscode"] {
|
||||
let path = entry.path().join("bin").join(name);
|
||||
if is_executable(&path, false) {
|
||||
found.push((v, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
found.into_iter().max_by_key(|(v, _)| *v).map(|(_, p)| p)
|
||||
}
|
||||
|
||||
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
|
||||
#[cfg(target_os = "macos")]
|
||||
fn xcrun_tool(command: &str) -> Option<PathBuf> {
|
||||
fn xcrun_tool(command: &str, cwd: &Path) -> Option<PathBuf> {
|
||||
if command != "lldb-dap" {
|
||||
return None;
|
||||
}
|
||||
let out = std::process::Command::new("/usr/bin/xcrun").args(["-f", command]).stderr(Stdio::null()).output().ok()?;
|
||||
let mut cmd = std::process::Command::new("/usr/bin/xcrun");
|
||||
cmd.current_dir(cwd);
|
||||
let out = ide_core::process::prepare(&mut cmd).args(["-f", command]).stderr(Stdio::null()).output().ok()?;
|
||||
let path = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
|
||||
(out.status.success() && is_executable(&path, false)).then_some(path)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn xcrun_tool(_command: &str) -> Option<PathBuf> {
|
||||
fn xcrun_tool(_command: &str, _cwd: &Path) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
@@ -469,7 +509,7 @@ fn is_app_execution_alias(path: &Path) -> bool {
|
||||
|
||||
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
|
||||
/// "Interpreter `dap' unrecognized".
|
||||
const GDB_MIN_MAJOR: u32 = 14;
|
||||
pub(crate) const GDB_MIN_MAJOR: u32 = 14;
|
||||
|
||||
/// `(major, minor)` of the first version number in the output of `gdb --version`
|
||||
/// (`GNU gdb (GDB) 14.2`, `GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1`, `GNU gdb
|
||||
@@ -510,24 +550,29 @@ pub fn parse_gdb_version(output: &str) -> Option<(u32, u32)> {
|
||||
|
||||
/// Probe the already resolved and verified executable with its launch environment.
|
||||
async fn gdb_version(binary: &Path, spec: &AdapterSpec) -> IdeResult<Option<(u32, u32)>> {
|
||||
Ok(probe_gdb_version(binary, &spec.cwd, &spec.env).await)
|
||||
}
|
||||
|
||||
/// `(major, minor)` of `binary --version`, run in `cwd` with `env`; `None` when it doesn't say.
|
||||
pub(crate) async fn probe_gdb_version(binary: &Path, cwd: &Path, env: &[(String, String)]) -> Option<(u32, u32)> {
|
||||
let mut probe = Command::new(binary);
|
||||
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
|
||||
if let Some(path) = adapter_path(env, cwd) {
|
||||
probe.env("PATH", path);
|
||||
}
|
||||
probe.current_dir(&spec.cwd);
|
||||
probe.current_dir(cwd);
|
||||
ide_core::process::prepare(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.arg("--version")
|
||||
.envs(spec.env.iter().cloned())
|
||||
.envs(env.iter().cloned())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output();
|
||||
let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(15), probe).await else {
|
||||
return Ok(None);
|
||||
return None;
|
||||
};
|
||||
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
|
||||
parse_gdb_version(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
|
||||
/// Refuse old GDB versions and report whether launch must follow configurationDone.
|
||||
@@ -540,8 +585,9 @@ async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
|
||||
return Ok(major == 15);
|
||||
}
|
||||
let mut msg = format!(
|
||||
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
|
||||
this one has no DAP interpreter (`gdb -i dap`)"
|
||||
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor} at {}): \
|
||||
this one has no DAP interpreter (`gdb -i dap`)",
|
||||
binary.display(),
|
||||
);
|
||||
if let Some(hint) = &spec.install_hint {
|
||||
msg.push_str(". ");
|
||||
@@ -1023,6 +1069,48 @@ mod tests {
|
||||
assert!(builtin("nope").is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn gdb_version_check_probes_the_adapter_command() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let binary = dir.path().join("custom gdb");
|
||||
std::fs::write(&binary, "#!/bin/sh\n[ \"$1\" = --version ] && echo 'GNU gdb (GDB) 13.2'\n").unwrap();
|
||||
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_path_buf());
|
||||
spec.command = binary.to_str().unwrap().to_owned();
|
||||
|
||||
let Err(error) = ProcessLauncher.launch(spec, None).await else {
|
||||
panic!("GDB 13 was started as a DAP adapter");
|
||||
};
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(error.message.contains("needs GDB 14 or newer (found 13.2 at "), "{}", error.message);
|
||||
assert!(error.message.contains(binary.to_str().unwrap()), "{}", error.message);
|
||||
}
|
||||
|
||||
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn finds_versioned_lldb_dap() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let exe = |p: &Path| {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "").unwrap();
|
||||
std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
let (bin, lib) = (tmp.path().join("bin"), tmp.path().join("lib"));
|
||||
exe(&bin.join("lldb-vscode-14"));
|
||||
std::fs::write(bin.join("lldb-dap-99"), "").unwrap(); // not executable
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-vscode-14")));
|
||||
exe(&lib.join("llvm-18/bin/lldb-dap"));
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(lib.join("llvm-18/bin/lldb-dap")));
|
||||
exe(&bin.join("lldb-dap-19"));
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-dap-19")));
|
||||
assert_eq!(versioned_lldb_dap(&[], &tmp.path().join("none")), None);
|
||||
}
|
||||
|
||||
/// The first version number of `gdb --version`'s first line, however the distro decorates it.
|
||||
#[test]
|
||||
fn parses_gdb_versions() {
|
||||
|
||||
@@ -22,6 +22,7 @@ mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
pub mod native;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
mod swiftpm;
|
||||
@@ -614,6 +615,16 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
|
||||
Ok(Some(DebugServer { host, port }))
|
||||
}
|
||||
|
||||
/// A source served only through the `source` request whose `path` is no file, such as
|
||||
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
|
||||
/// debug info. Opening it would show an error tab; without a path the stop selects the
|
||||
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
|
||||
/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive.
|
||||
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
|
||||
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
|
||||
reference > 0 && Path::new(path).has_root() && !Path::new(path).exists()
|
||||
}
|
||||
|
||||
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
|
||||
pub(crate) fn frame_from(f: &Value) -> StackFrame {
|
||||
let source = f.get("source");
|
||||
@@ -626,7 +637,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
|
||||
StackFrame {
|
||||
id: f.get("id").and_then(Value::as_i64).unwrap_or_default(),
|
||||
name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(),
|
||||
path: source.and_then(|s| s.get("path")).and_then(Value::as_str).map(Into::into),
|
||||
path: source
|
||||
.and_then(|s| s.get("path"))
|
||||
.and_then(Value::as_str)
|
||||
.filter(|p| !is_pseudo_path(source, p))
|
||||
.map(Into::into),
|
||||
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
presentation_hint: hint,
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! C/C++ launches made for lldb-dap (CMake, Swift packages) fall back to CodeLLDB, then to
|
||||
//! GDB 14 or newer, when the host has no lldb-dap: Linux hosts rarely put one on `PATH`, and
|
||||
//! CodeLLDB is the debugger OpenIDEA can install itself.
|
||||
|
||||
use crate::LaunchConfig;
|
||||
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
|
||||
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
|
||||
|
||||
/// `config` for the first of lldb-dap, CodeLLDB and GDB 14+ that `lookup` finds (it resolves a
|
||||
/// debugger command: a configured tool path, else the search path). Other launches pass through.
|
||||
pub async fn choose(
|
||||
mut config: LaunchConfig,
|
||||
lookup: impl Fn(&str) -> Option<PathBuf> + Send + 'static,
|
||||
) -> IdeResult<LaunchConfig> {
|
||||
if config.adapter != "lldb-dap" || config.request != "launch" {
|
||||
return Ok(config);
|
||||
}
|
||||
let found = tokio::task::spawn_blocking(move || {
|
||||
if lookup("lldb-dap").is_some() {
|
||||
return Found::LldbDap;
|
||||
}
|
||||
if lookup("codelldb").is_some() {
|
||||
return Found::CodeLldb;
|
||||
}
|
||||
lookup("gdb").map_or(Found::Nothing, Found::Gdb)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let cwd = config.cwd.clone().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
|
||||
match found {
|
||||
Found::LldbDap => {}
|
||||
Found::CodeLldb => convert(&mut config, "codelldb")?,
|
||||
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
|
||||
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((&gdb, major, minor)))),
|
||||
// Unknown versions are left to GDB itself, as a GDB launch does.
|
||||
_ => convert(&mut config, "gdb")?,
|
||||
},
|
||||
Found::Nothing => return Err(missing(None)),
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
enum Found {
|
||||
LldbDap,
|
||||
CodeLldb,
|
||||
Gdb(PathBuf),
|
||||
Nothing,
|
||||
}
|
||||
|
||||
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
|
||||
let found = match gdb {
|
||||
Some((path, major, minor)) => format!(
|
||||
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} at {} cannot debug through DAP \
|
||||
(it needs GDB {GDB_MIN_MAJOR} or newer)",
|
||||
path.display(),
|
||||
),
|
||||
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
|
||||
};
|
||||
IdeError::unavailable(format!(
|
||||
"{NO_NATIVE_DEBUGGER}: {found}. Install CodeLLDB, or install lldb-dap or GDB {GDB_MIN_MAJOR} or newer on this host"
|
||||
))
|
||||
}
|
||||
|
||||
/// Rewrites an lldb-dap launch for `to` (`codelldb` or `gdb`). lldb-dap takes the environment as
|
||||
/// `KEY=VALUE` strings and the source map as pairs; the others take the run configuration's
|
||||
/// environment map (`config.env`), CodeLLDB its source map as an object, GDB none.
|
||||
fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
|
||||
let mut extra = match config.extra_json.as_deref().filter(|e| !e.trim().is_empty()).map(serde_json::from_str) {
|
||||
None => Map::new(),
|
||||
Some(Ok(Value::Object(extra))) => extra,
|
||||
Some(Ok(other)) => return Err(IdeError::invalid(format!("launch arguments are not an object: {other}"))),
|
||||
Some(Err(e)) => return Err(IdeError::invalid(format!("invalid launch JSON: {e}"))),
|
||||
};
|
||||
extra.remove("env");
|
||||
let source_map = extra.remove("sourceMap");
|
||||
if to == "codelldb" {
|
||||
if let Some(Value::Array(pairs)) = source_map {
|
||||
let map: Map<String, Value> = pairs
|
||||
.iter()
|
||||
.filter_map(|pair| match pair.as_array().map(Vec::as_slice) {
|
||||
Some([Value::String(from), to]) => Some((from.clone(), to.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if !map.is_empty() {
|
||||
extra.insert("sourceMap".into(), Value::Object(map));
|
||||
}
|
||||
}
|
||||
// CodeLLDB evaluates as Rust unless told otherwise (ide-dap's default for it).
|
||||
let language = if extra.contains_key("swiftpm") { "swift" } else { "cpp" };
|
||||
extra.entry("sourceLanguages").or_insert_with(|| json!([language]));
|
||||
}
|
||||
config.adapter = to.to_owned();
|
||||
config.extra_json = (!extra.is_empty()).then(|| Value::Object(extra).to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn cmake_launch() -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
name: "hello".into(),
|
||||
adapter: "lldb-dap".into(),
|
||||
request: "launch".into(),
|
||||
program: Some("/home/dev/hello/build/hello".into()),
|
||||
args: vec![],
|
||||
cwd: Some(std::path::PathBuf::from("/").into()),
|
||||
env: BTreeMap::from([("A".into(), "1".into())]),
|
||||
extra_json: Some(json!({"env": ["A=1"], "sourceMap": [["/src", "/real/src"]]}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn extra(config: &LaunchConfig) -> Value {
|
||||
config.extra_json.as_deref().map_or(Value::Null, |e| serde_json::from_str(e).unwrap())
|
||||
}
|
||||
|
||||
fn only(names: &'static [&'static str]) -> impl Fn(&str) -> Option<PathBuf> + Send + 'static {
|
||||
move |c| names.contains(&c).then(|| PathBuf::from(format!("/usr/bin/{c}")))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn keeps_lldb_dap_when_it_is_there() {
|
||||
let config = choose(cmake_launch(), only(&["lldb-dap", "codelldb", "gdb"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "lldb-dap");
|
||||
assert_eq!(config.extra_json, cmake_launch().extra_json);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn falls_back_to_codelldb_with_its_launch_shape() {
|
||||
let config = choose(cmake_launch(), only(&["codelldb", "gdb"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "codelldb");
|
||||
assert_eq!(config.env, cmake_launch().env, "the environment comes from the run configuration's map");
|
||||
assert_eq!(
|
||||
extra(&config),
|
||||
json!({"sourceMap": {"/src": "/real/src"}, "sourceLanguages": ["cpp"]}),
|
||||
"no KEY=VALUE env strings; the source map as an object; C++ evaluation"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_swift_package_evaluates_swift_under_codelldb() {
|
||||
let mut launch = cmake_launch();
|
||||
launch.extra_json = Some(json!({"env": [], "swiftpm": {"product": "app", "buildArgs": []}}).to_string());
|
||||
let config = choose(launch, only(&["codelldb"])).await.unwrap();
|
||||
assert_eq!(extra(&config)["sourceLanguages"], json!(["swift"]));
|
||||
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_any_debugger_says_what_to_install() {
|
||||
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
|
||||
assert!(e.message.contains("Install CodeLLDB"), "{}", e.message);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn other_launches_pass_through() {
|
||||
let mut attach = cmake_launch();
|
||||
attach.request = "attach".into();
|
||||
assert_eq!(choose(attach, only(&[])).await.unwrap().adapter, "lldb-dap");
|
||||
let mut rust = cmake_launch();
|
||||
rust.adapter = "codelldb".into();
|
||||
assert_eq!(choose(rust, only(&[])).await.unwrap().adapter, "codelldb");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn fake_gdb(dir: &Path, version: &str) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let gdb = dir.join("gdb");
|
||||
std::fs::write(&gdb, format!("#!/bin/sh\necho '{version}'\n")).unwrap();
|
||||
std::fs::set_permissions(&gdb, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
gdb
|
||||
}
|
||||
|
||||
/// Ubuntu 22.04's GDB 12 has no DAP interpreter: the error names its version (#7001).
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn an_old_gdb_is_named_in_the_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
|
||||
let path = gdb.clone();
|
||||
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| path.clone())).await.unwrap_err();
|
||||
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
|
||||
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
|
||||
assert!(e.message.contains(gdb.to_str().unwrap()), "{}", e.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn falls_back_to_a_gdb_with_dap() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let gdb = fake_gdb(dir.path(), "GNU gdb (GDB) 14.2");
|
||||
let config = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap();
|
||||
assert_eq!(config.adapter, "gdb");
|
||||
assert_eq!(extra(&config), Value::Null, "GDB takes the environment map and has no source map");
|
||||
}
|
||||
}
|
||||
@@ -1134,21 +1134,27 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
|
||||
// CodeLLDB's launcher clears the terminal first; the console keeps the session's earlier output.
|
||||
cmd.args(rest.iter().filter(|a| *a != "--clear-screen"));
|
||||
let cwd = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()).map_or(s.spec.cwd.as_path(), Path::new);
|
||||
for (k, v) in ide_core::process::host_env_fixes_in(cwd) {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
}
|
||||
// See #6806: do not inherit portable-pty's registry-built Windows env block.
|
||||
cmd.env_clear();
|
||||
for (k, v) in ide_core::process::spawnable_host_vars_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
for (k, v) in ide_core::process::shell_env_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
if ide_core::process::is_spawnable_env_pair(&k, &v) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.cwd(cwd);
|
||||
if let Some(env) = args.get("env").and_then(Value::as_object) {
|
||||
for (k, v) in env {
|
||||
match v.as_str() {
|
||||
Some(v) => cmd.env(k, v),
|
||||
Some(v)
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) =>
|
||||
{
|
||||
cmd.env(k, v)
|
||||
}
|
||||
Some(_) => {}
|
||||
None => cmd.env_remove(k),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2164,6 +2164,21 @@ fn frames_keep_their_instruction_pointer() {
|
||||
assert!(json.get("instructionPointerReference").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_drop_pseudo_paths_of_referenced_sources() {
|
||||
let frame = |path: &str, reference: i64| {
|
||||
frame_from(&json!({"id": 1, "name": "f", "line": 1,
|
||||
"source": {"path": path, "sourceReference": reference}}))
|
||||
.path
|
||||
};
|
||||
let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow";
|
||||
assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly");
|
||||
assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent");
|
||||
let here = env!("CARGO_MANIFEST_DIR");
|
||||
assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file");
|
||||
assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn smart_step_into_and_reset_frame() {
|
||||
let h = harness(Script::default());
|
||||
|
||||
+134
-62
@@ -447,6 +447,15 @@ fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
|
||||
);
|
||||
details.partitioning = next();
|
||||
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
|
||||
// PostgreSQL's `table_properties` carries the comment as its last column, so reading it here
|
||||
// saves the separate query `table_comment` would make on the same `pg_class` row.
|
||||
if let Some(comment) = next() {
|
||||
// `table_comment` this replaces yielded `NULL` or empty for no comment, so an empty
|
||||
// comment must not become `Some("")` — the DDL would emit an empty `COMMENT ON`.
|
||||
if !comment.is_empty() {
|
||||
details.comment = Some(comment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flag(v: &Option<String>) -> bool {
|
||||
@@ -1384,8 +1393,61 @@ impl DbManager {
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, ..Default::default() });
|
||||
}
|
||||
// Everything below describes the same table and none of it feeds the next, so it goes
|
||||
// out together. Serialised, this is four round trips on the path that opens a table
|
||||
// (`table_page_on` calls this for the primary key), which is what makes opening a table
|
||||
// feel slow on a remote server. Five queries against a pool of four (`conn.rs`'s `MAX`),
|
||||
// so one waits — still one round trip rather than five.
|
||||
type Rows = Vec<Vec<Option<String>>>;
|
||||
let keys = !matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake);
|
||||
let (index_q, fk_q, trigger_q) = (
|
||||
sql::indexes(driver, schema, table),
|
||||
sql::table_foreign_keys(driver, schema, table),
|
||||
sql::triggers(driver, schema, table),
|
||||
);
|
||||
let (index_rows, fk_rows, trigger_rows, comment_rows, property_rows) = futures::join!(
|
||||
pool.rows(&index_q, MAX_META_ROWS),
|
||||
async {
|
||||
if !keys {
|
||||
return Ok::<Rows, IdeError>(Vec::new());
|
||||
}
|
||||
match pool.rows(&fk_q, MAX_META_ROWS).await {
|
||||
Ok(rows) => Ok(rows),
|
||||
Err(e) => {
|
||||
tracing::warn!("foreign keys: {}", e.message);
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
},
|
||||
async {
|
||||
if !keys {
|
||||
return Ok::<Rows, IdeError>(Vec::new());
|
||||
}
|
||||
match pool.rows(&trigger_q, MAX_META_ROWS).await {
|
||||
Ok(rows) => Ok(rows),
|
||||
Err(e) => {
|
||||
tracing::warn!("triggers: {}", e.message);
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
},
|
||||
async {
|
||||
// PostgreSQL reads it with the properties above; the engines without a
|
||||
// `table_properties` query ask for it here.
|
||||
match sql::table_comment(driver, schema, table) {
|
||||
Some(q) if sql::table_properties(driver, schema, table).is_none() => pool.rows(&q, 1).await,
|
||||
_ => Ok::<Rows, IdeError>(Vec::new()),
|
||||
}
|
||||
},
|
||||
async {
|
||||
match sql::table_properties(driver, schema, table) {
|
||||
Some(q) => catalog_rows(pool, &q).await,
|
||||
None => Ok::<Rows, IdeError>(Vec::new()),
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
for r in index_rows? {
|
||||
let mut it = r.into_iter();
|
||||
let (Some(name), unique, Some(col)) = (it.next().flatten(), it.next().flatten(), it.next().flatten())
|
||||
else {
|
||||
@@ -1401,11 +1463,7 @@ impl DbManager {
|
||||
}),
|
||||
}
|
||||
}
|
||||
let fk_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
|
||||
Vec::new()
|
||||
} else {
|
||||
pool.rows(&sql::table_foreign_keys(driver, schema, table), MAX_META_ROWS).await.unwrap_or_default()
|
||||
};
|
||||
let fk_rows = fk_rows?;
|
||||
let mut foreign_keys = group_foreign_keys(fk_rows, &[]);
|
||||
// SQLite keys that reference the primary key implicitly: look it up.
|
||||
for k in foreign_keys.iter_mut().filter(|k| k.ref_columns.is_empty()) {
|
||||
@@ -1418,15 +1476,7 @@ impl DbManager {
|
||||
.collect();
|
||||
}
|
||||
foreign_keys.retain(|k| k.columns.len() == k.ref_columns.len());
|
||||
let trigger_rows = if matches!(driver, DbDriver::Clickhouse | DbDriver::Snowflake) {
|
||||
Vec::new()
|
||||
} else {
|
||||
pool.rows(&sql::triggers(driver, schema, table), MAX_META_ROWS).await.unwrap_or_else(|e| {
|
||||
tracing::warn!("triggers: {}", e.message);
|
||||
Vec::new()
|
||||
})
|
||||
};
|
||||
let triggers = trigger_rows
|
||||
let triggers = trigger_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
@@ -1439,26 +1489,21 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
let comment = match sql::table_comment(driver, schema, table) {
|
||||
Some(q) => pool.rows(&q, 1).await.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
let comment = comment_rows.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
);
|
||||
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
|
||||
if let Some(q) = sql::table_properties(driver, schema, table) {
|
||||
match catalog_rows(pool, &q).await {
|
||||
Ok(rows) => {
|
||||
if let Some(row) = rows.into_iter().next() {
|
||||
read_table_properties(&mut details, row);
|
||||
}
|
||||
match property_rows {
|
||||
Ok(rows) => {
|
||||
if let Some(row) = rows.into_iter().next() {
|
||||
read_table_properties(&mut details, row);
|
||||
}
|
||||
Err(e) => tracing::warn!("table properties: {}", e.message),
|
||||
}
|
||||
Err(e) => tracing::warn!("table properties: {}", e.message),
|
||||
}
|
||||
Ok(details)
|
||||
}
|
||||
@@ -1669,16 +1714,16 @@ impl DbManager {
|
||||
ddl.map(|d| format!("{};\n", d.trim_end().trim_end_matches(';'))).ok_or_else(missing)
|
||||
}
|
||||
DbDriver::Postgres => {
|
||||
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
|
||||
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()),
|
||||
// Everything the script needs depends on the relation oid, so read that first and
|
||||
// then the rest at once — five queries in flight against a pool of four, so one
|
||||
// waits, but that is still two round trips instead of six.
|
||||
let rel = catalog_rows(&pool, &sql::postgres_relation(schema, name)).await?.into_iter().next();
|
||||
let Some([Some(oid), Some(kind), owner, comment, persistence, partition_key, parent @ ..]) =
|
||||
rel.as_deref()
|
||||
else {
|
||||
return Err(missing());
|
||||
};
|
||||
let oid = oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if kind == "v" || kind == "m" {
|
||||
let def = cells(pool.rows(&format!("SELECT pg_get_viewdef({oid}, true)"), 1).await?, 0);
|
||||
let what = if kind == "m" { "materialized view" } else { "view" };
|
||||
@@ -1686,43 +1731,70 @@ impl DbManager {
|
||||
let target = sql::qualified(driver, schema, name);
|
||||
return Ok(format!("create {what} {target} as\n{};\n", body.trim_end().trim_end_matches(';')));
|
||||
}
|
||||
let columns = pool
|
||||
.rows(&sql::postgres_ddl_columns(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let partition = match parent {
|
||||
[Some(parent_schema), Some(parent_table), Some(bound)] => Some(sql::DdlPartition {
|
||||
parent_schema: parent_schema.clone(),
|
||||
parent_table: parent_table.clone(),
|
||||
bound: bound.clone(),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let is_partition = partition.is_some();
|
||||
let (cols_q, keys_q, grants_q, index_q, trigger_q) = (
|
||||
sql::postgres_ddl_columns(oid, is_partition),
|
||||
sql::postgres_ddl_constraints(oid, is_partition),
|
||||
sql::postgres_ddl_grants(oid),
|
||||
sql::postgres_ddl_indexes(oid, is_partition),
|
||||
sql::postgres_ddl_triggers(oid, is_partition),
|
||||
);
|
||||
let (col_rows, key_rows, grant_rows, index_rows, trigger_rows) = futures::join!(
|
||||
catalog_rows(&pool, &cols_q),
|
||||
pool.rows(&keys_q, MAX_META_ROWS),
|
||||
pool.rows(&grants_q, MAX_META_ROWS),
|
||||
pool.rows(&index_q, MAX_META_ROWS),
|
||||
catalog_rows(&pool, &trigger_q),
|
||||
);
|
||||
let columns = col_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some(sql::DdlColumn {
|
||||
name: it.next().flatten()?,
|
||||
data_type: it.next().flatten().unwrap_or_default(),
|
||||
not_null: flag(&it.next().flatten()),
|
||||
default: it.next().flatten(),
|
||||
comment: it.next().flatten(),
|
||||
})
|
||||
let name = it.next().flatten()?;
|
||||
let data_type = it.next().flatten()?;
|
||||
let not_null = flag(&it.next().flatten());
|
||||
let expression = it.next().flatten();
|
||||
let comment = it.next().flatten().filter(|c| !c.is_empty());
|
||||
let identity = it.next().flatten();
|
||||
let generated = it.next().flatten();
|
||||
let value =
|
||||
sql::DdlColumnValue::from_catalog(identity.as_deref(), generated.as_deref(), expression);
|
||||
Some(sql::DdlColumn { name, data_type, not_null, value, comment })
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let constraints = pool
|
||||
.rows(&sql::postgres_ddl_constraints(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let constraints = key_rows?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
let mut it = r.into_iter();
|
||||
Some((it.next().flatten()?, it.next().flatten()?))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
|
||||
let grants = pool
|
||||
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
|
||||
.await?
|
||||
let indexes =
|
||||
index_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
|
||||
let grants = grant_rows?
|
||||
.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))
|
||||
.collect::<Vec<_>>();
|
||||
let triggers =
|
||||
trigger_rows?.into_iter().filter_map(|r| r.into_iter().next().flatten()).collect::<Vec<_>>();
|
||||
let options = sql::DdlTableOptions {
|
||||
unlogged: persistence.as_deref() == Some("u"),
|
||||
partition_key: partition_key.clone(),
|
||||
partition,
|
||||
};
|
||||
let extras = sql::DdlExtras { comment: comment.clone(), owner: owner.clone(), grants, triggers };
|
||||
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &options, &extras))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+224
-24
@@ -249,7 +249,7 @@ pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<S
|
||||
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
|
||||
am.amname, array_to_string(array_cat(c.reloptions, \
|
||||
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
|
||||
pg_get_partkeydef(c.oid), c.relpersistence \
|
||||
pg_get_partkeydef(c.oid), c.relpersistence, obj_description(c.oid, 'pg_class') \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
|
||||
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
|
||||
@@ -697,40 +697,70 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
|
||||
/// Rows: `oid, relkind, owner, comment, persistence, partition key, parent schema, parent name, bound`.
|
||||
pub fn postgres_relation(schema: &str, name: &str) -> String {
|
||||
format!(
|
||||
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
|
||||
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class'), \
|
||||
c.relpersistence::text, pg_get_partkeydef(c.oid), pn.nspname, p.relname, pg_get_expr(c.relpartbound, c.oid) \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
LEFT JOIN pg_inherits i ON i.inhrelid = c.oid AND c.relispartition \
|
||||
LEFT JOIN pg_class p ON p.oid = i.inhparent LEFT JOIN pg_namespace pn ON pn.oid = p.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, comment` of relation `oid`.
|
||||
pub fn postgres_ddl_columns(oid: u32) -> String {
|
||||
/// Rows: `name, type, not null (0/1), expression, comment, identity, generated` of relation `oid`.
|
||||
/// On a partition, the not-null flag and expression describe overrides of the parent column.
|
||||
///
|
||||
/// Read from `pg_attribute` with `format_type` rather than from `information_schema.columns`:
|
||||
/// that view reports `character varying` without the length, `numeric` without the precision,
|
||||
/// `ARRAY` for every array and `USER-DEFINED` for an enum, so a script built from it would not
|
||||
/// recreate the table. It also lists only the columns the current role holds privileges on.
|
||||
pub fn postgres_ddl_columns(oid: u32, partition: bool) -> String {
|
||||
// Generated clauses add their own parentheses. Keep the original deparser style for defaults.
|
||||
let pretty = "(a.attgenerated::text = 's') IS TRUE";
|
||||
let expression = format!("pg_get_expr(d.adbin, d.adrelid, {pretty})");
|
||||
let (not_null, expression, identity, parent_join) = if partition {
|
||||
let parent_expression = format!("pg_get_expr(pd.adbin, pd.adrelid, {pretty})");
|
||||
(
|
||||
"a.attnotnull AND NOT pa.attnotnull",
|
||||
format!(
|
||||
"CASE WHEN {expression} IS DISTINCT FROM {parent_expression} THEN COALESCE({expression}, 'NULL') END"
|
||||
),
|
||||
"NULL",
|
||||
"JOIN pg_inherits i ON i.inhrelid = a.attrelid \
|
||||
JOIN pg_attribute pa ON pa.attrelid = i.inhparent AND pa.attname = a.attname AND NOT pa.attisdropped \
|
||||
LEFT JOIN pg_attrdef pd ON pd.adrelid = pa.attrelid AND pd.adnum = pa.attnum",
|
||||
)
|
||||
} else {
|
||||
("a.attnotnull", expression, "a.attidentity::text", "")
|
||||
};
|
||||
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), 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 \
|
||||
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN {not_null} THEN 1 ELSE 0 END, \
|
||||
{expression}, col_description(a.attrelid, a.attnum), {identity}, a.attgenerated::text FROM pg_attribute a \
|
||||
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum {parent_join} \
|
||||
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `name, definition` of the constraints of relation `oid` (primary key first).
|
||||
pub fn postgres_ddl_constraints(oid: u32) -> String {
|
||||
pub fn postgres_ddl_constraints(oid: u32, partition: bool) -> String {
|
||||
let local = if partition { " AND conislocal AND coninhcount = 0" } else { "" };
|
||||
format!(
|
||||
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid} \
|
||||
"SELECT conname, pg_get_constraintdef(oid, true) FROM pg_constraint WHERE conrelid = {oid}{local} \
|
||||
ORDER BY CASE contype WHEN 'p' THEN 0 WHEN 'u' THEN 1 WHEN 'c' THEN 2 WHEN 'f' THEN 3 ELSE 4 END, conname"
|
||||
)
|
||||
}
|
||||
|
||||
/// Rows: `CREATE INDEX …` of relation `oid`, except the indexes behind constraints.
|
||||
pub fn postgres_ddl_indexes(oid: u32) -> String {
|
||||
pub fn postgres_ddl_indexes(oid: u32, partition: bool) -> String {
|
||||
let local =
|
||||
if partition { " AND NOT EXISTS (SELECT 1 FROM pg_inherits WHERE inhrelid = i.indexrelid)" } else { "" };
|
||||
format!(
|
||||
"SELECT pg_get_indexdef(i.indexrelid) FROM pg_index i WHERE i.indrelid = {oid} \
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid) \
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.indexrelid AND c.conrelid = i.indrelid){local} \
|
||||
ORDER BY 1"
|
||||
)
|
||||
}
|
||||
@@ -749,9 +779,10 @@ pub fn postgres_ddl_grants(oid: u32) -> String {
|
||||
}
|
||||
|
||||
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
|
||||
pub fn postgres_ddl_triggers(oid: u32) -> String {
|
||||
pub fn postgres_ddl_triggers(oid: u32, partition: bool) -> String {
|
||||
let local = if partition { " AND tgparentid = 0" } else { "" };
|
||||
format!(
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
|
||||
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger t WHERE tgrelid = {oid} AND NOT tgisinternal{local} \
|
||||
ORDER BY tgname"
|
||||
)
|
||||
}
|
||||
@@ -840,6 +871,12 @@ pub fn postgres_legacy(sql: &str) -> Option<String> {
|
||||
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
|
||||
.replace("am.amname", "NULL")
|
||||
.replace("pg_get_partkeydef(c.oid)", "NULL")
|
||||
.replace("c.relispartition", "false")
|
||||
.replace("pg_get_expr(c.relpartbound, c.oid)", "NULL")
|
||||
// These flags entered the catalog in different releases. Keep whichever ones exist.
|
||||
.replace("a.attidentity::text", "to_jsonb(a)->>'attidentity'")
|
||||
.replace("a.attgenerated::text", "to_jsonb(a)->>'attgenerated'")
|
||||
.replace("tgparentid = 0", "COALESCE(to_jsonb(t)->>'tgparentid', '0') = '0'")
|
||||
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
|
||||
(legacy != sql).then_some(legacy)
|
||||
}
|
||||
@@ -999,10 +1036,42 @@ pub struct DdlColumn {
|
||||
pub name: String,
|
||||
pub data_type: String,
|
||||
pub not_null: bool,
|
||||
pub default: Option<String>,
|
||||
pub value: Option<DdlColumnValue>,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
pub enum DdlColumnValue {
|
||||
Default(String),
|
||||
IdentityByDefault,
|
||||
IdentityAlways,
|
||||
GeneratedStored(String),
|
||||
}
|
||||
|
||||
impl DdlColumnValue {
|
||||
pub fn from_catalog(identity: Option<&str>, generated: Option<&str>, expression: Option<String>) -> Option<Self> {
|
||||
match (identity, generated) {
|
||||
(Some("d"), _) => Some(Self::IdentityByDefault),
|
||||
(Some("a"), _) => Some(Self::IdentityAlways),
|
||||
(_, Some("s")) => expression.map(Self::GeneratedStored),
|
||||
(_, None | Some("")) => expression.map(Self::Default),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DdlTableOptions {
|
||||
pub unlogged: bool,
|
||||
pub partition_key: Option<String>,
|
||||
pub partition: Option<DdlPartition>,
|
||||
}
|
||||
|
||||
pub struct DdlPartition {
|
||||
pub parent_schema: String,
|
||||
pub parent_table: String,
|
||||
pub bound: String,
|
||||
}
|
||||
|
||||
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
|
||||
#[derive(Default)]
|
||||
pub struct DdlExtras {
|
||||
@@ -1021,17 +1090,30 @@ pub fn postgres_table_ddl(
|
||||
columns: &[DdlColumn],
|
||||
constraints: &[(String, String)],
|
||||
indexes: &[String],
|
||||
options: &DdlTableOptions,
|
||||
extras: &DdlExtras,
|
||||
) -> String {
|
||||
let d = DbDriver::Postgres;
|
||||
let partition = options.partition.as_ref();
|
||||
let mut items: Vec<String> = columns
|
||||
.iter()
|
||||
.filter(|c| partition.is_none() || c.not_null || c.value.is_some())
|
||||
.map(|c| {
|
||||
let mut s = format!(" {} {}", quote_ident(d, &c.name), c.data_type);
|
||||
if let Some(v) = &c.default {
|
||||
s.push_str(&format!(" default {v}"));
|
||||
let mut s = format!(" {}", quote_ident(d, &c.name));
|
||||
if partition.is_none() {
|
||||
s.push(' ');
|
||||
s.push_str(&c.data_type);
|
||||
}
|
||||
if c.not_null {
|
||||
match &c.value {
|
||||
Some(DdlColumnValue::Default(v)) => s.push_str(&format!(" default {v}")),
|
||||
Some(DdlColumnValue::IdentityByDefault) => s.push_str(" generated by default as identity"),
|
||||
Some(DdlColumnValue::IdentityAlways) => s.push_str(" generated always as identity"),
|
||||
Some(DdlColumnValue::GeneratedStored(v)) => s.push_str(&format!(" generated always as ({v}) stored")),
|
||||
None => {}
|
||||
}
|
||||
if c.not_null
|
||||
&& !matches!(c.value, Some(DdlColumnValue::IdentityByDefault | DdlColumnValue::IdentityAlways))
|
||||
{
|
||||
s.push_str(" not null");
|
||||
}
|
||||
s
|
||||
@@ -1039,7 +1121,35 @@ pub fn postgres_table_ddl(
|
||||
.collect();
|
||||
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
|
||||
let target = qualified(d, schema, table);
|
||||
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
|
||||
let persistence = if options.unlogged { "unlogged " } else { "" };
|
||||
let mut out = format!("create {persistence}table {target}");
|
||||
if let Some(partition) = partition {
|
||||
let parent = qualified(d, &partition.parent_schema, &partition.parent_table);
|
||||
out.push_str(&format!(" partition of {parent}"));
|
||||
}
|
||||
if partition.is_none() || !items.is_empty() {
|
||||
out.push_str(&format!("\n(\n{}\n)", items.join(",\n")));
|
||||
}
|
||||
if let Some(partition) = partition {
|
||||
out.push_str("\n ");
|
||||
// pg_get_expr deparses bounds as keywords and constants. Preserve quoted constants,
|
||||
// including doubled quotes, while matching the casing of the generated DDL.
|
||||
for (i, part) in partition.bound.split('\'').enumerate() {
|
||||
if i != 0 {
|
||||
out.push('\'');
|
||||
}
|
||||
if i % 2 == 0 {
|
||||
out.push_str(&part.to_ascii_lowercase());
|
||||
} else {
|
||||
out.push_str(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(key) = &options.partition_key {
|
||||
let (method, expression) = key.split_at(key.find(' ').unwrap_or(key.len()));
|
||||
out.push_str(&format!("\n partition by {}{expression}", method.to_ascii_lowercase()));
|
||||
}
|
||||
out.push_str(";\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)));
|
||||
@@ -1416,15 +1526,31 @@ mod tests {
|
||||
assert_eq!(use_schema(DbDriver::Clickhouse, "default"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_columns_reads_pg_attribute_not_information_schema() {
|
||||
// `information_schema.columns.data_type` loses what a script needs to recreate the table:
|
||||
// `character varying` without the length, `numeric` without the precision, `ARRAY` for
|
||||
// every array and `USER-DEFINED` for an enum. It also lists only the columns the current
|
||||
// role holds privileges on. The DDL must therefore read `pg_attribute` with
|
||||
// `format_type(atttypid, atttypmod)`, which is what makes `varchar(255)`, `numeric(10,2)`,
|
||||
// `text[]` and an enum name come out as written.
|
||||
let q = postgres_ddl_columns(42, false);
|
||||
assert!(q.contains("format_type(a.atttypid, a.atttypmod)"), "{q}");
|
||||
assert!(q.contains("FROM pg_attribute a"), "{q}");
|
||||
assert!(q.contains("left join pg_attrdef") || q.contains("LEFT JOIN pg_attrdef"), "{q}");
|
||||
assert!(q.contains("attrelid = 42"), "{q}");
|
||||
assert!(!q.contains("information_schema"), "{q}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl() {
|
||||
let cols = [
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
|
||||
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "name".into(),
|
||||
data_type: "character varying(40)".into(),
|
||||
not_null: false,
|
||||
default: Some("'x'::character varying".into()),
|
||||
value: Some(DdlColumnValue::Default("'x'::character varying".into())),
|
||||
comment: None,
|
||||
},
|
||||
];
|
||||
@@ -1435,21 +1561,94 @@ mod tests {
|
||||
&cols,
|
||||
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
|
||||
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
|
||||
&DdlTableOptions::default(),
|
||||
&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_renders_identity_and_stored_columns() {
|
||||
let columns = [
|
||||
("id_default", "bigint", true, "d", "", Some("ignored()")),
|
||||
("id_always", "bigint", true, "a", "", None),
|
||||
("total", "integer", true, "", "s", Some("qty * price")),
|
||||
]
|
||||
.map(|(name, data_type, not_null, identity, generated, expression)| DdlColumn {
|
||||
name: name.into(),
|
||||
data_type: data_type.into(),
|
||||
not_null,
|
||||
value: DdlColumnValue::from_catalog(Some(identity), Some(generated), expression.map(Into::into)),
|
||||
comment: None,
|
||||
});
|
||||
let ddl =
|
||||
postgres_table_ddl("public", "t", &columns, &[], &[], &DdlTableOptions::default(), &DdlExtras::default());
|
||||
assert_eq!(
|
||||
ddl,
|
||||
concat!(
|
||||
"create table \"public\".\"t\"\n(\n",
|
||||
" \"id_default\" bigint generated by default as identity,\n",
|
||||
" \"id_always\" bigint generated always as identity,\n",
|
||||
" \"total\" integer generated always as (qty * price) stored not null\n",
|
||||
");\n",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_renders_unlogged_partitioned_parent() {
|
||||
let columns =
|
||||
[DdlColumn { name: "Day".into(), data_type: "date".into(), not_null: true, value: None, comment: None }];
|
||||
let options =
|
||||
DdlTableOptions { unlogged: true, partition_key: Some("RANGE (\"Day\")".into()), partition: None };
|
||||
assert_eq!(
|
||||
postgres_table_ddl("public", "events", &columns, &[], &[], &options, &DdlExtras::default()),
|
||||
"create unlogged table \"public\".\"events\"\n(\n \"Day\" date not null\n)\n partition by range (\"Day\");\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_ddl_renders_partitions_and_preserves_bound_literals() {
|
||||
let columns = [DdlColumn {
|
||||
name: "region".into(),
|
||||
data_type: "text".into(),
|
||||
not_null: false,
|
||||
value: None,
|
||||
comment: None,
|
||||
}];
|
||||
for (bound, rendered) in [
|
||||
("FOR VALUES FROM (MINVALUE) TO ('A) TO (B')", "for values from (minvalue) to ('A) TO (B')"),
|
||||
("FOR VALUES IN ('East''s', 'SOUTH', NULL)", "for values in ('East''s', 'SOUTH', null)"),
|
||||
("FOR VALUES WITH (modulus 2, remainder 0)", "for values with (modulus 2, remainder 0)"),
|
||||
("DEFAULT", "default"),
|
||||
] {
|
||||
let options = DdlTableOptions {
|
||||
partition: Some(DdlPartition {
|
||||
parent_schema: "other".into(),
|
||||
parent_table: "Parent\"Table".into(),
|
||||
bound: bound.into(),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
postgres_table_ddl("public", "child", &columns, &[], &[], &options, &DdlExtras::default()),
|
||||
format!(
|
||||
"create table \"public\".\"child\" partition of \"other\".\"Parent\"\"Table\"\n {rendered};\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: "id".into(), data_type: "integer".into(), not_null: true, value: None, comment: None },
|
||||
DdlColumn {
|
||||
name: "note".into(),
|
||||
data_type: "text".into(),
|
||||
not_null: false,
|
||||
default: None,
|
||||
value: None,
|
||||
comment: Some("what's this".into()),
|
||||
},
|
||||
];
|
||||
@@ -1468,6 +1667,7 @@ mod tests {
|
||||
&cols,
|
||||
&[],
|
||||
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
|
||||
&DdlTableOptions::default(),
|
||||
&extras
|
||||
),
|
||||
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
|
||||
|
||||
@@ -391,9 +391,12 @@ impl Manifest {
|
||||
if !self.capabilities.reasons.is_empty() {
|
||||
self.needs_api("`capabilities.reasons`", 19)?;
|
||||
}
|
||||
let derived = self.derived_capabilities();
|
||||
for (key, text) in &self.capabilities.reasons {
|
||||
if !self.capabilities.all().any(|c| c.to_string() == *key) {
|
||||
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
|
||||
if !self.capabilities.all().chain(&derived).any(|c| c.to_string() == *key) {
|
||||
return Err(format!(
|
||||
"capabilities.reasons: {key:?} is not under `required` or `optional`, nor comes from a contribution"
|
||||
));
|
||||
}
|
||||
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
|
||||
return Err(format!(
|
||||
@@ -522,6 +525,17 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Capabilities the plugin's contributions bring without being listed under `[capabilities]`:
|
||||
/// `java.agent` from `[[contributes.javaAgents]]`, `project.read` from
|
||||
/// `[[contributes.documentIndexers]]` (the extension points in `ide-host` add them to the grant).
|
||||
pub fn derived_capabilities(&self) -> Vec<Capability> {
|
||||
[("javaAgents", Capability::JavaAgent), ("documentIndexers", Capability::ProjectRead)]
|
||||
.into_iter()
|
||||
.filter(|(point, _)| self.contributes.contains_key(*point))
|
||||
.map(|(_, cap)| cap)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The declarations of one extension point: `[[contributes.x]]` gives
|
||||
/// several, `[contributes.x]` one.
|
||||
pub fn declarations(&self, point: &str) -> Vec<toml::Value> {
|
||||
@@ -843,6 +857,17 @@ required = [\"lsp:phoxite\"]
|
||||
assert!(err(&src(&long)).contains("1 to 500 characters"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_reasons_explain_capabilities_that_contributions_bring() {
|
||||
let src = |rest: &str| format!("{}{rest}", BASE.replace("^1.2", "^1.19"));
|
||||
let reason = "[capabilities.reasons]\n\"java.agent\" = \"Captures the SQL MyBatis runs.\"\n";
|
||||
let agent = "[[contributes.javaAgents]]\npath = \"agent.jar\"\n";
|
||||
let m = Manifest::parse(&src(&format!("{reason}{agent}"))).unwrap();
|
||||
assert_eq!(m.derived_capabilities(), [Capability::JavaAgent]);
|
||||
assert_eq!(m.capabilities.reason(&Capability::JavaAgent), Some("Captures the SQL MyBatis runs."));
|
||||
assert!(err(&src(reason)).contains("nor comes from a contribution"), "no javaAgents declaration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipboard_read_capability_needs_api_1_11() {
|
||||
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
|
||||
|
||||
@@ -448,18 +448,39 @@ pub async fn format(
|
||||
options: FormatOptions,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
let project = host.project(window)?;
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let source = FormatSource {
|
||||
path: snap.path,
|
||||
language: snap.language,
|
||||
text: snap.text,
|
||||
doc: Some(doc),
|
||||
version: snap.version,
|
||||
read_only: snap.read_only,
|
||||
// A notebook cell is a document of the language servers only: `documents` holds what the
|
||||
// editor opened, so ⌥⌘L in a cell used to answer "document DocId#N is not open".
|
||||
let source = match project.documents.snapshot(doc) {
|
||||
Ok(snap) => FormatSource {
|
||||
path: snap.path,
|
||||
language: snap.language,
|
||||
text: snap.text,
|
||||
doc: Some(doc),
|
||||
version: snap.version,
|
||||
read_only: snap.read_only,
|
||||
},
|
||||
Err(e) => match project.lsp.cell_text(doc) {
|
||||
Some(cell) => FormatSource {
|
||||
path: cell_script_path(&cell.path).into(),
|
||||
language: cell.language,
|
||||
text: cell.text,
|
||||
doc: Some(doc),
|
||||
version: cell.version,
|
||||
read_only: false,
|
||||
},
|
||||
None => return Err(e),
|
||||
},
|
||||
};
|
||||
format_source(host, window, &project, source, range, options).await
|
||||
}
|
||||
|
||||
/// The file name a formatter is given for a cell's text. It only picks the language and the
|
||||
/// settings: the text arrives on stdin. The notebook's own `.ipynb` would make Ruff parse the
|
||||
/// cell as notebook JSON instead of Python.
|
||||
fn cell_script_path(notebook: &Path) -> PathBuf {
|
||||
notebook.with_extension("py")
|
||||
}
|
||||
|
||||
/// Format a separate snapshot using the file's language, settings and formatter.
|
||||
pub async fn format_text(
|
||||
host: &Host,
|
||||
@@ -1385,6 +1406,14 @@ mod tests {
|
||||
assert!(project_configured(Oxfmt, &root.join("c/src/app.ts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cell_is_formatted_as_python_rather_than_as_notebook_json() {
|
||||
// Ruff reads the extension of `--stdin-filename` to decide what the text is; `.ipynb`
|
||||
// made it expect notebook JSON and fail on the cell's source.
|
||||
assert_eq!(cell_script_path(Path::new("/p/notebooks/a.ipynb")), Path::new("/p/notebooks/a.py"));
|
||||
assert_eq!(cell_script_path(Path::new("/p/a.b.ipynb")), Path::new("/p/a.b.py"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1572,15 +1601,21 @@ mod tests {
|
||||
let text = "a\n b\nc\nd\n e\n";
|
||||
let formatted = "a\nb\nc\nd\ne\n";
|
||||
let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }];
|
||||
let started = std::time::Instant::now();
|
||||
let edits = minimal_edits(text, whole);
|
||||
assert_eq!(
|
||||
edits,
|
||||
[
|
||||
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
|
||||
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
|
||||
]
|
||||
);
|
||||
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
|
||||
if started.elapsed() < ide_text::DIFF_BUDGET {
|
||||
assert_eq!(
|
||||
edits,
|
||||
[
|
||||
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() },
|
||||
TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() },
|
||||
]
|
||||
);
|
||||
}
|
||||
assert_eq!(after(text, &edits), formatted);
|
||||
// Merged or not, the edits stay between the first and the last changed line.
|
||||
assert!(edits[0].range.start >= Pos::new(1, 0) && edits[edits.len() - 1].range.end <= Pos::new(4, 2));
|
||||
// Single-line edits are already minimal and pass through.
|
||||
let small = vec![TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }];
|
||||
assert_eq!(minimal_edits(text, small.clone()), small);
|
||||
@@ -1631,11 +1666,17 @@ mod tests {
|
||||
let text = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
|
||||
// PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection.
|
||||
let formatted = format!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
|
||||
let started = std::time::Instant::now();
|
||||
let edits = whole_file(text, &formatted);
|
||||
// Lines 3..=6 select the array, up to the start of the line after it.
|
||||
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
|
||||
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
|
||||
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
|
||||
// Past the diff budget (a loaded machine) the regions may merge, still correctly.
|
||||
if started.elapsed() < ide_text::DIFF_BUDGET {
|
||||
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
|
||||
}
|
||||
// Merged or not, the edits leave the unchanged first and last lines alone.
|
||||
assert!(aligned[0].range.start >= Pos::new(1, 0) && aligned[aligned.len() - 1].range.end <= Pos::new(6, 0));
|
||||
assert_eq!(
|
||||
after(text, &aligned),
|
||||
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n"
|
||||
|
||||
@@ -27,10 +27,12 @@ pub mod relay;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
mod swiftlint;
|
||||
pub mod trust;
|
||||
mod ts_code_style;
|
||||
mod tsc_watch;
|
||||
pub mod web_server;
|
||||
mod xcode_env;
|
||||
|
||||
pub use project::{Project, history_retention};
|
||||
|
||||
@@ -88,6 +90,8 @@ impl HostConfig {
|
||||
|
||||
pub struct Host {
|
||||
local_database_tunnels: bool,
|
||||
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
|
||||
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
|
||||
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
|
||||
pub mcp: mcp::McpService,
|
||||
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
|
||||
@@ -207,6 +211,13 @@ impl Host {
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds a version control system besides Git: projects opened afterwards look for its
|
||||
/// working copies (when trusted) and route the Changes view, status and log to them.
|
||||
pub fn with_vcs_provider(mut self, provider: Arc<dyn ide_vcs::BackendProvider>) -> Self {
|
||||
self.vcs_providers.push(provider);
|
||||
self
|
||||
}
|
||||
|
||||
/// User home directory used by agent memory discovery.
|
||||
pub fn home_dir(&self) -> Option<PathBuf> {
|
||||
self.home_dir.clone()
|
||||
@@ -235,6 +246,7 @@ impl Host {
|
||||
let host = Self {
|
||||
plugin_host: RwLock::default(),
|
||||
local_database_tunnels: false,
|
||||
vcs_providers: Vec::new(),
|
||||
mcp_executable: Arc::default(),
|
||||
mcp: Default::default(),
|
||||
diagnostics,
|
||||
@@ -463,6 +475,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.stop();
|
||||
}
|
||||
if let Some(swiftlint) = &project.swiftlint {
|
||||
swiftlint.stop();
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.stop();
|
||||
}
|
||||
@@ -546,6 +561,8 @@ impl Host {
|
||||
if let Some(retired) = retired {
|
||||
let _ = retired.join();
|
||||
}
|
||||
// The project's buffers, index and caches are dropped: hand their pages back.
|
||||
ide_core::memory::release_free_pages_soon();
|
||||
})
|
||||
}
|
||||
|
||||
@@ -703,6 +720,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.stop();
|
||||
}
|
||||
if let Some(swiftlint) = &project.swiftlint {
|
||||
swiftlint.stop();
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.stop();
|
||||
}
|
||||
|
||||
@@ -172,15 +172,15 @@ impl Policy {
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve(&self, path: &Path) -> Option<PathBuf> {
|
||||
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path)
|
||||
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
policy::resolve(self.mode, &self.listed, &self.decisions, &self.recents, self.home.as_deref(), path, within)
|
||||
}
|
||||
}
|
||||
|
||||
/// The root of the project that serves `path` in the background under the current
|
||||
/// settings and trust decisions. Opens nothing.
|
||||
pub(crate) fn serving_root(host: &Host, path: &Path) -> Option<PathBuf> {
|
||||
Policy::current(host)?.resolve(path)
|
||||
/// settings and trust decisions; with `within`, only a root strictly inside it. Opens nothing.
|
||||
pub(crate) fn serving_root(host: &Host, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
Policy::current(host)?.resolve(path, within)
|
||||
}
|
||||
|
||||
/// How long a project may stay idle; `None` when `minutes` is 0 (never unloaded).
|
||||
@@ -283,7 +283,7 @@ impl BackgroundProjects {
|
||||
state.opening = Some(root.to_path_buf());
|
||||
Opening(self)
|
||||
};
|
||||
if serving_root(host, root).as_deref() != Some(root) {
|
||||
if serving_root(host, root, None).as_deref() != Some(root) {
|
||||
return Err(IdeError::unavailable(format!("{} is not served in the background", root.display())));
|
||||
}
|
||||
let limit = project_limit(host.global_settings.effective().mcp_server.background_project_limit);
|
||||
@@ -463,7 +463,7 @@ impl Host {
|
||||
}
|
||||
let policy = Policy::current(self);
|
||||
for root in roots {
|
||||
if policy.as_ref().and_then(|policy| policy.resolve(&root)).as_deref() != Some(&root) {
|
||||
if policy.as_ref().and_then(|policy| policy.resolve(&root, None)).as_deref() != Some(&root) {
|
||||
self.mcp_background.detach(self, &root, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,9 @@ use std::path::{Path, PathBuf};
|
||||
/// folders containing it and, in `Trusted` mode, of the trusted projects, the trusted recent
|
||||
/// projects and the nearest trusted folder with a project marker. `None` when the mode is
|
||||
/// `Off`, when `path` is relative or missing, and when no folder qualifies. Listed and
|
||||
/// recent folders that are gone or not absolute paths are skipped.
|
||||
/// recent folders that are gone or not absolute paths are skipped. With `within` (the root
|
||||
/// of the open project containing `path`) only folders strictly inside it count, and the
|
||||
/// others aren't looked up on disk.
|
||||
pub(crate) fn resolve(
|
||||
mode: McpBackgroundProjects,
|
||||
listed: &[PathBuf],
|
||||
@@ -18,6 +20,7 @@ pub(crate) fn resolve(
|
||||
recents: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
path: &Path,
|
||||
within: Option<&Path>,
|
||||
) -> Option<PathBuf> {
|
||||
let by_trust = match mode {
|
||||
McpBackgroundProjects::Off => return None,
|
||||
@@ -28,23 +31,37 @@ pub(crate) fn resolve(
|
||||
return None;
|
||||
}
|
||||
let path = dunce::canonicalize(path).ok()?;
|
||||
let within = within.map(|root| (root, dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf())));
|
||||
let open = within.as_ref().map(|(_, root)| root.as_path());
|
||||
// Only folders strictly inside `within` count. An entry is checked by its text before it
|
||||
// is canonicalized, so folders elsewhere (a network mount among them) aren't touched; one
|
||||
// that reaches inside through a link from elsewhere is left out.
|
||||
let inside = |entry: &Path, canonical: bool| {
|
||||
within.as_ref().is_none_or(|(raw, root)| {
|
||||
(entry.starts_with(root) && entry != root) || (!canonical && entry.starts_with(raw) && entry != *raw)
|
||||
})
|
||||
};
|
||||
// A relative entry would be read against the working directory, which says nothing
|
||||
// about the user's folders (`/` for an app started from the Finder).
|
||||
let existing = |entry: &PathBuf| entry.is_absolute().then(|| dunce::canonicalize(entry).ok()).flatten();
|
||||
let existing = |entry: &PathBuf| {
|
||||
(entry.is_absolute() && inside(entry, false)).then(|| dunce::canonicalize(entry).ok()).flatten()
|
||||
};
|
||||
// A listed folder serves its subtree whether or not it is trusted: it opens restricted then.
|
||||
let mut candidates: Vec<PathBuf> = listed.iter().filter_map(existing).collect();
|
||||
if by_trust {
|
||||
candidates.extend(decisions.projects.iter().filter(|p| trusted_here(decisions, p)).cloned());
|
||||
let projects = decisions.projects.iter().filter(|p| inside(p, true));
|
||||
candidates.extend(projects.filter(|p| trusted_here(decisions, p)).cloned());
|
||||
// Remote projects are recorded as locations (`ssh://…`), not as folders of this machine.
|
||||
let local = recents.iter().filter(|p| !p.to_string_lossy().contains("://"));
|
||||
candidates.extend(local.filter_map(existing).filter(|p| trusted_here(decisions, p)));
|
||||
let home = home.map(|h| dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf()));
|
||||
// A trusted location and the home folder hold projects; neither is one.
|
||||
candidates
|
||||
.extend(marker_root(&path).filter(|a| {
|
||||
.extend(marker_root(&path, open).filter(|a| {
|
||||
trusted_here(decisions, a) && !decisions.locations.contains(a) && home.as_ref() != Some(a)
|
||||
}));
|
||||
}
|
||||
candidates.retain(|candidate| inside(candidate, true));
|
||||
innermost(&candidates, &path).cloned()
|
||||
}
|
||||
|
||||
@@ -64,9 +81,10 @@ fn trusted_here(decisions: &TrustDecisions, root: &Path) -> bool {
|
||||
|
||||
/// The first ancestor of `path`, itself included, that looks like a project: it holds an
|
||||
/// `.openidea` folder, or a `.git` or `.jj` entry (a linked worktree's `.git` is a file).
|
||||
fn marker_root(path: &Path) -> Option<PathBuf> {
|
||||
/// The search stops short of `within`.
|
||||
fn marker_root(path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
let marked = |dir: &&Path| dir.join(".openidea").is_dir() || dir.join(".git").exists() || dir.join(".jj").exists();
|
||||
path.ancestors().find(marked).map(Path::to_path_buf)
|
||||
path.ancestors().take_while(|dir| Some(*dir) != within).find(marked).map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -159,7 +177,35 @@ mod tests {
|
||||
restricted: paths(restricted),
|
||||
};
|
||||
let home = base.join("home");
|
||||
let found = resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path));
|
||||
let found =
|
||||
resolve(*mode, &paths(listed), &decisions, &paths(recents), Some(&home), &base.join(path), None);
|
||||
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_an_open_project_only_a_folder_below_its_root_serves_a_path() {
|
||||
let (_tmp, base) = tree();
|
||||
let at = |folders: &[&str]| folders.iter().map(|folder| base.join(folder)).collect::<Vec<_>>();
|
||||
let trusted = |projects: &[&str], locations: &[&str]| TrustDecisions {
|
||||
projects: at(projects),
|
||||
locations: at(locations),
|
||||
..Default::default()
|
||||
};
|
||||
let within = base.join("code/app");
|
||||
let (none, root, location) = (trusted(&[], &[]), trusted(&["code/app"], &[]), trusted(&[], &["code"]));
|
||||
let (src, nested) = ("code/app/src", "code/app/.wt/feature");
|
||||
let below = trusted(&[nested], &[]);
|
||||
let nested_src = "code/app/.wt/feature/src";
|
||||
for (what, mode, listed, decisions, path, expected) in [
|
||||
("a listed folder below the root", Listed, &[src][..], &none, src, Some(src)),
|
||||
("the listed root and a listed folder around it", Listed, &["code", "code/app"], &none, src, None),
|
||||
("the trusted root", Trusted, &[], &root, src, None),
|
||||
("the root's own marker", Trusted, &[], &location, src, None),
|
||||
("a repository below the root", Trusted, &[], &location, nested_src, Some(nested)),
|
||||
("a trusted project below the root", Trusted, &[], &below, nested_src, Some(nested)),
|
||||
] {
|
||||
let found = resolve(mode, &at(listed), decisions, &[], None, &base.join(path), Some(&within));
|
||||
assert_eq!(found, expected.map(|root| base.join(root)), "{what}");
|
||||
}
|
||||
}
|
||||
@@ -170,7 +216,7 @@ mod tests {
|
||||
let listed = [base.join("code/app"), PathBuf::from("code/app"), PathBuf::from(".")];
|
||||
let none = TrustDecisions::default();
|
||||
for path in ["code/app/src", ".", "src"] {
|
||||
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path)), None, "{path}");
|
||||
assert_eq!(resolve(Listed, &listed, &none, &[], None, Path::new(path), None), None, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +234,7 @@ mod tests {
|
||||
("the same folder listed by its full path", Listed, absolute, &none, &[][..], Some(&here)),
|
||||
("the same folder recent by its full path", Trusted, &[][..], &around, absolute, Some(&here)),
|
||||
] {
|
||||
assert_eq!(resolve(mode, listed, decisions, recents, None, &here).as_ref(), expected, "{what}");
|
||||
assert_eq!(resolve(mode, listed, decisions, recents, None, &here, None).as_ref(), expected, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,13 +246,13 @@ mod tests {
|
||||
let none = TrustDecisions::default();
|
||||
// Listed by the link, asked for by the real path, and the other way round (`/tmp` and `/private/tmp`).
|
||||
for (listed, path) in [("link/app", "code/app/src"), ("code/app", "link/app/src"), ("link/app", "link/app")] {
|
||||
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path));
|
||||
let found = resolve(Listed, &[base.join(listed)], &none, &[], None, &base.join(path), None);
|
||||
assert_eq!(found, Some(base.join("code/app")), "{listed} for {path}");
|
||||
}
|
||||
let trusted = TrustDecisions { locations: vec![base.join("code")], ..Default::default() };
|
||||
let recent = [base.join("link/plain")];
|
||||
assert_eq!(
|
||||
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src")),
|
||||
resolve(Trusted, &[], &trusted, &recent, None, &base.join("link/plain/src"), None),
|
||||
Some(base.join("code/plain"))
|
||||
);
|
||||
}
|
||||
@@ -219,10 +265,10 @@ mod tests {
|
||||
std::fs::create_dir_all(base.join("ssh:/box/app/src")).unwrap();
|
||||
let recent = [PathBuf::from(format!("{}/ssh://box/app", base.display()))];
|
||||
let trusted = TrustDecisions { locations: vec![base.clone()], ..Default::default() };
|
||||
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src")), None);
|
||||
assert_eq!(resolve(Trusted, &[], &trusted, &recent, None, &base.join("ssh:/box/app/src"), None), None);
|
||||
let local = [base.join("ssh:/box/app")];
|
||||
assert_eq!(
|
||||
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src")),
|
||||
resolve(Trusted, &[], &trusted, &local, None, &base.join("ssh:/box/app/src"), None),
|
||||
Some(base.join("ssh:/box/app"))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -708,7 +708,7 @@ async fn a_host_that_serves_none_refuses_every_folder_whatever_the_settings_say(
|
||||
let root = f.root("inventory");
|
||||
f.host.mcp_background.serve_none();
|
||||
let registry = crate::mcp::Registry::new(f.host.clone());
|
||||
assert_eq!(registry.resolve(&root.join("parts")), None);
|
||||
assert_eq!(registry.resolve(&root.join("parts"), None), None);
|
||||
assert_eq!(f.refused("inventory"), format!("{} is not served in the background", root.display()));
|
||||
assert!(f.loaded().is_empty());
|
||||
assert!(f.host.projects().is_empty());
|
||||
@@ -726,11 +726,11 @@ async fn a_call_that_arrives_after_the_server_was_turned_off_opens_nothing() {
|
||||
assert!(f.loaded().is_empty());
|
||||
assert!(f.host.projects().is_empty());
|
||||
let registry = crate::mcp::Registry::new(f.host.clone());
|
||||
assert_eq!(registry.resolve(&root.join("parts")), None, "no folder is served with the server off");
|
||||
assert_eq!(registry.resolve(&root.join("parts"), None), None, "no folder is served with the server off");
|
||||
assert!(registry.tools(&root).is_err());
|
||||
|
||||
f.set("enabled", json!(true));
|
||||
assert_eq!(registry.resolve(&root.join("parts")), Some(root));
|
||||
assert_eq!(registry.resolve(&root.join("parts"), None), Some(root));
|
||||
f.open("inventory");
|
||||
assert_eq!(f.loaded(), ["inventory"]);
|
||||
}
|
||||
|
||||
@@ -213,6 +213,7 @@ In OpenIDEA the user is asked first, then the IDE's own Debug action starts the
|
||||
before-launch tasks and Debug tool window as when you press Debug. This needs a project window (it does not work \
|
||||
for a background project without one). Program output goes to the Debug console, not into this tool's result.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let target =
|
||||
execution_target(call.opt_str("configurationName")?, call.opt_str("filePath")?, call.opt_i64("line")?)?;
|
||||
let envs = call.args.get("envs").filter(|v| !v.is_null()).map(|_| call.str_map("envs")).transpose()?;
|
||||
@@ -490,6 +491,7 @@ optional `message` from the last verification. Function and data breakpoints are
|
||||
`function:` and `data:`. Call this before RESUME to check that an enabled breakpoint will be hit. Breakpoints set \
|
||||
with `xdebug_set_breakpoint` are the same ones the editor shows and persists.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
// The editor mirrors every change to the backend synchronously on request, so
|
||||
// flushing its pending debounced syncs makes this the same list the editor shows.
|
||||
call.ask(McpUiRequest::FlushBreakpoints).await?;
|
||||
@@ -589,6 +591,7 @@ suspends the thread and does not implement one-shot or stack-logging breakpoints
|
||||
`lineText` so the placement can be checked before RESUME. The breakpoint is shown in the editor's gutter and \
|
||||
persists with the project; this needs a project window.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let _guard = BREAKPOINT_EDITS.lock().await;
|
||||
let files = editor_breakpoints(&call);
|
||||
let (path, line0, relocate_from) = if let Some(id) = call.opt_str("breakpointId")? {
|
||||
@@ -680,6 +683,7 @@ that file are removed; with neither (the default `owner=agent`), all line breakp
|
||||
Removal of a missing breakpoint is not an error: `removed` says whether anything was removed. `owner` is accepted \
|
||||
for compatibility. Function and data breakpoints are managed in the IDE; this needs a project window.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let _guard = BREAKPOINT_EDITS.lock().await;
|
||||
let owner = call.opt_str("owner")?;
|
||||
if owner.as_deref().is_some_and(|o| o != "agent" && o != "user") {
|
||||
|
||||
@@ -429,6 +429,7 @@ Requires a filePath parameter containing the path to the file to open.
|
||||
The file path can be absolute or relative to the project root.
|
||||
Optionally puts the caret at a 1-based line and column.",
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let raw = call.str("filePath")?;
|
||||
// Opening shows the file to the user: outside the project the user agrees first.
|
||||
let path = call.resolve_readable(&raw).await?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::page::{OFFSET, Page};
|
||||
use super::search::{PathScope, paths_param};
|
||||
use super::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use ide_core::{Diagnostic, IdeError, IdeResult, Severity};
|
||||
use ide_core::{Diagnostic, IdeResult, Severity};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// Problems `get_project_problems` lists by default.
|
||||
@@ -51,28 +51,16 @@ Lines and UTF-16 columns are 1-based.",
|
||||
]
|
||||
}
|
||||
|
||||
/// Editors and the Problems view are reported by a window: a project served in the
|
||||
/// background has none, and says so instead of answering as if nothing were open.
|
||||
fn reported_by_a_window(call: &Call) -> IdeResult<()> {
|
||||
if !super::BackgroundProjects::is_key(call.window()) {
|
||||
return Ok(());
|
||||
}
|
||||
let (tool, root) = (&call.tool, call.root().display());
|
||||
Err(IdeError::unavailable(format!(
|
||||
"{tool} needs the project open in a window: {root} is served in the background."
|
||||
)))
|
||||
}
|
||||
|
||||
/// [`reported_by_a_window`] for the Problems view, which `check_files` stands in for.
|
||||
/// [`Call::needs_window`] for the Problems view, which `check_files` stands in for.
|
||||
fn problems_reported_by_a_window(call: &Call) -> IdeResult<()> {
|
||||
reported_by_a_window(call).map_err(|mut error| {
|
||||
call.needs_window().map_err(|mut error| {
|
||||
error.message.push_str(" Use check_files for diagnostics.");
|
||||
error
|
||||
})
|
||||
}
|
||||
|
||||
async fn open_editors(call: Call) -> IdeResult<Output> {
|
||||
reported_by_a_window(&call)?;
|
||||
call.needs_window()?;
|
||||
let paths = PathScope::of(&call)?;
|
||||
let windows = call.host.mcp_windows(call.root());
|
||||
let open = call.host.mcp_reports.editors(&windows);
|
||||
@@ -84,7 +72,7 @@ async fn open_editors(call: Call) -> IdeResult<Output> {
|
||||
}
|
||||
|
||||
async fn current_file(call: Call) -> IdeResult<Output> {
|
||||
reported_by_a_window(&call)?;
|
||||
call.needs_window()?;
|
||||
let editor = call.host.mcp_reports.focused(call.window());
|
||||
Output::json(match editor {
|
||||
None => json!({}),
|
||||
|
||||
@@ -18,7 +18,7 @@ pub mod service;
|
||||
mod symbols;
|
||||
mod tool;
|
||||
|
||||
pub(crate) use tool::trusted_attachments;
|
||||
pub(crate) use tool::{PROJECT_PATH, trusted_attachments};
|
||||
mod util;
|
||||
|
||||
use crate::Host;
|
||||
@@ -28,6 +28,7 @@ pub use reports::{
|
||||
FileProblems, FocusedEditor, Reports, mcp_report_problems, mcp_set_focused_editor, mcp_set_open_editors,
|
||||
};
|
||||
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM};
|
||||
use serde_json::json;
|
||||
pub use service::{McpServerStatus, McpService};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
@@ -55,7 +56,8 @@ fn tools() -> Vec<tool::Tool> {
|
||||
tools
|
||||
}
|
||||
|
||||
// Checked both when listing and calling, so a later trust change takes effect immediately.
|
||||
// What a project lists. A call checks the trust it has then (`call_with_client`), so a later
|
||||
// trust change takes effect immediately.
|
||||
fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
|
||||
trusted || tool.read_only
|
||||
}
|
||||
@@ -63,11 +65,36 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
|
||||
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
|
||||
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
|
||||
if let Some(plugins) = host.plugin_host() {
|
||||
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool));
|
||||
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(tool)));
|
||||
}
|
||||
all.into_iter().filter(|t| allowed(t, trusted)).collect()
|
||||
}
|
||||
|
||||
/// A plugin's tool as clients see it: it takes `projectPath` like every other tool, which the
|
||||
/// plugin gets only if its own schema takes it (`PluginHost::call_mcp_tool`).
|
||||
fn with_project_path(mut tool: ide_mcp::Tool) -> ide_mcp::Tool {
|
||||
if let Some(schema) = tool.input_schema.as_object_mut()
|
||||
&& let Some(properties) = schema.entry("properties").or_insert_with(|| json!({})).as_object_mut()
|
||||
{
|
||||
properties.entry(tool::PROJECT_PATH).or_insert_with(tool::project_path);
|
||||
}
|
||||
tool
|
||||
}
|
||||
|
||||
/// The tool a call runs: a plugin's or a built-in one.
|
||||
enum Found {
|
||||
Plugin { plugins: Arc<crate::plugins::PluginHost>, plugin: String, tool: String, metadata: ide_mcp::Tool },
|
||||
Builtin(tool::Tool),
|
||||
}
|
||||
impl Found {
|
||||
fn writes(&self) -> bool {
|
||||
match self {
|
||||
Self::Plugin { metadata, .. } => !metadata.read_only,
|
||||
Self::Builtin(tool) => !tool.metadata.read_only,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists the built-in IDE and plugin-contributed MCP tools visible to `window`.
|
||||
pub(crate) fn list_tools_for_window(host: &Host, window: &str) -> Vec<ide_mcp::Tool> {
|
||||
match host.project(window).ok().filter(|p| !p.light) {
|
||||
@@ -110,6 +137,16 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool `name` for `root`: a plugin's first. Loads nothing.
|
||||
fn find(&self, root: &Path, name: &str) -> Option<Found> {
|
||||
if let Some(plugins) = self.0.plugin_host()
|
||||
&& let Some((plugin, tool, metadata)) = plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name)
|
||||
{
|
||||
return Some(Found::Plugin { plugins, plugin, tool, metadata });
|
||||
}
|
||||
tools().into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
|
||||
}
|
||||
|
||||
/// Whether the tools listed for `root` include those that write and run. Opens nothing:
|
||||
/// a background project that is not loaded is judged as its open will judge it.
|
||||
fn lists_as_trusted(&self, root: &Path) -> Result<bool, String> {
|
||||
@@ -119,7 +156,7 @@ impl Registry {
|
||||
if let Some(project) = self.0.mcp_background.project(&self.0, root) {
|
||||
return Ok(project.is_trusted());
|
||||
}
|
||||
if background::serving_root(&self.0, root).as_deref() == Some(root) {
|
||||
if background::serving_root(&self.0, root, None).as_deref() == Some(root) {
|
||||
return Ok(self.0.trust.window_trusted(root).unwrap_or(false));
|
||||
}
|
||||
Err("project is no longer open".into())
|
||||
@@ -138,13 +175,21 @@ impl ToolRegistry for Registry {
|
||||
let attached: Vec<_> = open.iter().flat_map(|p| tool::attached_projects(&p.root)).collect();
|
||||
open.into_iter().map(|p| p.root.clone()).chain(attached).chain(self.0.mcp_reports.remote_roots()).collect()
|
||||
}
|
||||
fn resolve(&self, path: &Path) -> Option<PathBuf> {
|
||||
background::serving_root(&self.0, path)
|
||||
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
// A remote window's project holds that host's folders, even where this computer has
|
||||
// folders at the same paths.
|
||||
if within.is_some_and(|root| self.0.mcp_reports.remote_roots().iter().any(|remote| remote == root)) {
|
||||
return None;
|
||||
}
|
||||
background::serving_root(&self.0, path, within)
|
||||
}
|
||||
fn tools(&self, root: &Path) -> Result<Vec<ide_mcp::Tool>, String> {
|
||||
let trusted = self.lists_as_trusted(root)?;
|
||||
Ok(tools_for(&self.0, root, trusted))
|
||||
}
|
||||
fn tools_without_project(&self) -> Vec<ide_mcp::Tool> {
|
||||
tools_for(&self.0, Path::new(""), true)
|
||||
}
|
||||
fn call(
|
||||
&self,
|
||||
root: &Path,
|
||||
@@ -162,19 +207,27 @@ impl ToolRegistry for Registry {
|
||||
cancel: CancellationToken,
|
||||
client: &str,
|
||||
) -> Result<String, ToolCallError> {
|
||||
let unknown = || ToolCallError::UnknownTool(format!("unknown tool: {name}"));
|
||||
// Before the project loads, so the refusal neither loads a background project nor
|
||||
// unloads an idle one at the limit to make room.
|
||||
if self.find(root, name).ok_or_else(unknown)?.writes() && self.lists_as_trusted(root) == Ok(false) {
|
||||
return Err(ToolCallError::Failed(crate::project::RESTRICTED_MODE.into()));
|
||||
}
|
||||
// The guard lives until the call ends, whichever way it leaves: neither the idle
|
||||
// sweep nor the limit unloads a background project a call runs in.
|
||||
let (window, project, _activity) = self.target(root).map_err(ToolCallError::Failed)?;
|
||||
if let Some(plugins) = self.0.plugin_host()
|
||||
&& let Some((plugin, tool, metadata)) =
|
||||
plugins.mcp_tools(root).into_iter().find(|(_, _, t)| t.name == name && allowed(t, project.is_trusted()))
|
||||
{
|
||||
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
|
||||
// Found again: a plugin can change while a background project opens, and the call
|
||||
// runs the tool as it is now.
|
||||
let found = self.find(root, name).ok_or_else(unknown)?;
|
||||
if found.writes() {
|
||||
project.require_trust().map_err(|e| ToolCallError::Failed(e.message))?;
|
||||
}
|
||||
let tool = tools()
|
||||
.into_iter()
|
||||
.find(|t| t.metadata.name == name && allowed(&t.metadata, project.is_trusted()))
|
||||
.ok_or_else(|| ToolCallError::UnknownTool(format!("unknown tool: {name}")))?;
|
||||
let tool = match found {
|
||||
Found::Plugin { plugins, plugin, tool, metadata } => {
|
||||
return self.call_plugin(window, project, plugins, plugin, tool, metadata, arguments, cancel, client);
|
||||
}
|
||||
Found::Builtin(tool) => tool,
|
||||
};
|
||||
let args = serde_json::from_str(arguments).map_err(|e| ToolCallError::Failed(e.to_string()))?;
|
||||
let call = tool::Call {
|
||||
host: self.0.clone(),
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
//! Window-bound requests; missing windows, cancellation and timeout all fail closed.
|
||||
//! Window-bound requests; missing windows, cancellation and timeout all fail closed. A
|
||||
//! confirmation for a project served in the background shows in another project's window
|
||||
//! and moves to the next one when that window stops answering.
|
||||
use super::tool::Call;
|
||||
use crate::Host;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, event::McpUiRequest};
|
||||
use parking_lot::Mutex;
|
||||
use parking_lot::{Mutex, MutexGuard};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use tokio::sync::oneshot;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{Notify, oneshot};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Requests(Mutex<State>);
|
||||
@@ -13,10 +17,24 @@ struct State {
|
||||
pending: HashMap<u32, Pending>,
|
||||
}
|
||||
struct Pending {
|
||||
window: String,
|
||||
/// The window key of the call that asked.
|
||||
owner: String,
|
||||
/// The window that shows the request and may answer it.
|
||||
shown_in: String,
|
||||
/// Signalled when `shown_in` stops answering while `owner` still waits.
|
||||
moved: Arc<Notify>,
|
||||
answer: oneshot::Sender<Result<bool, String>>,
|
||||
value: oneshot::Sender<Option<String>>,
|
||||
}
|
||||
impl State {
|
||||
/// `window` answers no more requests: the ones it shows for another window move on.
|
||||
fn stop_showing(&mut self, window: &str) {
|
||||
self.ready.remove(window);
|
||||
for pending in self.pending.values().filter(|p| p.shown_in == window && p.owner != window) {
|
||||
pending.moved.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Requests {
|
||||
pub fn set_ready(&self, window: &str, ready: bool) {
|
||||
if ready {
|
||||
@@ -25,10 +43,18 @@ impl Requests {
|
||||
self.forget_window(window);
|
||||
}
|
||||
}
|
||||
/// `window` closed: its own requests fail, and the ones it shows for a project served in
|
||||
/// the background move to another window.
|
||||
pub fn forget_window(&self, window: &str) {
|
||||
let mut state = self.0.lock();
|
||||
state.ready.remove(window);
|
||||
state.pending.retain(|_, p| p.window != window);
|
||||
state.pending.retain(|_, p| p.owner != window);
|
||||
state.stop_showing(window);
|
||||
}
|
||||
/// `window` lost its project's trust: the requests it shows for a project served in the
|
||||
/// background move to another window; its own stay there and fail the trust check after
|
||||
/// the answer.
|
||||
pub(crate) fn withdraw(&self, window: &str) {
|
||||
self.0.lock().stop_showing(window);
|
||||
}
|
||||
pub fn answer(&self, window: &str, id: u32, allow: bool, error: Option<String>) -> IdeResult<()> {
|
||||
self.answer_with(window, id, allow, error, None)
|
||||
@@ -43,10 +69,10 @@ impl Requests {
|
||||
value: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
let mut state = self.0.lock();
|
||||
if !state.pending.get(&id).is_some_and(|p| p.window == window) {
|
||||
if !state.pending.get(&id).is_some_and(|p| p.shown_in == window) {
|
||||
return Err(IdeError::invalid("MCP request expired or belongs to another window"));
|
||||
}
|
||||
let pending = state.pending.remove(&id).unwrap();
|
||||
let pending = state.pending.remove(&id).expect("the request was just found");
|
||||
let _ = pending.value.send(value);
|
||||
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
|
||||
Ok(())
|
||||
@@ -64,30 +90,96 @@ impl Requests {
|
||||
self.ask_inner(call, request).await
|
||||
}
|
||||
|
||||
/// The window to show a background project's request in: the most recently focused ready
|
||||
/// window whose project is trusted. Returns it with the state locked while it is still
|
||||
/// ready, or `None` when there is none.
|
||||
fn pick(&self, host: &Host) -> Option<(MutexGuard<'_, State>, String)> {
|
||||
loop {
|
||||
// Projects and focus are read without the lock, which is never held with theirs.
|
||||
let mut windows: Vec<String> = self.0.lock().ready.iter().cloned().collect();
|
||||
windows.retain(|w| host.project(w).is_ok_and(|p| p.is_trusted()));
|
||||
host.mcp_reports.most_recently_focused_first(&mut windows);
|
||||
let target = windows.into_iter().next()?;
|
||||
let state = self.0.lock();
|
||||
if state.ready.contains(&target) {
|
||||
return Some((state, target));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn ask_inner(&self, call: &Call, request: McpUiRequest) -> IdeResult<Option<String>> {
|
||||
let id = super::tool::request_id().0;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let (tx, mut rx) = oneshot::channel();
|
||||
let (value_tx, value_rx) = oneshot::channel();
|
||||
{
|
||||
let mut state = self.0.lock();
|
||||
if !state.ready.contains(call.window()) {
|
||||
return Err(IdeError::unavailable("MCP request denied: no project window is available"));
|
||||
}
|
||||
state.pending.insert(id, Pending { window: call.window.clone(), answer: tx, value: value_tx });
|
||||
let moved = Arc::new(Notify::new());
|
||||
let background = matches!(request, McpUiRequest::Confirm { background: true, .. });
|
||||
let shown_in = {
|
||||
let own = self.0.lock();
|
||||
let (mut state, shown_in) = if own.ready.contains(call.window()) {
|
||||
(own, call.window.clone())
|
||||
} else {
|
||||
drop(own);
|
||||
background
|
||||
.then(|| self.pick(&call.host))
|
||||
.flatten()
|
||||
.ok_or_else(|| IdeError::unavailable("MCP request denied: no project window is available"))?
|
||||
};
|
||||
let pending = Pending {
|
||||
owner: call.window.clone(),
|
||||
shown_in: shown_in.clone(),
|
||||
moved: moved.clone(),
|
||||
answer: tx,
|
||||
value: value_tx,
|
||||
};
|
||||
state.pending.insert(id, pending);
|
||||
shown_in
|
||||
};
|
||||
struct Close<'a> {
|
||||
requests: &'a Requests,
|
||||
call: &'a Call,
|
||||
id: u32,
|
||||
shown_in: String,
|
||||
}
|
||||
struct Close<'a>(&'a Requests, &'a Call, u32);
|
||||
impl Drop for Close<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.0.lock().pending.remove(&self.2);
|
||||
self.1.project.sink.emit(IdeEvent::McpRequestClosed { id: self.2 });
|
||||
self.requests.0.lock().pending.remove(&self.id);
|
||||
self.call.host.window_sink(&self.shown_in).emit(IdeEvent::McpRequestClosed { id: self.id });
|
||||
}
|
||||
}
|
||||
let _close = Close(self, call, id);
|
||||
call.project.sink.emit(IdeEvent::McpRequest { id, request });
|
||||
let result = tokio::select! {
|
||||
result = rx => result.map_err(|_| IdeError::unavailable("MCP request denied: project window closed"))?,
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(180)) => return Err(IdeError::unavailable("MCP request denied: confirmation timed out")),
|
||||
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
let mut close = Close { requests: self, call, id, shown_in };
|
||||
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
|
||||
// One deadline however often the request moves.
|
||||
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(180);
|
||||
let result = loop {
|
||||
// An answer that arrives together with a move or a close still counts.
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut rx => break result.map_err(|_| IdeError::unavailable("MCP request denied: project window closed"))?,
|
||||
_ = call.cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
// A project unloading after its window was forgotten must not reach another window.
|
||||
_ = call.project.closed.cancelled() => return Err(IdeError::unavailable("MCP request denied: project closed")),
|
||||
_ = tokio::time::sleep_until(deadline) => return Err(IdeError::unavailable("MCP request denied: confirmation timed out")),
|
||||
_ = moved.notified() => {
|
||||
if self.window_ready(&close.shown_in) {
|
||||
// The window answers again after a reload, whose new page has not seen the
|
||||
// request: show it there again (the page drops a repeated id).
|
||||
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
|
||||
continue;
|
||||
}
|
||||
let target = {
|
||||
let (mut state, target) = self
|
||||
.pick(&call.host)
|
||||
.ok_or_else(|| IdeError::unavailable("MCP request denied: project window closed"))?;
|
||||
// Answered or dropped meanwhile: `rx` says which.
|
||||
let Some(pending) = state.pending.get_mut(&id) else { continue };
|
||||
pending.shown_in = target.clone();
|
||||
target
|
||||
};
|
||||
let left = std::mem::replace(&mut close.shown_in, target);
|
||||
call.host.window_sink(&left).emit(IdeEvent::McpRequestClosed { id });
|
||||
call.host.window_sink(&close.shown_in).emit(IdeEvent::McpRequest { id, request: request.clone() });
|
||||
}
|
||||
}
|
||||
};
|
||||
match result {
|
||||
Ok(true) => Ok(value_rx.await.unwrap_or(None)),
|
||||
@@ -96,3 +188,109 @@ impl Requests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{HostConfig, mcp::BackgroundProjects};
|
||||
use futures::FutureExt;
|
||||
use ide_core::{CancellationToken, IdeEvent};
|
||||
use std::path::PathBuf;
|
||||
|
||||
type Events = Arc<Mutex<Vec<(String, IdeEvent)>>>;
|
||||
|
||||
/// A trusted project open in the ready window `main`, and the folder `inventory` loaded in the
|
||||
/// background next to it.
|
||||
struct Fixture {
|
||||
host: Arc<Host>,
|
||||
inventory: PathBuf,
|
||||
events: Events,
|
||||
_temp: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
async fn new() -> Self {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let (root, inventory) = (base.join("project"), base.join("inventory"));
|
||||
for dir in [&root, &inventory] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
let events = Events::default();
|
||||
let sink = events.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
local_data_dir: base.join("local"),
|
||||
sink_for: Box::new(move |window| {
|
||||
let (window, events) = (window.to_owned(), sink.clone());
|
||||
Arc::new(move |e| events.lock().push((window.clone(), e)))
|
||||
}),
|
||||
..HostConfig::for_test(&base)
|
||||
}));
|
||||
host.open_project("main", &root).unwrap();
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
host.mcp_requests.set_ready("main", true);
|
||||
Self { host, inventory, events, _temp: temp }
|
||||
}
|
||||
|
||||
/// A call from the background project at `inventory`.
|
||||
fn background_call(&self) -> Call {
|
||||
let window = BackgroundProjects::key(&self.inventory);
|
||||
Call {
|
||||
client: "test-client".into(),
|
||||
tool: "build_project".into(),
|
||||
host: self.host.clone(),
|
||||
project: self.host.open_project(&window, &self.inventory).unwrap(),
|
||||
window,
|
||||
args: serde_json::Value::Null,
|
||||
cancel: CancellationToken::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm(&self) -> McpUiRequest {
|
||||
McpUiRequest::Confirm {
|
||||
client: "test-client".into(),
|
||||
tool: "build_project".into(),
|
||||
subject: "build".into(),
|
||||
project: self.inventory.to_string_lossy().into_owned(),
|
||||
detail: None,
|
||||
background: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of the requests `main` was asked to show, in order.
|
||||
fn shown_in_main(&self) -> Vec<u32> {
|
||||
let events = self.events.lock();
|
||||
let asked = events.iter().filter(|(window, _)| window == "main");
|
||||
asked.filter_map(|(_, e)| if let IdeEvent::McpRequest { id, .. } = e { Some(*id) } else { None }).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_request_of_a_project_that_closed_fails_instead_of_moving() {
|
||||
let f = Fixture::new().await;
|
||||
let call = f.background_call();
|
||||
// Unloading forgets the project's key before it cancels `closed`; a request registered in
|
||||
// between belongs to nobody that will answer it.
|
||||
call.project.closed.cancel();
|
||||
let error = f.host.mcp_requests.ask(&call, f.confirm()).now_or_never().expect("fails at once").unwrap_err();
|
||||
assert_eq!(error.message, "MCP request denied: project closed");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_reloaded_window_shows_the_request_again() {
|
||||
let f = Fixture::new().await;
|
||||
let call = f.background_call();
|
||||
let ask = f.host.mcp_requests.ask(&call, f.confirm());
|
||||
tokio::pin!(ask);
|
||||
assert!((&mut ask).now_or_never().is_none());
|
||||
let [id] = f.shown_in_main()[..] else { panic!("{:?}", f.shown_in_main()) };
|
||||
// A reload: the old page stops answering and drops the request, the new one is ready.
|
||||
f.host.mcp_requests.set_ready("main", false);
|
||||
f.host.mcp_requests.set_ready("main", true);
|
||||
assert!((&mut ask).now_or_never().is_none());
|
||||
assert_eq!(f.shown_in_main(), [id, id]);
|
||||
f.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
let error = ask.await.unwrap_err();
|
||||
assert_eq!(error.message, "MCP request denied by the user");
|
||||
}
|
||||
}
|
||||
@@ -137,6 +137,7 @@ crashed, stoppedByAgent, stoppedByUser or startFailed; `exitCode`; `crash` with
|
||||
process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
|
||||
),
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let name = tab_name(&call.str("name")?)?;
|
||||
let command = call.str("command")?;
|
||||
if command.trim().is_empty() {
|
||||
|
||||
@@ -5,6 +5,14 @@ use serde_json::{Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The argument that names the project a call is for; the server routes the call by it.
|
||||
pub(crate) const PROJECT_PATH: &str = "projectPath";
|
||||
|
||||
/// The schema of [`PROJECT_PATH`], which every tool takes.
|
||||
pub(crate) fn project_path() -> Value {
|
||||
json!({ "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." })
|
||||
}
|
||||
|
||||
pub struct Call {
|
||||
pub client: String,
|
||||
pub tool: String,
|
||||
@@ -88,12 +96,24 @@ impl Call {
|
||||
client: self.client.clone(),
|
||||
tool: self.tool.clone(),
|
||||
subject: subject.into(),
|
||||
project: self.root().to_string_lossy().into_owned(),
|
||||
project: ide_core::ipc_path::to_ipc(self.root()),
|
||||
detail,
|
||||
background: super::BackgroundProjects::is_key(&self.window),
|
||||
})
|
||||
.await?;
|
||||
self.project.require_trust()
|
||||
}
|
||||
/// Refuses a tool that works through the project's window (its editors, Problems view, Run
|
||||
/// tool window or breakpoints) when the project is served in the background without one.
|
||||
pub fn needs_window(&self) -> IdeResult<()> {
|
||||
if !super::BackgroundProjects::is_key(&self.window) {
|
||||
return Ok(());
|
||||
}
|
||||
let (tool, root) = (&self.tool, self.root().display());
|
||||
Err(IdeError::unavailable(format!(
|
||||
"{tool} needs the project open in a window: {root} is served in the background."
|
||||
)))
|
||||
}
|
||||
pub fn host(&self) -> Arc<Host> {
|
||||
self.host.clone()
|
||||
}
|
||||
@@ -242,9 +262,7 @@ impl Tool {
|
||||
read_only: true,
|
||||
destructive: false,
|
||||
output_schema: None,
|
||||
input_schema: json!({ "type": "object", "properties": {
|
||||
"projectPath": { "type": "string", "description": "Any directory inside a project that is open in a window or served in the background. Defaults to the connection's project (`?project=`) or the only one open in a window." }
|
||||
}, "required": [] }),
|
||||
input_schema: json!({ "type": "object", "properties": { PROJECT_PATH: project_path() }, "required": [] }),
|
||||
},
|
||||
handler: Arc::new(move |call| Box::pin(handler(call))),
|
||||
}
|
||||
|
||||
@@ -99,8 +99,8 @@ fn get_repositories() -> Tool {
|
||||
"get_repositories",
|
||||
"Retrieves the list of VCS roots in the project.
|
||||
This is useful to detect all repositories in a multi-repository project.
|
||||
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached), `headCommit` and a merge, \
|
||||
rebase or cherry-pick in progress (`operationInProgress`).",
|
||||
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached or the repository is unavailable), \
|
||||
`headCommit`, a merge, rebase or cherry-pick in progress (`operationInProgress`), and `unavailable` (`true` when the repository directory cannot be reached).",
|
||||
|call| async move {
|
||||
let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?;
|
||||
let list: Vec<Value> = roots
|
||||
@@ -117,6 +117,9 @@ rebase or cherry-pick in progress (`operationInProgress`).",
|
||||
if let Some(op) = r.operation {
|
||||
v["operationInProgress"] = op.into();
|
||||
}
|
||||
if r.unavailable {
|
||||
v["unavailable"] = true.into();
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
@@ -256,10 +259,10 @@ By default all Git repositories are returned.",
|
||||
let include_ignored = call.flag("includeIgnored", false)?;
|
||||
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
|
||||
let host = call.host();
|
||||
let repos: Vec<(PathBuf, Option<String>)> = crate::ops::vcs::vcs_roots(&host, &call.window)
|
||||
let repos: Vec<(PathBuf, (Option<String>, bool))> = crate::ops::vcs::vcs_roots(&host, &call.window)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.root.into_path_buf(), r.head))
|
||||
.map(|r| (r.root.into_path_buf(), (r.head, r.unavailable)))
|
||||
.collect();
|
||||
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
|
||||
let paths = super::search::PathScope::of(&call)?;
|
||||
@@ -271,12 +274,25 @@ By default all Git repositories are returned.",
|
||||
};
|
||||
let mut roots: Vec<(PathBuf, Option<String>)> = if targets.is_empty() {
|
||||
repos
|
||||
.into_iter()
|
||||
.filter(|(_, (_, unavailable))| !unavailable)
|
||||
.map(|(root, (head, _))| (root, head))
|
||||
.collect()
|
||||
} else {
|
||||
let mut picked: Vec<(PathBuf, Option<String>)> = Vec::new();
|
||||
for path in targets {
|
||||
// The innermost repository containing the path.
|
||||
let repo = match innermost_repo(repos.clone(), &path) {
|
||||
Some(repo) => repo,
|
||||
Some((root, (_, true))) => {
|
||||
if wanted.is_some() {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Git repository '{}' is currently unavailable",
|
||||
relative_to_project(&call, &root)
|
||||
)));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Some((root, (head, false))) => (root, head),
|
||||
None => match find_git_root(call.root(), &path) {
|
||||
Some(root) => {
|
||||
// JetBrains reads the branch of any repository it reports.
|
||||
|
||||
@@ -277,6 +277,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("file.exportSettings", "Export Settings…"),
|
||||
act("file.importSettings", "Import Settings…"),
|
||||
act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"),
|
||||
act("file.importJetBrainsRecentProjects", "Import Recent Projects from JetBrains IDE…"),
|
||||
act("file.syncSettings", "Sync Settings Now"),
|
||||
],
|
||||
),
|
||||
@@ -484,6 +485,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("navigate.declaration", "Declaration or Usages"),
|
||||
act("navigate.implementation", "Implementation(s)"),
|
||||
act("navigate.typeDeclaration", "Type Declaration"),
|
||||
act("navigate.sourceDefinition", "Source Definition"),
|
||||
act("navigate.superMethod", "Super Method"),
|
||||
act("navigate.gotoTest", "Test"),
|
||||
act("navigate.relatedSymbol", "Related Symbol…"),
|
||||
|
||||
@@ -1115,11 +1115,16 @@ pub async fn agent_mcp_test(host: &Host, window: &str, id: String) -> IdeResult<
|
||||
let cwd = project.as_ref().map(|p| p.root.clone()).or_else(dirs::home_dir).unwrap_or_else(std::env::temp_dir);
|
||||
match server.transport {
|
||||
McpTransport::Stdio => Ok(ide_agent::mcp::probe_stdio_server(&server, &cwd).await),
|
||||
McpTransport::Http | McpTransport::Sse => Ok(probe_http_mcp_server(&server).await),
|
||||
McpTransport::Http | McpTransport::Sse => {
|
||||
Ok(probe_http_mcp_server(&server, &ide_core::proxy_settings::proxy()).await)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> McpProbeResult {
|
||||
async fn probe_http_mcp_server(
|
||||
server: &ide_core::settings::AgentMcpServer,
|
||||
proxy: &ide_core::proxy_settings::ProxySettings,
|
||||
) -> McpProbeResult {
|
||||
let started = std::time::Instant::now();
|
||||
let elapsed_ms = || u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
let Some(url) = server.url.as_deref().map(str::trim).filter(|u| !u.is_empty()) else {
|
||||
@@ -1145,31 +1150,36 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
|
||||
headers.insert(name, val);
|
||||
}
|
||||
}
|
||||
let client =
|
||||
match reqwest::Client::builder().default_headers(headers).timeout(std::time::Duration::from_secs(12)).build() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
return McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some(format!("HTTP client error: {e}")),
|
||||
};
|
||||
}
|
||||
};
|
||||
let client = match ide_http::client::build(proxy) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
return McpProbeResult {
|
||||
ok: false,
|
||||
server_name: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
tools: Vec::new(),
|
||||
duration_ms: elapsed_ms(),
|
||||
error: Some(format!("HTTP client error: {}", e.message)),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// The shared client has no MCP headers or 12 s limit of its own. The protocol's headers win over the
|
||||
// configured ones, as they did over the client's default headers.
|
||||
let post = |client: &reqwest::Client, url: &str, session_id: Option<&str>| {
|
||||
let mut headers = headers.clone();
|
||||
headers.insert(reqwest::header::CONTENT_TYPE, reqwest::header::HeaderValue::from_static("application/json"));
|
||||
if let Some(value) = session_id.and_then(|sid| reqwest::header::HeaderValue::from_str(sid).ok()) {
|
||||
headers.insert("mcp-session-id", value);
|
||||
}
|
||||
client.post(url).headers(headers).timeout(std::time::Duration::from_secs(12))
|
||||
};
|
||||
let post_rpc = |session_id: Option<String>, body: serde_json::Value| {
|
||||
let client = client.clone();
|
||||
let url = url.to_owned();
|
||||
async move {
|
||||
let mut req =
|
||||
client.post(&url).header(reqwest::header::CONTENT_TYPE, "application/json").body(body.to_string());
|
||||
if let Some(sid) = session_id.as_deref() {
|
||||
req = req.header("Mcp-Session-Id", sid);
|
||||
}
|
||||
let req = post(&client, &url, session_id.as_deref()).body(body.to_string());
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
@@ -1218,7 +1228,7 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
|
||||
};
|
||||
|
||||
// Best-effort `notifications/initialized` + `tools/list`.
|
||||
let mut not_req = client.post(url).header(reqwest::header::CONTENT_TYPE, "application/json").body(
|
||||
let not_req = post(&client, url, session_id.as_deref()).body(
|
||||
serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/initialized",
|
||||
@@ -1226,9 +1236,6 @@ async fn probe_http_mcp_server(server: &ide_core::settings::AgentMcpServer) -> M
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
if let Some(sid) = session_id.as_deref() {
|
||||
not_req = not_req.header("Mcp-Session-Id", sid);
|
||||
}
|
||||
let _ = not_req.send().await;
|
||||
|
||||
let tools_res = post_rpc(
|
||||
@@ -1866,6 +1873,112 @@ fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::P
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_mcp_probe_goes_through_the_manual_proxy_and_keeps_its_headers() {
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let settings = ide_core::proxy_settings::ProxySettings {
|
||||
mode: ide_core::proxy_settings::ProxyMode::Manual,
|
||||
host: "127.0.0.1".into(),
|
||||
port: address.port(),
|
||||
..Default::default()
|
||||
};
|
||||
let proxy = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut reader = BufReader::new(stream.try_clone().unwrap());
|
||||
let mut head = String::new();
|
||||
while !head.ends_with("\r\n\r\n") {
|
||||
if reader.read_line(&mut head).unwrap() == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = stream.write_all(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
head
|
||||
});
|
||||
let server = ide_core::settings::AgentMcpServer {
|
||||
transport: McpTransport::Http,
|
||||
url: Some("http://mcp-target.invalid/mcp".into()),
|
||||
headers: [("X-Test".to_owned(), "1".to_owned())].into(),
|
||||
..Default::default()
|
||||
};
|
||||
let result = probe_http_mcp_server(&server, &settings).await;
|
||||
assert!(!result.ok);
|
||||
// A probe that bypassed the proxy leaves it waiting in `accept`; a dummy connection releases it.
|
||||
let _ = std::net::TcpStream::connect(address);
|
||||
let head = proxy.join().unwrap().to_ascii_lowercase();
|
||||
assert!(head.starts_with("post http://mcp-target.invalid/mcp http/1.1"), "{head}");
|
||||
assert!(head.contains("accept: application/json, text/event-stream"), "{head}");
|
||||
assert!(head.contains("x-test: 1"), "{head}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_protocol_headers_win_over_configured_ones_in_all_three_requests() {
|
||||
use std::io::{Read, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let server = std::thread::spawn(move || {
|
||||
let mut heads = Vec::new();
|
||||
for reply in [
|
||||
r#"{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05","capabilities":{},"serverInfo":{"name":"t","version":"1"}}}"#,
|
||||
"",
|
||||
r#"{"jsonrpc":"2.0","id":2,"result":{"tools":[]}}"#,
|
||||
] {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut raw = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
while !raw.ends_with(b"\r\n\r\n") {
|
||||
stream.read_exact(&mut byte).unwrap();
|
||||
raw.push(byte[0]);
|
||||
}
|
||||
let head = String::from_utf8(raw).unwrap().to_ascii_lowercase();
|
||||
let length = head
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("content-length: "))
|
||||
.map_or(0, |value| value.trim().parse().unwrap());
|
||||
let mut body = vec![0u8; length];
|
||||
stream.read_exact(&mut body).unwrap();
|
||||
heads.push(head);
|
||||
let _ = stream.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nMcp-Session-Id: s1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
|
||||
reply.len()
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
}
|
||||
heads
|
||||
});
|
||||
let settings = ide_core::proxy_settings::ProxySettings {
|
||||
mode: ide_core::proxy_settings::ProxyMode::None,
|
||||
..Default::default()
|
||||
};
|
||||
let server_config = ide_core::settings::AgentMcpServer {
|
||||
transport: McpTransport::Http,
|
||||
url: Some(format!("http://127.0.0.1:{port}/mcp")),
|
||||
headers: [
|
||||
("Content-Type".to_owned(), "text/plain".to_owned()),
|
||||
("Mcp-Session-Id".to_owned(), "configured".to_owned()),
|
||||
("Accept".to_owned(), "text/x-configured".to_owned()),
|
||||
]
|
||||
.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let result = probe_http_mcp_server(&server_config, &settings).await;
|
||||
assert!(result.ok, "{:?}", result.error);
|
||||
let heads = server.join().unwrap();
|
||||
let values = |head: &str, name: &str| -> Vec<String> {
|
||||
head.lines().filter_map(|line| line.strip_prefix(name)).map(|v| v.trim().to_owned()).collect()
|
||||
};
|
||||
for (i, head) in heads.iter().enumerate() {
|
||||
assert_eq!(values(head, "content-type:"), ["application/json"], "request {i}: {head}");
|
||||
assert_eq!(values(head, "accept:"), ["text/x-configured"], "request {i}: {head}");
|
||||
// The first request has no session yet, so the configured value stands.
|
||||
let session = if i == 0 { "configured" } else { "s1" };
|
||||
assert_eq!(values(head, "mcp-session-id:"), [session], "request {i}: {head}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_installs_once_at_a_time() {
|
||||
let first = Installing::begin("test-agent").unwrap();
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
mod kotlin;
|
||||
#[cfg(test)]
|
||||
mod kotlin_tests;
|
||||
#[cfg(test)]
|
||||
mod native_tests;
|
||||
mod output;
|
||||
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{DebugSessionId, IdeResult};
|
||||
use ide_dap::*;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
|
||||
#[command(trust = trusted)]
|
||||
@@ -140,6 +142,17 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
config = add_java_source_paths(config, &roots);
|
||||
}
|
||||
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
|
||||
// No lldb-dap on this host (most Linux hosts): CodeLLDB, else GDB 14+.
|
||||
if config.adapter == "lldb-dap" {
|
||||
let (root, settings) = (root.clone(), settings.clone());
|
||||
let project_root = project.root.clone();
|
||||
config = ide_dap::native::choose(config, move |command| {
|
||||
native_debugger_command(&project_root, &settings.debugger.cpp, command)
|
||||
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
|
||||
.or_else(|| ide_dap::adapter::resolve_binary(command, &root))
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
let mut ruby_tools = Vec::new();
|
||||
if config.adapter == "rdbg" && config.request == "launch" {
|
||||
let project_root = host.project(window).map(|p| p.root.clone()).unwrap_or_else(|_| root.clone());
|
||||
@@ -152,11 +165,13 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
.await?;
|
||||
}
|
||||
let java_analyzer = java_analyzer_command(host, window, &config)?;
|
||||
let native = native_debugger_command(&project.root, &settings.debugger.cpp, &config.adapter);
|
||||
let custom = |command: &str| {
|
||||
if let Some(binary) = java_analyzer {
|
||||
return Some(binary.to_string_lossy().into_owned());
|
||||
}
|
||||
let path = ide_sdk::apply::tool_command(&root, &settings, command)
|
||||
let path = native
|
||||
.or_else(|| ide_sdk::apply::tool_command(&root, &settings, command))
|
||||
.or_else(|| ruby_tools.into_iter().find(|(name, _)| *name == command).map(|(_, path)| path))?;
|
||||
Some(path.to_string_lossy().into_owned())
|
||||
};
|
||||
@@ -188,6 +203,19 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
result
|
||||
}
|
||||
|
||||
fn native_debugger_command(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::CppDebuggerSettings,
|
||||
adapter: &str,
|
||||
) -> Option<PathBuf> {
|
||||
let path = match adapter {
|
||||
"gdb" => &settings.gdb_executable,
|
||||
"lldb-dap" => &settings.lldb_dap_executable,
|
||||
_ => return None,
|
||||
};
|
||||
ide_sdk::apply::setting_path(root, path)
|
||||
}
|
||||
|
||||
/// For java-analyzer's debugger, the executable of the java-analyzer serving the module
|
||||
/// (`projectRoot`, else the working directory), so the session debugs with the server that
|
||||
/// analyzes the code.
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
use super::*;
|
||||
use ide_core::IdeError;
|
||||
use ide_dap::adapter::{AdapterLauncher, AdapterSpec, LaunchFuture};
|
||||
use ide_workspace::SettingsScope;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Default)]
|
||||
struct CaptureAdapter(Mutex<Option<AdapterSpec>>);
|
||||
|
||||
impl AdapterLauncher for CaptureAdapter {
|
||||
fn launch(&self, spec: AdapterSpec, _: Option<u16>) -> LaunchFuture {
|
||||
*self.0.lock() = Some(spec);
|
||||
Box::pin(async { Err(IdeError::cancelled()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn cpp_debugger_paths_override_adapter_commands() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let cwd = root.join("build");
|
||||
std::fs::create_dir_all(&cwd).unwrap();
|
||||
let capture = Arc::new(CaptureAdapter::default());
|
||||
let mut host = Host::new(crate::HostConfig::for_test(&base));
|
||||
host.debugger = DebugManager::with_launcher(host.languages.clone(), capture.clone());
|
||||
host.open_project("main", &root).unwrap();
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
let project = host.project("main").unwrap();
|
||||
|
||||
for (adapter, key, configured) in [
|
||||
("gdb", "gdbExecutable", root.join("custom gdb").to_str().unwrap().to_owned()),
|
||||
("lldb-dap", "lldbDapExecutable", "tools/lldb-dap-custom".into()),
|
||||
] {
|
||||
let config = LaunchConfig {
|
||||
name: "C++".into(),
|
||||
adapter: adapter.into(),
|
||||
request: "attach".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: Some(cwd.clone().into()),
|
||||
env: Default::default(),
|
||||
extra_json: Some(r#"{"pid":1}"#.into()),
|
||||
};
|
||||
let _ = debug_start(&host, "main", config.clone()).await.unwrap_err();
|
||||
assert_eq!(capture.0.lock().take().unwrap().command, adapter);
|
||||
|
||||
project
|
||||
.settings
|
||||
.set(SettingsScope::Project, &format!("debugger.cpp.{key}"), serde_json::json!(configured))
|
||||
.unwrap();
|
||||
let mut config = config;
|
||||
config.request = "launch".into();
|
||||
config.program = Some(cwd.join("app").to_str().unwrap().to_owned());
|
||||
config.extra_json = None;
|
||||
let _ = debug_start(&host, "main", config).await.unwrap_err();
|
||||
let spec = capture.0.lock().take().unwrap();
|
||||
assert_eq!(spec.adapter, adapter);
|
||||
assert_eq!(Path::new(&spec.command), root.join(configured));
|
||||
assert_eq!(spec.cwd, cwd);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ pub async fn doc_close(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.documents.close(doc);
|
||||
ide_core::memory::release_free_pages_soon();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -246,7 +246,17 @@ pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
|
||||
#[command(trust = always)]
|
||||
pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
|
||||
match host.project(window) {
|
||||
Ok(p) => p.documents.set_writable(&path, writable),
|
||||
Ok(p) => {
|
||||
// A checkout backend keeps files read-only until opened for edit (`p4 edit`), so
|
||||
// its server learns about the change to come. `backend_of` is empty unless trusted.
|
||||
if writable
|
||||
&& let Some(backend) = p.backend_of(&path)
|
||||
&& backend.open_for_edit(std::slice::from_ref(&path))?
|
||||
{
|
||||
p.vcs_changed();
|
||||
}
|
||||
p.documents.set_writable(&path, writable)
|
||||
}
|
||||
Err(_) => ide_vfs::set_writable(&path, writable).map(|()| !writable),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,16 +8,16 @@ async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + '
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// The available iOS simulators, booted first; `None` outside macOS or when the project has no
|
||||
/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
|
||||
/// no change feed, and one listing takes a fraction of a second.
|
||||
/// The available iOS simulators, booted first, then the paired iPhones and iPads; `None` outside
|
||||
/// macOS or when the project has no Xcode project or workspace at its root. Asked again whenever
|
||||
/// the chooser opens: `simctl` has no change feed, and one listing takes a fraction of a second.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<IosSimulator>>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
if !cfg!(target_os = "macos") || !simulator::is_xcode_project(&root) {
|
||||
return Ok(None);
|
||||
}
|
||||
blocking(simulator::list).await.map(Some)
|
||||
blocking(move || simulator::list(&root)).await.map(Some)
|
||||
}
|
||||
|
||||
/// Boots a simulator; returns once it is booted.
|
||||
|
||||
@@ -246,6 +246,7 @@ pub(crate) async fn resolve_launch(
|
||||
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_maven_system_classpath(&mut info, root, &model, &module);
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
if build && !delegated {
|
||||
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
|
||||
@@ -544,39 +545,28 @@ async fn resolve_launch_without_jdtls(
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
match from_server {
|
||||
// The IDE's Java build gave the whole classpath; the server adds its JDK.
|
||||
Some(server) if by_service => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
}
|
||||
None if by_service => {}
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.module_paths = server.classpath.module_paths;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
|
||||
}
|
||||
None => {
|
||||
if !is_maven_module(root, &model, &module) {
|
||||
return Err(IdeError::unavailable(
|
||||
"Cannot resolve the classpath: the Java language server does not report it \
|
||||
(java-analyzer/projectClasspath), and the module is not a Maven project",
|
||||
));
|
||||
}
|
||||
let is_maven = is_maven_module(root, &model, &module);
|
||||
let delegated_maven = !by_service && settings.languages.java.maven.delegate_build && is_maven;
|
||||
apply_without_jdtls_classpath(
|
||||
&mut class_paths,
|
||||
&mut info,
|
||||
from_server,
|
||||
by_service,
|
||||
is_maven,
|
||||
delegated_maven,
|
||||
|| {
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
let classpath = if aggregator && policy == BuildPolicy::NoBuild {
|
||||
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)?
|
||||
if aggregator && policy == BuildPolicy::NoBuild {
|
||||
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)
|
||||
} else {
|
||||
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?
|
||||
};
|
||||
append_unique_class_paths(
|
||||
&mut class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
);
|
||||
}
|
||||
}
|
||||
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)
|
||||
}
|
||||
},
|
||||
)?;
|
||||
info.class_paths = class_paths;
|
||||
if !by_service {
|
||||
apply_maven_system_classpath(&mut info, root, &model, &module);
|
||||
}
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
@@ -695,6 +685,15 @@ fn entry_key(path: &str, windows: bool) -> String {
|
||||
if windows { key.to_lowercase() } else { key }
|
||||
}
|
||||
|
||||
fn apply_maven_system_classpath(info: &mut JavaLaunchInfo, root: &Path, model: &BuildModel, module: &Path) {
|
||||
for path in compile::maven_system_classpath(root, model, module) {
|
||||
let path = path.to_string_lossy();
|
||||
if !info.class_paths.iter().chain(&info.module_paths).any(|entry| same_entry(entry, &path, cfg!(windows))) {
|
||||
info.class_paths.push(path.into_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_library_classpath(
|
||||
info: &mut JavaLaunchInfo,
|
||||
root: &std::path::Path,
|
||||
@@ -709,8 +708,10 @@ fn apply_library_classpath(
|
||||
DependencyScope::Compile | DependencyScope::Runtime => true,
|
||||
DependencyScope::Test | DependencyScope::Provided => test,
|
||||
};
|
||||
lib.classes.iter().filter_map(move |entry| {
|
||||
ide_sdk::apply::setting_path(root, entry).map(|path| (path.to_string_lossy().into_owned(), allowed))
|
||||
lib.classes.iter().flat_map(move |entry| {
|
||||
ide_sdk::libraries::library_class_paths(root, entry)
|
||||
.into_iter()
|
||||
.map(move |p| (p.to_string_lossy().into_owned(), allowed))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -825,6 +826,59 @@ fn same_entry(a: &str, b: &str, windows: bool) -> bool {
|
||||
a == b || entry_key(a, windows) == entry_key(b, windows)
|
||||
}
|
||||
|
||||
/// Resolves the runtime/test classpath for a launch without jdtls (e.g. `java-analyzer` or
|
||||
/// no Java language server). When `delegated_maven` is true (`delegateBuild = true` on a Maven
|
||||
/// module), delegates classpath resolution to Maven itself (falling back to the language server's
|
||||
/// classpath on error, matching the jdtls path) so child POM `<exclusions>` and Maven dependency
|
||||
/// mediation are respected (#5586).
|
||||
fn apply_without_jdtls_classpath(
|
||||
class_paths: &mut Vec<String>,
|
||||
info: &mut JavaLaunchInfo,
|
||||
from_server: Option<ide_lsp::java_project::ServerClasspath>,
|
||||
by_service: bool,
|
||||
is_maven: bool,
|
||||
delegated_maven: bool,
|
||||
probe_maven: impl FnOnce() -> IdeResult<String>,
|
||||
) -> IdeResult<()> {
|
||||
match from_server {
|
||||
// The IDE's Java build gave the whole classpath; the server adds its JDK.
|
||||
Some(server) if by_service => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
Ok(())
|
||||
}
|
||||
None if by_service => Ok(()),
|
||||
Some(server) if delegated_maven => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.module_paths = server.classpath.module_paths;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
info.class_paths = server.classpath.class_paths;
|
||||
merge_maven_launch_classpath(class_paths, info, probe_maven(), &[])
|
||||
}
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.module_paths = server.classpath.module_paths;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
append_unique_class_paths(class_paths, server.classpath.class_paths);
|
||||
Ok(())
|
||||
}
|
||||
None => {
|
||||
if !is_maven {
|
||||
return Err(IdeError::unavailable(
|
||||
"Cannot resolve the classpath: the Java language server does not report it \
|
||||
(java-analyzer/projectClasspath), and the module is not a Maven project",
|
||||
));
|
||||
}
|
||||
let classpath = probe_maven()?;
|
||||
append_unique_class_paths(
|
||||
class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge the Maven launch classpath without turning a recoverable probe failure into a
|
||||
/// failed launch. Cancellation still propagates; ordinary failures keep jdtls' classpath
|
||||
/// and leave the reason in the run console. Maven lists the module's and its reactor
|
||||
@@ -1234,6 +1288,34 @@ mod tests {
|
||||
assert!(info.hints[0].contains("offline dependency"), "{:?}", info.hints);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_server_launch_classpath_includes_local_maven_system_jars() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let jar = root.join("src/main/resources/lib/offline.jar");
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>demo</groupId><artifactId>app</artifactId><version>1</version>
|
||||
<dependencies><dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${pom.basedir}/src/main/resources/lib/offline.jar</systemPath>
|
||||
</dependency></dependencies></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let model = ide_build::load(&root, &root.join("cache"), None);
|
||||
let jar = jar.to_string_lossy().into_owned();
|
||||
let mut info = JavaLaunchInfo { class_paths: vec!["classes".into()], ..Default::default() };
|
||||
apply_maven_system_classpath(&mut info, &root, &model, &root);
|
||||
apply_maven_system_classpath(&mut info, &root, &model, &root);
|
||||
assert_eq!(info.class_paths, ["classes", &jar]);
|
||||
|
||||
info.class_paths.pop();
|
||||
info.module_paths.push(jar);
|
||||
apply_maven_system_classpath(&mut info, &root, &model, &root);
|
||||
assert_eq!(info.class_paths, ["classes"]);
|
||||
}
|
||||
|
||||
/// Maven's launch classpath lists the module's and its reactor siblings' outputs, which
|
||||
/// the launch already runs from a snapshot: listed twice, MyBatis loads each mapper XML
|
||||
/// twice and fails with "XML fragments parsed from previous mappers already contains value".
|
||||
@@ -1259,6 +1341,55 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delegated_maven_without_jdtls_prefers_maven_classpath_over_server_classpath() {
|
||||
let server = ide_lsp::java_project::ServerClasspath {
|
||||
classpath: ide_lsp::jdtls::JavaClasspath {
|
||||
project_root: Some(PathBuf::from("/work/child").into()),
|
||||
// Static server resolver kept an excluded parent transitive jar (#5586).
|
||||
class_paths: vec![
|
||||
"/work/child/target/classes".into(),
|
||||
"/m2/log4j-slf4j-impl-2.12.1.jar".into(),
|
||||
"/m2/logback-classic.jar".into(),
|
||||
],
|
||||
module_paths: vec![],
|
||||
},
|
||||
jdk_home: Some(PathBuf::from("/jdk8")),
|
||||
};
|
||||
let maven = std::env::join_paths(["/work/child/target/classes", "/m2/logback-classic.jar"])
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
|
||||
let mut info = JavaLaunchInfo::default();
|
||||
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || Ok(maven))
|
||||
.unwrap();
|
||||
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/logback-classic.jar"]);
|
||||
assert_eq!(info.project_root, Some(PathBuf::from("/work/child").into()));
|
||||
assert_eq!(info.java_home, Some(PathBuf::from("/jdk8").into()));
|
||||
assert!(info.hints.is_empty(), "{:?}", info.hints);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delegated_maven_without_jdtls_falls_back_to_server_classpath_on_probe_error() {
|
||||
let server = ide_lsp::java_project::ServerClasspath {
|
||||
classpath: ide_lsp::jdtls::JavaClasspath {
|
||||
project_root: Some(PathBuf::from("/work/child").into()),
|
||||
class_paths: vec!["/m2/server-fallback.jar".into()],
|
||||
module_paths: vec![],
|
||||
},
|
||||
jdk_home: None,
|
||||
};
|
||||
let mut class_paths = vec!["/work/child/target/classes".to_owned()];
|
||||
let mut info = JavaLaunchInfo::default();
|
||||
apply_without_jdtls_classpath(&mut class_paths, &mut info, Some(server), false, true, true, || {
|
||||
Err(IdeError::internal("maven offline"))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(class_paths, ["/work/child/target/classes", "/m2/server-fallback.jar"]);
|
||||
assert!(info.hints[0].contains("maven offline"), "{:?}", info.hints);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_maven_classpath_probe_propagates_without_fallback() {
|
||||
let mut class_paths = vec!["snapshot.jar".to_owned()];
|
||||
@@ -1404,6 +1535,26 @@ mod tests {
|
||||
let mut info = JavaLaunchInfo::default();
|
||||
apply_library_classpath(&mut info, root.path(), &libraries, false);
|
||||
assert_eq!(info.class_paths, &paths[..2]);
|
||||
|
||||
// Directory library roots expand to the JAR files inside them.
|
||||
let web_lib = root.path().join("WebRoot/WEB-INF/lib");
|
||||
std::fs::create_dir_all(&web_lib).unwrap();
|
||||
let a_jar = web_lib.join("a.jar");
|
||||
let b_jar = web_lib.join("b.jar");
|
||||
std::fs::write(&a_jar, b"").unwrap();
|
||||
std::fs::write(&b_jar, b"").unwrap();
|
||||
let dir_libs = vec![ProjectLibrary {
|
||||
name: "web".into(),
|
||||
classes: vec!["WebRoot/WEB-INF/lib".into()],
|
||||
scope: DependencyScope::Compile,
|
||||
..Default::default()
|
||||
}];
|
||||
let mut dir_info = JavaLaunchInfo::default();
|
||||
apply_library_classpath(&mut dir_info, root.path(), &dir_libs, false);
|
||||
assert_eq!(
|
||||
dir_info.class_paths,
|
||||
vec![a_jar.to_string_lossy().into_owned(), b_jar.to_string_lossy().into_owned()]
|
||||
);
|
||||
}
|
||||
|
||||
/// JDT LS and our build model spell a module output differently on Windows; the
|
||||
|
||||
@@ -336,20 +336,36 @@ pub async fn lsp_inline_completion(
|
||||
let plugin = match plugin_providers(host, window, doc, ProviderKind::InlineCompletion) {
|
||||
Some((plugins, d)) if !matches!(&result, Ok(items) if !items.is_empty()) => {
|
||||
let cancel = cancel.clone();
|
||||
plugin_call(move || plugins.provide_inline_completion(&d, pos, &cancel)).await.flatten()
|
||||
plugin_call(move || {
|
||||
let offered = plugins.offers_inline_completion(&d.language);
|
||||
(offered, plugins.provide_inline_completion(&d, pos, &cancel).map(|(_, s)| s))
|
||||
})
|
||||
.await
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
host.end_request(request);
|
||||
inline_items(result, plugin)
|
||||
}
|
||||
|
||||
/// The plugin's suggestion, else the servers'. When a plugin offers ghost text
|
||||
/// for the document, "no server supports inline completion" is not returned:
|
||||
/// the editor would stop asking while typing for 30 s, and a plugin that had
|
||||
/// nothing this time (cancelled by the next keystroke) may have some next time.
|
||||
fn inline_items(
|
||||
servers: IdeResult<Vec<InlineCompletionItem>>,
|
||||
plugin: Option<(bool, Option<ide_plugin::InlineSuggestion>)>,
|
||||
) -> IdeResult<Vec<InlineCompletionItem>> {
|
||||
match plugin {
|
||||
Some((_, s)) => Ok(vec![InlineCompletionItem {
|
||||
Some((_, Some(s))) => Ok(vec![InlineCompletionItem {
|
||||
insert_text: s.insert_text,
|
||||
range: s.replace,
|
||||
filter_text: None,
|
||||
command: None,
|
||||
server: PLUGIN_SERVER,
|
||||
}]),
|
||||
None => result,
|
||||
Some((true, None)) => provider_server(servers),
|
||||
_ => servers,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -659,6 +675,53 @@ pub async fn lsp_switch_source_header(
|
||||
Ok(result?.map(|path| path.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
/// Go to Source Definition (vtsls): the JavaScript implementation of the symbol at `pos`
|
||||
/// instead of its `.d.ts`. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_source_definition(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
pos: Pos,
|
||||
) -> IdeResult<Vec<Location>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::select! {
|
||||
result = lsp.source_definition(doc, pos, cancel.clone()) => result,
|
||||
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
|
||||
};
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Has vtsls open the document's `tsconfig.json` / `jsconfig.json` or the TS Server log.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_open_typescript_file(host: &Host, window: &str, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
lsp.open_typescript_file(doc, what).await
|
||||
}
|
||||
|
||||
/// The files tsserver suggests for vtsls' Move to File code action `command`. Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_move_to_file_targets(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
command: Command,
|
||||
) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::select! {
|
||||
result = lsp.move_to_file_targets(doc, command, cancel.clone()) => result,
|
||||
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
|
||||
};
|
||||
host.end_request(request);
|
||||
Ok(result?.into_iter().map(ide_core::IpcPath::from).collect())
|
||||
}
|
||||
|
||||
/// Implementations of the symbols at `positions`, one list per position (the
|
||||
/// editor's "is implemented / overridden" gutter markers). Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
@@ -866,9 +929,14 @@ pub async fn lsp_library_sources(
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_resolve_class_file(host: &Host, window: &str, path: std::path::PathBuf) -> IdeResult<String> {
|
||||
// Opens compiled classes through JDT as decompiled class documents.
|
||||
let archive = ide_vfs::split_archive_path(&path);
|
||||
host.project(window)?.lsp.java_class_file(&path, archive).await
|
||||
host.project(window)?.lsp.java_class_file(&path, archive, read_internal_class_name(&path)).await
|
||||
}
|
||||
|
||||
async fn read_internal_class_name(path: &Path) -> IdeResult<String> {
|
||||
let bytes = tokio::fs::read(path).await?;
|
||||
ide_build::jbuild::class_file_name(&bytes)
|
||||
.ok_or_else(|| IdeError::not_found(format!("invalid class file: {}", path.display())))
|
||||
}
|
||||
|
||||
/// References of the symbol at `pos`. `project_wide` also searches project files
|
||||
@@ -2429,6 +2497,31 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[tokio::test]
|
||||
async fn disk_class_name_comes_from_bytecode() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("moved.class");
|
||||
// Class header, UTF-8 and Class constants, then access_flags and this_class.
|
||||
let bytes = b"\xca\xfe\xba\xbe\0\0\0\x3d\0\x03\x01\0\x0d\x70/Outer$Inner\x07\0\x01\0\x21\0\x02";
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
assert_eq!(read_internal_class_name(&path).await.unwrap(), "p/Outer$Inner");
|
||||
std::fs::write(&path, b"invalid").unwrap();
|
||||
assert_eq!(read_internal_class_name(&path).await.unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plugin_offering_ghost_text_keeps_the_editor_asking() {
|
||||
use super::*;
|
||||
let none = || Err(ide_core::IdeError::unavailable("No server supports inline completion"));
|
||||
// Nothing this time (cancelled by the next keystroke): an empty answer, not "unavailable".
|
||||
assert!(inline_items(none(), Some((true, None))).unwrap().is_empty());
|
||||
// No plugin for this language: the servers' answer as it is.
|
||||
assert!(inline_items(none(), Some((false, None))).is_err());
|
||||
assert!(inline_items(none(), None).is_err());
|
||||
let s = ide_plugin::InlineSuggestion { insert_text: "a + b".into(), replace: None };
|
||||
assert_eq!(inline_items(none(), Some((true, Some(s)))).unwrap()[0].insert_text, "a + b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_completion_word_is_its_line_and_what_precedes_it() {
|
||||
use super::*;
|
||||
@@ -3315,6 +3408,9 @@ ide_command::domain!(
|
||||
lsp_implementation_locations,
|
||||
lsp_file_references,
|
||||
lsp_switch_source_header,
|
||||
lsp_source_definition,
|
||||
lsp_open_typescript_file,
|
||||
lsp_move_to_file_targets,
|
||||
lsp_implementations,
|
||||
lsp_inlay_hints,
|
||||
lsp_inline_completion,
|
||||
|
||||
@@ -521,11 +521,19 @@ pub async fn nav_python_library_imports(
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.language.as_str() != "python" {
|
||||
// A notebook cell is a document of the language servers only: `documents` holds what the
|
||||
// editor opened, so ⌥↵ on a cell's unresolved name used to answer nothing.
|
||||
let (language, path) = match project.documents.snapshot(doc) {
|
||||
Ok(snap) => (snap.language, snap.path.0),
|
||||
Err(e) => match project.lsp.cell_text(doc) {
|
||||
Some(cell) => (cell.language, cell.path),
|
||||
None => return Err(e),
|
||||
},
|
||||
};
|
||||
if language.as_str() != "python" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&snap.path)) else {
|
||||
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&path)) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let roots = interpreter_site_packages(&python);
|
||||
|
||||
@@ -468,6 +468,12 @@ pub fn set_settings(
|
||||
}
|
||||
});
|
||||
}
|
||||
if ["languages", "languages.swift", "languages.swift.xcode"].contains(&key) {
|
||||
// An untrusted project keeps no Xcode of its own (see `xcode_env`).
|
||||
for project in affected().into_iter().filter(|p| p.is_trusted()) {
|
||||
host.runtime.spawn(async move { crate::xcode_env::apply_and_restart(&project).await });
|
||||
}
|
||||
}
|
||||
// `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() {
|
||||
|
||||
@@ -1,19 +1,34 @@
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeResult;
|
||||
use ide_dap::LaunchConfig;
|
||||
use ide_workspace::roots::RootKind;
|
||||
use std::collections::BTreeMap;
|
||||
use ide_workspace::roots::{RootKind, SourceFolder};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The project's import roots, put on `PYTHONPATH` by runs, debug sessions and consoles.
|
||||
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
|
||||
let mut paths = vec![project.root.clone()];
|
||||
paths.extend(project.content_roots());
|
||||
for root in project.roots().roots {
|
||||
if matches!(root.kind, RootKind::Source | RootKind::Test) {
|
||||
let path = project.root.join(root.path);
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
import_roots(&project.root, project.content_roots(), &project.roots().roots)
|
||||
}
|
||||
|
||||
/// `root`, the content roots, then the Source and Test roots. A detected root that is itself a
|
||||
/// package (it holds `__init__.py`, like an Odoo addon or its `tests` folder) is left out:
|
||||
/// importing from it would give its modules a second top-level name, and a project with
|
||||
/// thousands of them made `PYTHONPATH` longer than a process environment can hold (#7083).
|
||||
/// Folders the user marked always count.
|
||||
fn import_roots(root: &Path, content_roots: Vec<PathBuf>, roots: &[SourceFolder]) -> Vec<PathBuf> {
|
||||
let mut paths = vec![root.to_path_buf()];
|
||||
paths.extend(content_roots);
|
||||
let mut seen: HashSet<PathBuf> = paths.iter().cloned().collect();
|
||||
for folder in roots {
|
||||
if !matches!(folder.kind, RootKind::Source | RootKind::Test) {
|
||||
continue;
|
||||
}
|
||||
let path = root.join(&folder.path);
|
||||
if folder.detected_from.is_some() && path.join("__init__.py").is_file() {
|
||||
continue;
|
||||
}
|
||||
if seen.insert(path.clone()) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
paths
|
||||
@@ -120,6 +135,38 @@ pub(super) fn prepare_debug(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn detected_package_folders_are_not_import_roots() {
|
||||
use ide_workspace::roots::{RootKind, SourceFolder};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
for file in ["src/pkg/__init__.py", "addon/__init__.py", "addon/tests/__init__.py", "marked/__init__.py"] {
|
||||
let path = root.join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(root.join("tests")).unwrap();
|
||||
let folder = |path: &str, kind, detected: bool| SourceFolder {
|
||||
path: path.into(),
|
||||
kind,
|
||||
detected_from: detected.then(|| "pyproject.toml".into()),
|
||||
};
|
||||
let roots = [
|
||||
folder("src", RootKind::Source, true),
|
||||
folder("tests", RootKind::Test, true),
|
||||
folder("addon", RootKind::Source, true),
|
||||
folder("addon/tests", RootKind::Test, true),
|
||||
folder("marked", RootKind::Source, false),
|
||||
folder("build", RootKind::Excluded, true),
|
||||
folder("src", RootKind::Source, true),
|
||||
];
|
||||
assert_eq!(
|
||||
super::import_roots(root, vec![], &roots),
|
||||
[root.to_path_buf(), root.join("src"), root.join("tests"), root.join("marked")],
|
||||
"detected packages are left out, a folder the user marked stays, no duplicates"
|
||||
);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -448,13 +448,18 @@ async fn start_inner(
|
||||
}
|
||||
let target = ide_remote::service::run_target(&settings, id)?;
|
||||
if target.kind != RunTargetKind::Ssh {
|
||||
// A local run of the docker CLI: the command is resolved in the container, and
|
||||
// this machine's toolchains and `PYTHONPATH` don't apply.
|
||||
let mut config = config;
|
||||
if ide_run::is_python_kind(&config.kind) {
|
||||
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
|
||||
}
|
||||
let (config, note) = container::prepare(host, &project.root, target, config).await?;
|
||||
// A local run of the docker CLI or `wsl.exe`: the command is resolved in the
|
||||
// container or distribution, and this machine's toolchains and `PYTHONPATH` don't apply.
|
||||
// The settings of the workspace member it belongs to derived its values.
|
||||
let mut member = config.clone();
|
||||
let (member_root, member_settings, fallback) = settings_for(host, &project, &mut member)?;
|
||||
let derived = Derived { root: &member_root, fallback: fallback.as_deref(), settings: &member_settings };
|
||||
let config = remote_config(&config, derived, &project.root, &super::python::paths(&project));
|
||||
let (config, note) = if target.kind == RunTargetKind::Wsl {
|
||||
(container::prepare_wsl(host, &project.root, target, config).await?, None)
|
||||
} else {
|
||||
container::prepare(host, &project.root, target, config).await?
|
||||
};
|
||||
if let Some(note) = note {
|
||||
on_output(OutputChunk::System { text: format!("{note}\n") });
|
||||
}
|
||||
@@ -462,7 +467,7 @@ async fn start_inner(
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths: Vec::new(),
|
||||
// A folder on this machine: not in the container.
|
||||
// A folder on this machine: not in the container or distribution.
|
||||
ruby_reporter: None,
|
||||
plots: None,
|
||||
capture_junit_reports: false,
|
||||
@@ -547,19 +552,19 @@ async fn start_inner(
|
||||
.then(|| xcode_container(&config).map(|c| run_dir.join(c)))
|
||||
.flatten();
|
||||
if config.kind == "xcode" {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
let dir = run_dir.clone();
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode::prepare(&dir, &cache, &mut config)?;
|
||||
ide_run::xcode::prepare(&dir, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == ide_run::xcode_clean::KIND {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
let dir = run_dir.clone();
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode_clean::prepare(&dir, &cache, &mut config)?;
|
||||
ide_run::xcode_clean::prepare(&dir, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
@@ -575,9 +580,10 @@ async fn start_inner(
|
||||
}
|
||||
if config.kind == "xcode-test" {
|
||||
let bundles = project.cache_dir.join("xcresult");
|
||||
let dir = project.root.clone();
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode::prepare_test(&mut config, &bundles)?;
|
||||
ide_run::xcode::prepare_test(&mut config, &dir, &bundles)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
@@ -863,6 +869,44 @@ pub use commands::*;
|
||||
mod ownership_tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_remote_run_gets_none_of_this_machines_derived_values() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let venv = root.join(".venv");
|
||||
std::fs::create_dir_all(venv.join("bin")).unwrap();
|
||||
std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
|
||||
std::fs::write(venv.join("bin/python"), "").unwrap();
|
||||
let mut settings = ide_core::settings::Settings::default();
|
||||
settings.languages.python.interpreter = venv.join("bin/python").to_string_lossy().into_owned();
|
||||
let mut config = RunConfig {
|
||||
id: "app".into(),
|
||||
name: "app".into(),
|
||||
kind: "python".into(),
|
||||
command: "python".into(),
|
||||
args: vec!["main.py".into()],
|
||||
cwd: None,
|
||||
env: [("FOO".to_owned(), "bar".to_owned())].into(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
config.extras.target = Some("wsl".into());
|
||||
ide_sdk::apply::apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
|
||||
assert!(config.env.contains_key("VIRTUAL_ENV") && config.env.contains_key("PATH"), "{:?}", config.env);
|
||||
config.env.insert("GOFLAGS".into(), "-mod=mod".into());
|
||||
let derived = Derived { root, fallback: None, settings: &settings };
|
||||
let out = remote_config(&config, derived, root, &[root.to_path_buf()]);
|
||||
assert_eq!(out.env.keys().collect::<Vec<_>>(), ["FOO", "GOFLAGS", "PYTHONPATH"], "{:?}", out.env);
|
||||
assert_eq!(out.command, "python", "the interpreter is the target's");
|
||||
assert_eq!(out.extras.target.as_deref(), Some("wsl"));
|
||||
assert!(has_local_path("/opt/go") && has_local_path("/a/bin:/b/bin"));
|
||||
assert!(!has_local_path("-mod=mod") && !has_local_path("https://proxy.golang.org,direct"), "kept: not paths");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn source_roots_go_on_the_container_pythonpath() {
|
||||
@@ -1061,6 +1105,9 @@ pub async fn run_container_path(
|
||||
if !path.starts_with('/') {
|
||||
return Ok(None);
|
||||
}
|
||||
if run_target.kind == RunTargetKind::Wsl {
|
||||
return Ok(ide_remote::wsl::local_file(&path, &run_target, &root).filter(|f| f.is_file()).map(Into::into));
|
||||
}
|
||||
let library = snapshots
|
||||
.and_then(|dir| ide_sdk::container_python::current(&dir))
|
||||
.and_then(|(dir, snapshot)| ide_sdk::container_python::snapshot_file(&dir, &snapshot, &path));
|
||||
@@ -1073,9 +1120,39 @@ pub async fn run_container_path(
|
||||
.await
|
||||
}
|
||||
|
||||
/// The project's source roots on `PYTHONPATH` in a container, as a local run gets them:
|
||||
/// they are mounted with the project, and `container::prepare` maps their paths. The
|
||||
/// container's separator is `:`, whatever this machine's is.
|
||||
/// `config` for a container or WSL distribution: without what settings derived from this
|
||||
/// machine (its `PATH`, `VIRTUAL_ENV`, toolchain homes, resolved interpreter paths), which
|
||||
/// would replace the values there, and with the project's source roots on `PYTHONPATH`.
|
||||
/// Values that settings derive but that are not paths of this machine (`GOPROXY`, `GOFLAGS`)
|
||||
/// still apply there and are kept.
|
||||
fn remote_config(config: &RunConfig, derived: Derived<'_>, root: &Path, python_roots: &[PathBuf]) -> RunConfig {
|
||||
let plain = ide_sdk::apply::without_derived_in(config, derived.root, derived.fallback, derived.settings);
|
||||
let mut out = config.clone();
|
||||
out.command = plain.command;
|
||||
out.env.retain(|key, value| plain.env.contains_key(key) || !has_local_path(value));
|
||||
if ide_run::is_python_kind(&out.kind) {
|
||||
container_python_path(&mut out.env, python_roots, root);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The settings a configuration's derived values come from (see [`settings_for`]).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Derived<'a> {
|
||||
root: &'a Path,
|
||||
fallback: Option<&'a Path>,
|
||||
settings: &'a ide_core::settings::Settings,
|
||||
}
|
||||
|
||||
/// `value` is an absolute path of this machine, alone or first in a path list (a URL such
|
||||
/// as `GOPROXY`'s is not: its first part is `https`).
|
||||
fn has_local_path(value: &str) -> bool {
|
||||
std::env::split_paths(value).find(|p| !p.as_os_str().is_empty()).is_some_and(|p| p.is_absolute())
|
||||
}
|
||||
|
||||
/// The project's source roots on `PYTHONPATH` in a container or WSL distribution, as a local
|
||||
/// run gets them: they are mounted with the project, and `container::prepare` /
|
||||
/// `prepare_wsl` map their paths. The separator there is `:`, whatever this machine's is.
|
||||
fn container_python_path(env: &mut std::collections::BTreeMap<String, String>, roots: &[PathBuf], root: &Path) {
|
||||
let mut paths: Vec<String> =
|
||||
roots.iter().filter(|p| p.starts_with(root)).map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
|
||||
@@ -30,6 +30,8 @@ pub async fn run_xcode_test_results(host: &Host, window: &str, bundle: std::path
|
||||
return Err(IdeError::invalid("Not an Xcode result bundle"));
|
||||
}
|
||||
let mut cmd = tokio::process::Command::new("xcrun");
|
||||
// The project's Xcode reads the bundle its `xcodebuild` wrote.
|
||||
cmd.current_dir(&host.project(window)?.root);
|
||||
cmd.args(["xcresulttool", "get", "test-results", "tests", "--compact", "--path"]).arg(&bundle);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let out = cmd.output().await?;
|
||||
@@ -251,8 +253,10 @@ fn project_web_artifacts(ps: &ide_core::settings::ProjectStructureSettings) -> V
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Compiles the project and packs the Project Structure artifact `name` as the WAR Tomcat
|
||||
/// deploys, recorded in `base` like a build tool's archive.
|
||||
/// Compiles the project and builds the Project Structure artifact `name` for Tomcat to
|
||||
/// deploy, recording its output path in `base` like a build tool's archive.
|
||||
/// The artifact lives outside `base` (at `artifact_file`), so `tomcat::prepare` recreating
|
||||
/// the runtime directory does not delete what was just built.
|
||||
fn build_project_war(
|
||||
root: &std::path::Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
@@ -268,10 +272,7 @@ fn build_project_war(
|
||||
.iter()
|
||||
.find(|a| a.name == name)
|
||||
.ok_or_else(|| IdeError::invalid(format!("No artifact named {name} in Project Structure › Artifacts")))?;
|
||||
let war = base.join("artifact").join(format!(
|
||||
"{}.war",
|
||||
name.split(':').next().unwrap_or(name).replace(|c: char| !c.is_alphanumeric() && c != '-', "_")
|
||||
));
|
||||
let target = compile::artifact_file(root, artifact);
|
||||
let plan = compile::structure_war_plan(
|
||||
root,
|
||||
&ps,
|
||||
@@ -279,7 +280,7 @@ fn build_project_war(
|
||||
jdk.as_ref(),
|
||||
&settings.languages.java.language_level,
|
||||
artifact,
|
||||
&war,
|
||||
None,
|
||||
cache,
|
||||
)?;
|
||||
let result = compile::run(root, &plan, &ide_core::CancellationToken::new(), &|_| {})?;
|
||||
@@ -298,7 +299,7 @@ fn build_project_war(
|
||||
}
|
||||
std::fs::create_dir_all(base)?;
|
||||
std::fs::write(base.join("artifact-id.txt"), format!("{PROJECT_ARTIFACT}{name}"))?;
|
||||
std::fs::write(base.join("artifact-path.txt"), war.to_string_lossy().as_bytes())?;
|
||||
std::fs::write(base.join("artifact-path.txt"), target.to_string_lossy().as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -330,8 +331,14 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective());
|
||||
let artifacts = ide_build::web::artifacts(&project.root, &model);
|
||||
let settings = project.settings.effective();
|
||||
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &settings);
|
||||
let mut artifacts = ide_build::web::artifacts(&project.root, &model);
|
||||
if model.maven.is_none() && model.gradle.is_empty() {
|
||||
let detected = project.detected_roots.read().clone();
|
||||
let (ps, _, _) = crate::ops::build::structure_inputs(&project.root, &settings, &detected);
|
||||
artifacts.extend(project_web_artifacts(&ps));
|
||||
}
|
||||
let id = config
|
||||
.extras
|
||||
.params
|
||||
@@ -343,7 +350,6 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I
|
||||
let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?;
|
||||
let base = ide_run::tomcat::state_dir(&base, &config);
|
||||
if let Some(name) = id.strip_prefix(PROJECT_ARTIFACT) {
|
||||
let settings = project.settings.effective();
|
||||
let detected = project.detected_roots.read().clone();
|
||||
build_project_war(&project.root, &settings, &detected, name, &base, &project.build_cache_dir())?;
|
||||
return Ok(None);
|
||||
@@ -465,3 +471,100 @@ ide_command::domain!(
|
||||
run_tomcat_sync,
|
||||
run_tomcat_update,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::settings::{ArtifactConfig, ArtifactKind, FacetConfig, Settings};
|
||||
use std::io::Write;
|
||||
|
||||
fn fake_tomcat(home: &std::path::Path) {
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::create_dir_all(home.join("conf")).unwrap();
|
||||
std::fs::create_dir_all(home.join("lib")).unwrap();
|
||||
std::fs::write(home.join("bin/catalina.sh"), "").unwrap();
|
||||
std::fs::write(home.join("bin/catalina.bat"), "").unwrap();
|
||||
let server = "<Server port='8005'><Service><Connector port='8080'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
|
||||
std::fs::write(home.join("conf/server.xml"), server).unwrap();
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(home.join("lib/catalina.jar")).unwrap());
|
||||
zip.start_file("org/apache/catalina/util/ServerInfo.properties", zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(b"server.info=Apache Tomcat/10.1").unwrap();
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_structure_war_and_exploded_artifacts_survive_tomcat_prepare() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("EJSH");
|
||||
let cache = root.parent().unwrap().join("cache");
|
||||
let tomcat_home = root.parent().unwrap().join("tomcat-home");
|
||||
fake_tomcat(&tomcat_home);
|
||||
|
||||
std::fs::create_dir_all(root.join("WebRoot/WEB-INF")).unwrap();
|
||||
std::fs::write(root.join("WebRoot/WEB-INF/web.xml"), "<web-app/>").unwrap();
|
||||
std::fs::write(root.join("WebRoot/index.jsp"), "<h1>ok</h1>").unwrap();
|
||||
|
||||
let mut settings = Settings::default();
|
||||
settings.project_structure.facets.push(FacetConfig {
|
||||
kind: "web".into(),
|
||||
module: ".".into(),
|
||||
descriptor: "WebRoot/WEB-INF/web.xml".into(),
|
||||
web_root: "WebRoot".into(),
|
||||
});
|
||||
settings.project_structure.artifacts.push(ArtifactConfig {
|
||||
name: "EJSH:war exploded".into(),
|
||||
kind: ArtifactKind::WarExploded,
|
||||
module: ".".into(),
|
||||
output_directory: "out/artifacts/EJSH_war_exploded".into(),
|
||||
..Default::default()
|
||||
});
|
||||
settings.project_structure.artifacts.push(ArtifactConfig {
|
||||
name: "EJSH:war".into(),
|
||||
kind: ArtifactKind::War,
|
||||
module: ".".into(),
|
||||
output_directory: "out/artifacts/EJSH_war".into(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
for (artifact_name, expect_exploded_dir) in [("EJSH:war exploded", true), ("EJSH:war", false)] {
|
||||
let mut config = RunConfig {
|
||||
id: format!("tomcat-{artifact_name}"),
|
||||
name: "Tomcat".into(),
|
||||
kind: "tomcat".into(),
|
||||
command: "catalina".into(),
|
||||
args: vec![],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
config.extras.params.insert("tomcatHome".into(), tomcat_home.to_string_lossy().into_owned());
|
||||
config.extras.params.insert("deployment".into(), "artifact".into());
|
||||
config.extras.params.insert("artifact".into(), format!("{PROJECT_ARTIFACT}{artifact_name}"));
|
||||
config.extras.params.insert("artifactName".into(), "EJSH".into());
|
||||
config.extras.params.insert("httpPort".into(), "8080".into());
|
||||
|
||||
let base = ide_run::tomcat::effective_base_dir(&root, &cache, &config).unwrap();
|
||||
let state = ide_run::tomcat::state_dir(&base, &config);
|
||||
build_project_war(&root, &settings, &[], artifact_name, &state, &cache.join("build")).unwrap();
|
||||
|
||||
// `prepare` deletes and recreates `base`; the built artifact must remain intact.
|
||||
ide_run::tomcat::prepare(&root, &cache, &mut config).unwrap();
|
||||
let catalina_base = std::path::PathBuf::from(&config.env["CATALINA_BASE"]);
|
||||
let ctx = std::fs::read_to_string(catalina_base.join("conf/Catalina/localhost/EJSH.xml")).unwrap();
|
||||
if expect_exploded_dir {
|
||||
let expected = root.join("out/artifacts/EJSH_war_exploded");
|
||||
assert!(expected.join("WEB-INF/web.xml").is_file());
|
||||
assert!(ctx.contains(expected.to_string_lossy().as_ref()), "{ctx}");
|
||||
} else {
|
||||
assert!(root.join("out/artifacts/EJSH_war/EJSH.war").is_file());
|
||||
assert!(catalina_base.join("deployment/WEB-INF/web.xml").is_file());
|
||||
assert!(ctx.contains("deployment"), "{ctx}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Docker and Compose run targets: the configuration becomes a local run of the
|
||||
//! docker CLI (see `ide_remote::docker`).
|
||||
//! Docker, Compose and WSL run targets: the configuration becomes a local run of the
|
||||
//! docker CLI (see `ide_remote::docker`) or of `wsl.exe` (see `ide_remote::wsl`).
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
@@ -73,6 +73,37 @@ pub(super) async fn prepare(
|
||||
.await
|
||||
}
|
||||
|
||||
/// `config` rewritten to run in `target`'s WSL distribution.
|
||||
pub(super) async fn prepare_wsl(
|
||||
host: &Host,
|
||||
root: &Path,
|
||||
target: RunTarget,
|
||||
config: RunConfig,
|
||||
) -> IdeResult<RunConfig> {
|
||||
if !cfg!(windows) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Run target '{}' is a WSL distribution: WSL needs Windows",
|
||||
target.name
|
||||
)));
|
||||
}
|
||||
let root = root.to_path_buf();
|
||||
host.blocking(move || {
|
||||
let linux_root = ide_remote::wsl::project_root(&target, &root)?;
|
||||
let file_env = env_files(&root, &config)?;
|
||||
let inherited = std::env::var("WSLENV").ok();
|
||||
ide_remote::wsl::wsl_config(
|
||||
&config,
|
||||
&target,
|
||||
&root,
|
||||
&linux_root,
|
||||
ide_core::wsl::EXE,
|
||||
&file_env,
|
||||
inherited.as_deref(),
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The project can only be bind-mounted from a daemon on this machine.
|
||||
pub(crate) fn require_local(endpoint: &DockerEndpoint, target: &RunTarget) -> IdeResult<()> {
|
||||
if !ide_docker::endpoint_is_local(endpoint)? {
|
||||
|
||||
@@ -12,7 +12,7 @@ use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
pub mod container_python;
|
||||
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh};
|
||||
pub use container_python::{ContainerPython, sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons};
|
||||
|
||||
/// Executables found for "run this file", and where single files are compiled to.
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
//! A snapshot runs the target's Python once in a new container (the image's entrypoint
|
||||
//! and the service's dependencies skipped), then copies its `sys.path` folders out of
|
||||
//! the stopped container with `docker cp`. Nothing is installed in the container.
|
||||
//!
|
||||
//! A WSL run target's snapshot only records its Python's `sys.path`: the folders are read
|
||||
//! in place through `\\wsl.localhost\<distro>`.
|
||||
|
||||
use crate::Host;
|
||||
use crate::project::Project;
|
||||
@@ -23,6 +26,8 @@ use std::time::Duration;
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
|
||||
const COPY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
|
||||
const QUICK: Duration = Duration::from_secs(30);
|
||||
/// Starting the distribution may come first.
|
||||
const WSL_TIMEOUT: Duration = Duration::from_secs(2 * 60);
|
||||
|
||||
/// The project interpreter when it is a run target's.
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
@@ -34,8 +39,10 @@ pub struct ContainerPython {
|
||||
pub name: String,
|
||||
/// The Python version of the snapshot in use; `None`: no snapshot yet.
|
||||
pub version: Option<String>,
|
||||
/// The image the snapshot was copied from.
|
||||
/// The image the snapshot was copied from; `None` for WSL.
|
||||
pub image: Option<String>,
|
||||
/// The interpreter's path in the container or distribution.
|
||||
pub executable: Option<String>,
|
||||
/// The copied library folders on this machine.
|
||||
pub folders: Vec<IpcPath>,
|
||||
/// Packages of the snapshot (read-only).
|
||||
@@ -108,22 +115,25 @@ pub(crate) fn library_group(host: &Host, root: &Path, settings: &Settings) -> Op
|
||||
}
|
||||
|
||||
/// The project interpreter when it is a Docker or Compose run target's, with its snapshot.
|
||||
/// Off the calling thread: a WSL interpreter's packages are read over `\\wsl.localhost`.
|
||||
#[command(trust = trusted)]
|
||||
pub fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
|
||||
pub async fn sdk_container_python(host: &Host, window: &str) -> IdeResult<Option<ContainerPython>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
Ok(describe(host, &project.root, &project.settings.effective()))
|
||||
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
|
||||
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
|
||||
}
|
||||
|
||||
fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPython> {
|
||||
fn describe(dirs: &Dirs, root: &Path, settings: &Settings) -> Option<ContainerPython> {
|
||||
let target = settings.languages.python.run_target()?;
|
||||
let name = settings.run_targets.iter().find(|t| t.id == target).map(|t| t.name.clone()).unwrap_or_default();
|
||||
let dir = Dirs::of(host).target(root, target);
|
||||
let dir = dirs.target(root, target);
|
||||
let mut out = ContainerPython {
|
||||
target: target.to_owned(),
|
||||
name,
|
||||
version: None,
|
||||
image: None,
|
||||
executable: None,
|
||||
folders: Vec::new(),
|
||||
packages: Vec::new(),
|
||||
updating: updating(&dir),
|
||||
@@ -132,7 +142,8 @@ fn describe(host: &Host, root: &Path, settings: &Settings) -> Option<ContainerPy
|
||||
out.folders = snapshots::local_folders(&dir, &snapshot).into_iter().map(Into::into).collect();
|
||||
out.packages = snapshots::packages(&dir, &snapshot);
|
||||
out.version = Some(snapshot.probe.version);
|
||||
out.image = Some(snapshot.image);
|
||||
out.executable = Some(snapshot.probe.executable);
|
||||
out.image = snapshot.distro.is_none().then_some(snapshot.image);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
@@ -144,7 +155,8 @@ pub async fn sdk_container_python_refresh(host: &Host, window: &str) -> IdeResul
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
update(Dirs::of(host), &project, true).await?;
|
||||
Ok(describe(host, &project.root, &project.settings.effective()))
|
||||
let (dirs, root, settings) = (Dirs::of(host), project.root.clone(), project.settings.effective());
|
||||
host.blocking(move || Ok(describe(&dirs, &root, &settings))).await
|
||||
}
|
||||
|
||||
/// Takes a snapshot when the project interpreter is a run target's and the current image
|
||||
@@ -154,13 +166,22 @@ pub(crate) fn ensure(host: &Host, project: &Arc<Project>) {
|
||||
return;
|
||||
}
|
||||
let (dirs, project) = (Dirs::of(host), project.clone());
|
||||
let settings = project.settings.effective();
|
||||
let wsl = settings
|
||||
.languages
|
||||
.python
|
||||
.run_target()
|
||||
.and_then(|id| settings.run_targets.iter().find(|t| t.id == id))
|
||||
.is_some_and(|t| t.kind == RunTargetKind::Wsl);
|
||||
let title =
|
||||
if wsl { "Cannot read the WSL Python's libraries" } else { "Cannot copy the container's Python libraries" };
|
||||
host.runtime.spawn(async move {
|
||||
if let Err(e) = update(dirs, &project, false).await
|
||||
&& e.kind != ide_core::error::ErrorKind::Cancelled
|
||||
{
|
||||
project.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Warning,
|
||||
title: "Cannot copy the container's Python libraries".into(),
|
||||
title: title.into(),
|
||||
body: Some(e.message),
|
||||
});
|
||||
}
|
||||
@@ -173,7 +194,7 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
|
||||
let target = ide_remote::service::run_target(&settings, id)?;
|
||||
if target.kind == RunTargetKind::Ssh {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Run target '{}' runs over SSH: only a Docker or Compose run target can be the project interpreter",
|
||||
"Run target '{}' is an SSH host: only a Docker, Compose or WSL run target can be the project interpreter",
|
||||
target.name
|
||||
)));
|
||||
}
|
||||
@@ -182,7 +203,10 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
|
||||
return Ok(());
|
||||
}
|
||||
let _done = Updating(dir.clone());
|
||||
let endpoint = crate::ops::run::container::endpoint(&dirs.data, &target)?;
|
||||
let endpoint = match target.kind {
|
||||
RunTargetKind::Wsl => None,
|
||||
_ => Some(crate::ops::run::container::endpoint(&dirs.data, &target)?),
|
||||
};
|
||||
let task = TaskId::next();
|
||||
let title = format!("Python libraries of {}", target.name);
|
||||
let (root, sink) = (project.root.clone(), project.sink.clone());
|
||||
@@ -198,7 +222,11 @@ async fn update(dirs: Dirs, project: &Arc<Project>, force: bool) -> IdeResult<()
|
||||
};
|
||||
let report = progress.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
take(&endpoint, &root, &target, &dir, &dirs.cache, force, &|message| report(message, false))
|
||||
let report = |message: &str| report(message, false);
|
||||
match endpoint {
|
||||
Some(endpoint) => take(&endpoint, &root, &target, &dir, &dirs.cache, force, &report),
|
||||
None => take_wsl(&root, &target, &dir, &dirs.cache, &report),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
@@ -288,6 +316,7 @@ fn take(
|
||||
image: image.clone(),
|
||||
probe,
|
||||
folders,
|
||||
distro: None,
|
||||
};
|
||||
snapshots::write(&partial, &snapshot)?;
|
||||
if dir.exists() {
|
||||
@@ -298,6 +327,72 @@ fn take(
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Records where the WSL target's Python finds its libraries and makes that the snapshot in
|
||||
/// use; `false` when nothing changed. Nothing is copied, so packages installed later show up.
|
||||
fn take_wsl(
|
||||
root: &Path,
|
||||
target: &RunTarget,
|
||||
target_dir: &Path,
|
||||
cache: &Path,
|
||||
progress: &dyn Fn(&str),
|
||||
) -> IdeResult<bool> {
|
||||
if !cfg!(windows) {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Run target '{}' is a WSL distribution: WSL needs Windows",
|
||||
target.name
|
||||
)));
|
||||
}
|
||||
let linux_root = ide_remote::wsl::project_root(target, root)?;
|
||||
let distro = target.distro.trim();
|
||||
progress("Starting the WSL Python");
|
||||
let out = ide_core::wsl::exec(distro, &[ide_remote::wsl::python(target), "-c", snapshots::PROBE], WSL_TIMEOUT)?;
|
||||
let probe = snapshots::parse_probe(&out)?;
|
||||
let id = format!("wsl-{}-{}", probe.executable, probe.version);
|
||||
let snapshot = Snapshot {
|
||||
image: id.clone(),
|
||||
folders: wsl_folders(&probe, &linux_root),
|
||||
neutral_python: snapshots::neutral_python(cache, &probe.version),
|
||||
distro: Some(distro.to_owned()),
|
||||
probe,
|
||||
};
|
||||
// What the language server is given: the probe's other details (its raw `sys.path` order,
|
||||
// say) are kept in the snapshot but don't restart it.
|
||||
let libraries = |s: &Snapshot| (s.image.clone(), s.folders.clone(), s.neutral_python.clone(), s.distro.clone());
|
||||
let changed = snapshots::current(target_dir).map(|(_, s)| libraries(&s)) != Some(libraries(&snapshot));
|
||||
let dir = target_dir.join(snapshots::dir_name(&id));
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
snapshots::write(&dir, &snapshot)?;
|
||||
snapshots::make_current(target_dir, &id)?;
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// The library folders of a WSL Python: as a container's, plus a virtualenv's in the project
|
||||
/// (`.venv/lib/python3.12/site-packages`), which a container mount would hold anyway.
|
||||
fn wsl_folders(probe: &snapshots::Probe, linux_root: &str) -> Vec<String> {
|
||||
let root = linux_root.trim_end_matches('/');
|
||||
let in_project = |f: &str| root.is_empty() || f == root || f.starts_with(&format!("{root}/"));
|
||||
let packages = |f: &str| f.split('/').any(|c| c == "site-packages" || c == "dist-packages");
|
||||
snapshots::folders_to_copy(probe, "").into_iter().filter(|f| !in_project(f) || packages(f)).collect()
|
||||
}
|
||||
|
||||
/// The Pythons found in a WSL distribution, for Add Python Interpreter: the ones on its
|
||||
/// `PATH`, in `/usr/bin` and `/usr/local/bin`, pyenv's, and the project's virtualenv. Empty off Windows.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn sdk_wsl_pythons(host: &Host, window: &str, distro: String) -> IdeResult<Vec<String>> {
|
||||
host.require_trust(window)?;
|
||||
if !cfg!(windows) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let root = host.project(window)?.root.clone();
|
||||
host.blocking(move || {
|
||||
let distro = distro.trim();
|
||||
let linux_root = ide_core::wsl::linux_path(&root, distro).unwrap_or_default();
|
||||
let script = ["sh", "-c", ide_remote::wsl::FIND_PYTHONS, "sh", &linux_root];
|
||||
Ok(ide_remote::wsl::parse_pythons(&ide_core::wsl::exec(distro, &script, WSL_TIMEOUT)?))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Distinguishes probe containers.
|
||||
fn unique() -> String {
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
@@ -306,4 +401,23 @@ fn unique() -> String {
|
||||
format!("{:x}-{}-{}", secs & 0xff_ffff, std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))
|
||||
}
|
||||
|
||||
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh);
|
||||
#[cfg(test)]
|
||||
mod wsl_tests {
|
||||
#[test]
|
||||
fn a_virtualenv_in_the_project_is_read_and_its_sources_are_not() {
|
||||
let probe = super::snapshots::Probe {
|
||||
version: "3.12.3".into(),
|
||||
executable: "/mnt/c/p/.venv/bin/python".into(),
|
||||
stdlib: vec![Some("/usr/lib/python3.12".into())],
|
||||
path: ["/mnt/c/p/src", "/usr/lib/python3.12", "/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
|
||||
.map(String::from)
|
||||
.to_vec(),
|
||||
};
|
||||
assert_eq!(
|
||||
super::wsl_folders(&probe, "/mnt/c/p"),
|
||||
["/mnt/c/p/.venv/lib/python3.12/site-packages", "/opt/extra"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(sdk_container_python: sdk_container_python, sdk_container_python_refresh, sdk_wsl_pythons);
|
||||
@@ -7,19 +7,7 @@ use ide_vcs::FileStatus;
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_status(host: &Host, window: &str) -> IdeResult<Vec<FileStatus>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
let repos = project.repos();
|
||||
if repos.is_empty() {
|
||||
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
}
|
||||
repos.status()
|
||||
})
|
||||
.await
|
||||
host.blocking(move || merged_status(&project, None)).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -42,19 +30,67 @@ pub async fn vcs_ignored_files(host: &Host, window: &str) -> IdeResult<Vec<FileS
|
||||
pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::PathBuf>) -> IdeResult<Vec<FileStatus>> {
|
||||
// `paths` that belong to no repository are ignored, and an empty list is the full status.
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let settings = project.settings.effective();
|
||||
let repos = project.repos();
|
||||
if repos.is_empty() {
|
||||
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
|
||||
host.blocking(move || merged_status(&project, Some(&paths))).await
|
||||
}
|
||||
|
||||
/// The Git repositories' changes and those of the non-Git working copies, each file reported
|
||||
/// by the backend [`crate::Project::backend_of`] routes it to. `paths` narrows them (empty:
|
||||
/// everything). A working copy that cannot answer (an unreachable server) is logged and
|
||||
/// skipped while another backend answered, so it never hides the Git changes.
|
||||
fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>) -> IdeResult<Vec<FileStatus>> {
|
||||
let settings = project.settings.effective();
|
||||
let repos = project.repos();
|
||||
let backends = project.backends();
|
||||
if repos.is_empty() && backends.is_empty() {
|
||||
return Err(ide_core::IdeError::unavailable("project is not a git repository"));
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
}
|
||||
let mut status = if repos.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
match paths {
|
||||
Some(paths) => repos.status_paths(paths)?,
|
||||
None => repos.status()?,
|
||||
}
|
||||
for r in repos.all() {
|
||||
r.set_ignored_names(settings.ignored_names());
|
||||
r.set_cli_status(settings.vcs.git.cli_status);
|
||||
};
|
||||
if backends.is_empty() {
|
||||
return Ok(status);
|
||||
}
|
||||
// Routed from these snapshots: one lookup per entry, no locks taken again.
|
||||
let owner = |f: &FileStatus| crate::project::backend_for(&backends, &repos, &f.path).map(|b| b.root());
|
||||
status.retain(|f| owner(f).is_none());
|
||||
let mut answered = !repos.is_empty();
|
||||
let mut failure = None;
|
||||
for backend in &backends {
|
||||
let changes = match paths.filter(|p| !p.is_empty()) {
|
||||
Some(paths) => {
|
||||
let mine: Vec<_> = paths.iter().filter(|p| p.starts_with(backend.root())).cloned().collect();
|
||||
if mine.is_empty() {
|
||||
answered = true;
|
||||
continue;
|
||||
}
|
||||
backend.status_paths(&mine)
|
||||
}
|
||||
None => backend.status(),
|
||||
};
|
||||
match changes {
|
||||
Ok(changes) => {
|
||||
answered = true;
|
||||
status.extend(changes.into_iter().filter(|f| owner(f) == Some(backend.root())));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("status of {}: {e}", backend.root().display());
|
||||
failure = Some(e);
|
||||
}
|
||||
}
|
||||
repos.status_paths(&paths)
|
||||
})
|
||||
.await
|
||||
}
|
||||
match failure {
|
||||
Some(e) if !answered => Err(e),
|
||||
_ => Ok(status),
|
||||
}
|
||||
}
|
||||
|
||||
pub mod commands;
|
||||
|
||||
@@ -94,13 +94,14 @@ async fn revision_text(
|
||||
project: &Option<std::sync::Arc<Project>>,
|
||||
external: &Option<std::sync::Arc<ide_vcs::Repo>>,
|
||||
path: &Path,
|
||||
f: impl FnOnce(&ide_vcs::Repo) -> IdeResult<T>,
|
||||
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
match project {
|
||||
Some(project) => project.with_log_repo_of(path, f),
|
||||
Some(project) => project.with_log_backend_of(path, f),
|
||||
None => f(external
|
||||
.as_ref()
|
||||
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?),
|
||||
.ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?
|
||||
.as_ref()),
|
||||
}
|
||||
}
|
||||
let (text_encoding, charset) = match &encoding {
|
||||
@@ -148,20 +149,46 @@ impl LogAccess {
|
||||
.with_log_repo_at(at, f)
|
||||
}
|
||||
|
||||
/// The non-Git working copy `at` names (see [`Project::backend_at`]).
|
||||
fn backend(&self, at: Option<&Path>) -> Option<std::sync::Arc<dyn Backend>> {
|
||||
if self.external.is_some() {
|
||||
return None;
|
||||
}
|
||||
self.project.as_ref().and_then(|p| p.backend_at(at))
|
||||
}
|
||||
|
||||
/// `with_log_repo_at` through the backend-agnostic Changes-view surface.
|
||||
fn with_log_backend_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
|
||||
if let Some(backend) = self.backend(at) {
|
||||
return f(backend.as_ref());
|
||||
}
|
||||
self.with_log_repo_at(at, |r| f(r as &dyn Backend))
|
||||
}
|
||||
|
||||
/// `with_log_repo_at` for a Git-only read: a non-Git working copy answers `T::default()`
|
||||
/// (no refs, users, branches) so its log and branch widget still work.
|
||||
fn with_git_log_or_default<T: Default>(
|
||||
&self,
|
||||
at: Option<&Path>,
|
||||
f: impl FnOnce(&Repo) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
if self.backend(at).is_some() {
|
||||
return Ok(T::default());
|
||||
}
|
||||
self.with_log_repo_at(at, f)
|
||||
}
|
||||
}
|
||||
|
||||
/// A repository of the project (IDEA's VCS root).
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[derive(Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct VcsRoot {
|
||||
/// Worktree root.
|
||||
pub root: ide_core::IpcPath,
|
||||
/// Root representing all mapped worktrees of the same Git repository in branch lists.
|
||||
pub branch_root: ide_core::IpcPath,
|
||||
/// The version control system holding it.
|
||||
pub kind: VcsKind,
|
||||
/// Merge / rebase / cherry-pick / revert in progress.
|
||||
pub operation: Option<String>,
|
||||
/// The current rebase uses Git's interactive mode.
|
||||
@@ -190,6 +217,10 @@ pub struct VcsRoot {
|
||||
/// Conflicts staged during the current operation that can be reopened.
|
||||
#[serde(default)]
|
||||
pub resolved_conflicts: Vec<ide_core::IpcPath>,
|
||||
/// The repository's worktree or git directory is missing or on an unmounted volume.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub unavailable: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
@@ -422,14 +453,32 @@ fn per_repo(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `per_repo` through the backend-agnostic Changes-view surface.
|
||||
/// `per_repo` through the backend-agnostic Changes-view surface: the paths of a non-Git
|
||||
/// working copy go to it, the rest to the Git repositories as before.
|
||||
fn per_backend(
|
||||
project: &Project,
|
||||
paths: &[PathBuf],
|
||||
recorded: Option<&str>,
|
||||
f: impl Fn(&dyn Backend, &[PathBuf]) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
per_repo(project, paths, recorded, |r, paths| f(r as &dyn Backend, paths))
|
||||
let mut git: Vec<PathBuf> = Vec::new();
|
||||
let mut groups: Vec<(std::sync::Arc<dyn Backend>, Vec<PathBuf>)> = Vec::new();
|
||||
for path in paths {
|
||||
match project.backend_of(path) {
|
||||
Some(backend) => match groups.iter_mut().find(|(b, _)| b.root() == backend.root()) {
|
||||
Some((_, mine)) => mine.push(path.clone()),
|
||||
None => groups.push((backend, vec![path.clone()])),
|
||||
},
|
||||
None => git.push(path.clone()),
|
||||
}
|
||||
}
|
||||
for (backend, mine) in &groups {
|
||||
project.backend_recorded(backend.as_ref(), recorded, |b| f(b, mine))?;
|
||||
}
|
||||
if git.is_empty() && !groups.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
per_repo(project, &git, recorded, |r, paths| f(r as &dyn Backend, paths))
|
||||
}
|
||||
|
||||
fn with_shelf_batch<T>(project: &Project, batch: Option<String>, operation: impl FnOnce() -> T) -> T {
|
||||
@@ -531,29 +580,58 @@ pub async fn vcs_detected_roots(host: &Host, window: &str) -> IdeResult<Vec<Path
|
||||
blocking(move || project.detected_repository_roots()).await
|
||||
}
|
||||
|
||||
fn unavailable_vcs_root(root: &Path) -> VcsRoot {
|
||||
VcsRoot {
|
||||
root: root.into(),
|
||||
branch_root: root.into(),
|
||||
kind: VcsKind::Git,
|
||||
operation: None,
|
||||
interactive_rebase: false,
|
||||
head: None,
|
||||
head_commit: None,
|
||||
shallow: false,
|
||||
lfs: false,
|
||||
uninitialized_submodules: Vec::new(),
|
||||
has_remotes: None,
|
||||
resolved_conflicts: Vec::new(),
|
||||
unavailable: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's repositories, the primary one first.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
let project = host.project(window)?;
|
||||
let repos = project.repos();
|
||||
let backends = project.backends();
|
||||
let trusted = project.is_trusted();
|
||||
blocking(move || {
|
||||
let primary = repos.primary().map(|r| r.root().to_path_buf());
|
||||
let mut all: Vec<_> = repos.all().iter().collect();
|
||||
all.sort_by_key(|r| Some(r.root()) != primary.as_deref());
|
||||
let roots: Vec<_> = all.into_iter().map(|repo| (repo, repo.metadata_dirs().ok())).collect();
|
||||
let roots: Vec<_> = all
|
||||
.into_iter()
|
||||
.map(|repo| {
|
||||
let dirs = repo.check_valid().ok().and_then(|()| repo.metadata_dirs().ok());
|
||||
let available = dirs.is_some() && !repo.is_stale();
|
||||
(repo, available, dirs)
|
||||
})
|
||||
.collect();
|
||||
let mut branch_roots = std::collections::HashMap::new();
|
||||
for (repo, dirs) in &roots {
|
||||
if let Some([git_dir, common_dir]) = dirs {
|
||||
for (repo, available, dirs) in &roots {
|
||||
if *available && let Some([git_dir, common_dir]) = dirs {
|
||||
let first = branch_roots.entry(common_dir).or_insert(repo.root());
|
||||
if git_dir == common_dir {
|
||||
*first = repo.root();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(roots
|
||||
let mut roots: Vec<VcsRoot> = roots
|
||||
.iter()
|
||||
.map(|(r, dirs)| {
|
||||
.map(|(r, available, dirs)| {
|
||||
if !available {
|
||||
return unavailable_vcs_root(r.root());
|
||||
}
|
||||
let branch_root = dirs.as_ref().and_then(|[_, common_dir]| branch_roots.get(common_dir));
|
||||
let (head, head_commit) = r.head().unwrap_or_default();
|
||||
let operation = r.operation().ok().flatten();
|
||||
@@ -565,14 +643,20 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.collect();
|
||||
let has_remotes = trusted.then(|| r.has_remotes().ok()).flatten();
|
||||
let shallow = r.is_shallow().unwrap_or(false);
|
||||
if r.is_stale() {
|
||||
return unavailable_vcs_root(r.root());
|
||||
}
|
||||
VcsRoot {
|
||||
root: r.root().into(),
|
||||
branch_root: branch_root.copied().unwrap_or_else(|| r.root()).into(),
|
||||
kind: VcsKind::Git,
|
||||
operation,
|
||||
interactive_rebase,
|
||||
head,
|
||||
head_commit,
|
||||
shallow: r.is_shallow().unwrap_or(false),
|
||||
shallow,
|
||||
lfs: r.uses_lfs(),
|
||||
uninitialized_submodules: r
|
||||
.uninitialized_submodules()
|
||||
@@ -580,11 +664,21 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
.iter()
|
||||
.map(|path| ide_core::ipc_path::to_ipc(path))
|
||||
.collect(),
|
||||
has_remotes: trusted.then(|| r.has_remotes().ok()).flatten(),
|
||||
has_remotes,
|
||||
resolved_conflicts,
|
||||
unavailable: false,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
.collect();
|
||||
// A non-Git working copy shows its own head (a stream, `trunk`) where Git shows the branch.
|
||||
roots.extend(backends.iter().map(|b| VcsRoot {
|
||||
root: b.root().into(),
|
||||
branch_root: b.root().into(),
|
||||
kind: b.kind(),
|
||||
head: b.head_label(),
|
||||
..VcsRoot::default()
|
||||
}));
|
||||
Ok(roots)
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -592,7 +686,13 @@ pub async fn vcs_roots(host: &Host, window: &str) -> IdeResult<Vec<VcsRoot>> {
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_branch_info(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<BranchInfo> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())).await
|
||||
blocking(move || {
|
||||
if let Some(backend) = project.backend(repo.as_deref()) {
|
||||
return Ok(BranchInfo { head: backend.head_label(), ..BranchInfo::default() });
|
||||
}
|
||||
project.with_log_repo_at(repo.as_deref(), |r| r.branch_info())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -863,6 +963,9 @@ pub async fn vcs_log(host: &Host, window: &str, repo: Option<PathBuf>, query: Lo
|
||||
let cancel =
|
||||
request.map_or_else(ide_core::CancellationToken::new, |id| host.begin_project_read_request(window, id));
|
||||
let result = blocking(move || {
|
||||
if let Some(backend) = project.backend(repo.as_deref()) {
|
||||
return backend.log(&query, &cancel);
|
||||
}
|
||||
project.with_log_repo_at(repo.as_deref(), |r| {
|
||||
r.enable_log_index(&project.cache);
|
||||
(r as &dyn Backend).log(&query, &cancel)
|
||||
@@ -900,13 +1003,13 @@ pub async fn vcs_log_refs(
|
||||
repo: Option<PathBuf>,
|
||||
) -> IdeResult<std::collections::BTreeMap<String, String>> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_refs())).await
|
||||
blocking(move || project.with_git_log_or_default(repo.as_deref(), |r| r.log_refs())).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_log_users(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<String>> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_users())).await
|
||||
blocking(move || project.with_git_log_or_default(repo.as_deref(), |r| r.log_users())).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -936,7 +1039,7 @@ pub async fn vcs_log_details(
|
||||
revision: String,
|
||||
) -> IdeResult<LogDetails> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.log_details(&revision))).await
|
||||
blocking(move || project.with_log_backend_at(repo.as_deref(), |b| b.log_details(&revision))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -950,6 +1053,9 @@ pub async fn vcs_log_details_batch(
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = blocking(move || {
|
||||
if let Some(backend) = project.backend(repo.as_deref()) {
|
||||
return revisions.iter().map(|revision| backend.log_details(revision)).collect();
|
||||
}
|
||||
project.with_log_repo_at(repo.as_deref(), |r| {
|
||||
r.enable_log_index(&project.cache);
|
||||
r.log_details_batch_cancellable(&revisions, &cancel)
|
||||
@@ -1093,13 +1199,23 @@ pub async fn vcs_commit_selection_changes(
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_branches(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Branch>> {
|
||||
let project = LogAccess::new(host, window, repo.as_deref());
|
||||
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.branches())).await
|
||||
blocking(move || match project.backend(repo.as_deref()) {
|
||||
Some(backend) => backend.branches(),
|
||||
None => project.with_log_repo_at(repo.as_deref(), |r| r.branches()),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_stashes(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<Vec<Stash>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.with_repo_at(repo.as_deref(), |r| r.stashes())).await
|
||||
blocking(move || {
|
||||
if project.backend_at(repo.as_deref()).is_some() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
project.with_repo_at(repo.as_deref(), |r| r.stashes())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -1303,6 +1419,15 @@ pub async fn vcs_checkout(
|
||||
let options = options.unwrap_or_default();
|
||||
blocking(move || {
|
||||
with_shelf_batch(&project, shelf_batch, || {
|
||||
// A non-Git working copy switches to another line of development (`svn switch`).
|
||||
if project.backend_at(repo.as_deref()).is_some() {
|
||||
if create {
|
||||
return Err(ide_core::IdeError::unavailable("creating a branch is not supported here"));
|
||||
}
|
||||
return project.with_backend_recorded(repo.as_deref(), Some("Switch"), |b| {
|
||||
b.switch_to(&branch).map(|()| CheckoutOutcome::Done)
|
||||
});
|
||||
}
|
||||
project.with_repo_recorded(repo.as_deref(), Some("Git checkout"), |r| {
|
||||
r.checkout_with(&branch, create, &options)
|
||||
})
|
||||
@@ -1802,6 +1927,15 @@ pub async fn vcs_remote(
|
||||
RemoteOp::PullLfs => Some("Git LFS pull"),
|
||||
_ => None,
|
||||
};
|
||||
// Update Project on a non-Git working copy is its own update (`svn update`, `p4 sync`).
|
||||
if matches!(op, RemoteOp::Pull { .. } | RemoteOp::UpdateProjectBranch { .. })
|
||||
&& project.backend_at(repo.as_deref()).is_some()
|
||||
{
|
||||
return with_shelf_batch(&project, shelf_batch, || {
|
||||
project
|
||||
.with_backend_recorded(repo.as_deref(), Some("Update"), |b| b.update(&cancel, &out).map(|()| None))
|
||||
});
|
||||
}
|
||||
with_shelf_batch(&project, shelf_batch, || {
|
||||
project.with_repo_recorded(repo.as_deref(), recorded, |r| match op {
|
||||
RemoteOp::Fetch { background: true, report, skip_remotes } => {
|
||||
@@ -3236,6 +3370,103 @@ pub async fn vcs_shelf_import(
|
||||
.await
|
||||
}
|
||||
|
||||
/// The changelists the non-Git working copy at `repo` keeps itself; `None` when the root
|
||||
/// (Git) leaves them to the IDE's lists ([`vcs_changelists_load`]).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelists(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
) -> IdeResult<Option<Vec<BackendChangelist>>> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || match project.backend_at(repo.as_deref()) {
|
||||
Some(backend) => backend.changelists(),
|
||||
None => Ok(None),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Creates a changelist of the working copy at `repo`; returns its id.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelist_create(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
name: String,
|
||||
comment: String,
|
||||
) -> IdeResult<String> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let id = project.with_backend_at(repo.as_deref(), |b| b.create_changelist(&name, &comment))?;
|
||||
project.vcs_changed();
|
||||
Ok(id)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelist_edit(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
id: String,
|
||||
name: String,
|
||||
comment: String,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_backend_at(repo.as_deref(), |b| b.edit_changelist(&id, &name, &comment))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelist_delete(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
id: String,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
project.with_backend_at(repo.as_deref(), |b| b.delete_changelist(&id))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Moves `paths` to changelist `id` of the working copy each belongs to.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn vcs_backend_changelist_move(host: &Host, window: &str, paths: Vec<PathBuf>, id: String) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let mut groups: Vec<(std::sync::Arc<dyn Backend>, Vec<PathBuf>)> = Vec::new();
|
||||
for path in paths {
|
||||
let backend = project.backend_of(&path).ok_or_else(|| {
|
||||
ide_core::IdeError::invalid(format!("{} is not in a working copy with changelists", path.display()))
|
||||
})?;
|
||||
match groups.iter_mut().find(|(b, _)| b.root() == backend.root()) {
|
||||
Some((_, mine)) => mine.push(path),
|
||||
None => groups.push((backend, vec![path])),
|
||||
}
|
||||
}
|
||||
for (backend, mine) in &groups {
|
||||
backend.move_to_changelist(mine, &id)?;
|
||||
}
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_changelists_load(host: &Host, window: &str) -> IdeResult<ChangelistState> {
|
||||
let project = host.project(window)?;
|
||||
@@ -3319,6 +3550,11 @@ ide_command::domain!(
|
||||
vcs_branch_info,
|
||||
vcs_check_incoming,
|
||||
vcs_branches,
|
||||
vcs_backend_changelists,
|
||||
vcs_backend_changelist_create,
|
||||
vcs_backend_changelist_edit,
|
||||
vcs_backend_changelist_delete,
|
||||
vcs_backend_changelist_move,
|
||||
vcs_changelists_load,
|
||||
vcs_changelists_save,
|
||||
vcs_checkout,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Code insight for Xcode projects: sourcekit-lsp doesn't read `.xcodeproj` / `.xcworkspace`
|
||||
//! files, it gets their build settings from a Build Server Protocol server named in
|
||||
//! `.bsp/*.json` or the legacy `buildServer.json`. The IDE neither bundles nor installs a BSP
|
||||
//! server: it offers to run the one on `PATH` (xcode-build-server, sourcekit-xcode-bsp) to write
|
||||
//! the config, then restarts sourcekit-lsp.
|
||||
//! server: when a trusted project has none, it runs the one on `PATH` (xcode-build-server,
|
||||
//! sourcekit-xcode-bsp) to write the config, keeps the config out of Git through
|
||||
//! `.git/info/exclude`, then restarts sourcekit-lsp.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -24,6 +25,39 @@ fn tool_args(tool: &str, container: &str) -> Vec<String> {
|
||||
vec!["config".into(), flag.into(), container.into()]
|
||||
}
|
||||
|
||||
/// The config `tool` writes at the project root.
|
||||
fn config_name(tool: &str) -> &'static str {
|
||||
if tool == "sourcekit-xcode-bsp" { ".bsp" } else { "buildServer.json" }
|
||||
}
|
||||
|
||||
fn git(root: &Path, args: &[&str]) -> Option<std::process::Output> {
|
||||
let mut cmd = Command::new("git");
|
||||
ide_core::process::prepare(&mut cmd).arg("-C").arg(root).args(args).stdin(Stdio::null());
|
||||
cmd.output().ok()
|
||||
}
|
||||
|
||||
/// Adds `name` (a file or folder at `root`) to the repository's `info/exclude`, so a generated
|
||||
/// machine-specific config doesn't show up as a change. Nothing when `root` isn't in a Git
|
||||
/// repository or `name` is already tracked or ignored. Returns whether it added the line.
|
||||
fn exclude_from_git(root: &Path, name: &str) -> std::io::Result<bool> {
|
||||
let ok = |args: &[&str]| git(root, args).filter(|o| o.status.success());
|
||||
let text = |o: std::process::Output| String::from_utf8_lossy(&o.stdout).trim_end_matches('\n').to_owned();
|
||||
let Some(exclude) = ok(&["rev-parse", "--git-path", "info/exclude"]).map(text) else { return Ok(false) };
|
||||
let prefix = ok(&["rev-parse", "--show-prefix"]).map(text).unwrap_or_default();
|
||||
if ok(&["ls-files", "--error-unmatch", "--", name]).is_some() || ok(&["check-ignore", "-q", "--", name]).is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let exclude = root.join(exclude);
|
||||
if let Some(dir) = exclude.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let before = std::fs::read_to_string(&exclude).unwrap_or_default();
|
||||
let sep = if before.is_empty() || before.ends_with('\n') { "" } else { "\n" };
|
||||
let mut file = std::fs::OpenOptions::new().create(true).append(true).open(&exclude)?;
|
||||
std::io::Write::write_all(&mut file, format!("{sep}/{prefix}{name}\n").as_bytes())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// An Xcode project without a BSP config, at the project root.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -69,8 +103,8 @@ pub fn xcode_bsp_setup(host: &Host, window: &str) -> IdeResult<Option<XcodeBspSe
|
||||
Ok(Some(XcodeBspSetup { container, tool }))
|
||||
}
|
||||
|
||||
/// Writes the BSP config at the project root with `tool`, then restarts the project's
|
||||
/// sourcekit-lsp so it reads it.
|
||||
/// Writes the BSP config at the project root with `tool`, adds it to `.git/info/exclude`
|
||||
/// ([`exclude_from_git`]), then restarts the project's sourcekit-lsp so it reads it.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, container: String) -> IdeResult<()> {
|
||||
if !TOOLS.contains(&tool.as_str()) {
|
||||
@@ -93,6 +127,10 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
|
||||
.stdin(Stdio::null());
|
||||
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("{tool}: {e}")))?;
|
||||
if out.status.success() {
|
||||
// Best effort: a config that shows up in `git status` is a nuisance, not a failure.
|
||||
if let Err(e) = exclude_from_git(&root, config_name(&tool)) {
|
||||
tracing::warn!("could not add {} to .git/info/exclude: {e}", config_name(&tool));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
@@ -136,6 +174,81 @@ mod tests {
|
||||
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj"), ["init"]);
|
||||
}
|
||||
|
||||
fn git_in(dir: &Path, args: &[&str]) {
|
||||
let out = Command::new("git").arg("-C").arg(dir).args(args).output().unwrap();
|
||||
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn exclude_file(repo: &Path) -> String {
|
||||
std::fs::read_to_string(repo.join(".git/info/exclude")).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excludes_the_generated_config_from_git_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path();
|
||||
git_in(repo, &["init", "-q"]);
|
||||
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
|
||||
assert!(exclude_from_git(repo, "buildServer.json").unwrap());
|
||||
assert!(exclude_file(repo).ends_with("\n/buildServer.json\n"), "{}", exclude_file(repo));
|
||||
// Now ignored: not added twice.
|
||||
assert!(!exclude_from_git(repo, "buildServer.json").unwrap());
|
||||
assert_eq!(exclude_file(repo).matches("buildServer.json").count(), 1);
|
||||
// sourcekit-xcode-bsp's folder.
|
||||
std::fs::create_dir(repo.join(".bsp")).unwrap();
|
||||
std::fs::write(repo.join(".bsp/x.json"), "{}").unwrap();
|
||||
assert!(exclude_from_git(repo, config_name("sourcekit-xcode-bsp")).unwrap());
|
||||
assert!(exclude_file(repo).ends_with("/buildServer.json\n/.bsp\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_tracked_and_ignored_configs_and_non_repos_alone() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// Not a Git repository: nothing to do, no `.git` created.
|
||||
let plain = tmp.path().join("plain");
|
||||
std::fs::create_dir(&plain).unwrap();
|
||||
assert!(!exclude_from_git(&plain, "buildServer.json").unwrap());
|
||||
assert!(!plain.join(".git").exists());
|
||||
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git_in(&repo, &["init", "-q"]);
|
||||
let before = exclude_file(&repo);
|
||||
// Tracked: the team shares it.
|
||||
std::fs::write(repo.join("buildServer.json"), "{}").unwrap();
|
||||
git_in(&repo, &["add", "buildServer.json"]);
|
||||
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
|
||||
// Already in .gitignore.
|
||||
git_in(&repo, &["rm", "-q", "--cached", "buildServer.json"]);
|
||||
std::fs::write(repo.join(".gitignore"), "buildServer.json\n").unwrap();
|
||||
assert!(!exclude_from_git(&repo, "buildServer.json").unwrap());
|
||||
assert_eq!(exclude_file(&repo), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excludes_the_config_of_a_project_in_a_subfolder_of_the_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path();
|
||||
git_in(repo, &["init", "-q"]);
|
||||
let ios = repo.join("apps/ios");
|
||||
std::fs::create_dir_all(&ios).unwrap();
|
||||
assert!(exclude_from_git(&ios, "buildServer.json").unwrap());
|
||||
assert!(exclude_file(repo).ends_with("/apps/ios/buildServer.json\n"));
|
||||
std::fs::write(ios.join("buildServer.json"), "{}").unwrap();
|
||||
// The line matches the file in the subfolder only.
|
||||
git_in(&ios, &["check-ignore", "-q", "buildServer.json"]);
|
||||
assert!(
|
||||
Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo)
|
||||
.args(["check-ignore", "-q", "buildServer.json"])
|
||||
.status()
|
||||
.unwrap()
|
||||
.code()
|
||||
== Some(1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_only_bundle_names_in_the_root() {
|
||||
assert!(is_container_name("App.xcworkspace") && is_container_name("App.xcodeproj"));
|
||||
|
||||
@@ -9,6 +9,22 @@ pub struct NavigationFiles {
|
||||
pub paths: Vec<ide_core::IpcPath>,
|
||||
pub indexing: bool,
|
||||
pub extensions: Vec<String>,
|
||||
/// In-scope files matching `extensions`; `paths` holds the first
|
||||
/// `MAX_NAVIGATION_FILES` of them.
|
||||
pub total: u32,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Discovery offers at most this many files; larger projects get navigation
|
||||
/// on the first ones instead of none.
|
||||
const MAX_NAVIGATION_FILES: usize = 20_000;
|
||||
|
||||
/// The first `limit` files `in_scope` accepts, and how many it accepts in all.
|
||||
fn first_in_scope(files: Vec<PathBuf>, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec<PathBuf>, usize) {
|
||||
let mut files: Vec<_> = files.into_iter().filter(in_scope).collect();
|
||||
let total = files.len();
|
||||
files.truncate(limit);
|
||||
(files, total)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -24,19 +40,25 @@ pub async fn plugin_navigation_files(
|
||||
blocking(move || {
|
||||
let extensions = plugins.navigation_extensions(&project.root);
|
||||
if extensions.is_empty() {
|
||||
return Ok(NavigationFiles { paths: vec![], indexing: false, extensions: vec![] });
|
||||
return Ok(NavigationFiles {
|
||||
paths: vec![],
|
||||
indexing: false,
|
||||
extensions: vec![],
|
||||
total: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
let indexing = project.index.status().indexing;
|
||||
let files = project.index.files_with_extensions(&extensions, 20_001);
|
||||
if files.len() > 20_000 {
|
||||
return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files"));
|
||||
}
|
||||
let files = project.index.files_with_extensions(&extensions, usize::MAX);
|
||||
// A project window group's members are project scope: their files are
|
||||
// in the group's index (the group root holds none of them).
|
||||
let members = crate::project::workspace_member_roots(&project.root);
|
||||
let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m));
|
||||
let (files, total) = first_in_scope(files, in_scope, MAX_NAVIGATION_FILES);
|
||||
Ok(NavigationFiles {
|
||||
paths: files.into_iter().filter(in_scope).map(Into::into).collect(),
|
||||
truncated: total > files.len(),
|
||||
total: u32::try_from(total).unwrap_or(u32::MAX),
|
||||
paths: files.into_iter().map(Into::into).collect(),
|
||||
indexing,
|
||||
extensions,
|
||||
})
|
||||
@@ -210,3 +232,19 @@ ide_command::domain!(
|
||||
plugin_navigation_invalidate,
|
||||
plugin_navigation_markers,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() {
|
||||
let files: Vec<PathBuf> = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
|
||||
let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3);
|
||||
// Out-of-scope files neither take a slot nor count toward the total.
|
||||
assert_eq!(total, 4);
|
||||
assert_eq!(kept, ["/p/0/f0.xml", "/p/0/f2.xml", "/p/0/f4.xml"].map(PathBuf::from));
|
||||
let (kept, total) = first_in_scope(kept, |_| true, 20_000);
|
||||
assert_eq!((kept.len(), total), (3, 3));
|
||||
}
|
||||
}
|
||||
@@ -118,21 +118,50 @@ impl PluginHost {
|
||||
.find(|(p, n, _)| p == plugin && n == tool)
|
||||
.ok_or_else(|| IdeError::not_found("plugin MCP tool is no longer available"))?;
|
||||
let args: serde_json::Value = serde_json::from_str(arguments).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
let validator =
|
||||
jsonschema::validator_for(&declared.input_schema).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if !validator.is_valid(&args) {
|
||||
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
|
||||
}
|
||||
let (tool, arguments) = (tool.to_owned(), arguments.to_owned());
|
||||
let arguments = arguments_for(&declared.input_schema, args)?;
|
||||
let tool = tool.to_owned();
|
||||
self.code_call_cancellable(plugin, invocation, "calling the MCP tool", Some(cancel), move |rt, inv| {
|
||||
rt.mcp_call(&tool, &arguments, inv)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `args` as the tool's `schema` takes them. Every listed tool takes `projectPath`, which the
|
||||
/// server routes a call by; a schema that refuses it gets the call without it.
|
||||
fn arguments_for(schema: &serde_json::Value, mut args: serde_json::Value) -> IdeResult<String> {
|
||||
let validator = jsonschema::validator_for(schema).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if !validator.is_valid(&args)
|
||||
&& let Some(args) = args.as_object_mut()
|
||||
{
|
||||
args.remove(crate::mcp::PROJECT_PATH);
|
||||
}
|
||||
if !validator.is_valid(&args) {
|
||||
return Err(IdeError::invalid("MCP arguments do not match inputSchema"));
|
||||
}
|
||||
Ok(args.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_schema_gets_the_project_path_only_when_it_takes_it() {
|
||||
let call = serde_json::json!({ "text": "hi", "projectPath": "/work/inventory" });
|
||||
let strict = serde_json::json!({
|
||||
"type": "object", "properties": { "text": { "type": "string" } }, "additionalProperties": false
|
||||
});
|
||||
assert_eq!(arguments_for(&strict, call.clone()).unwrap(), r#"{"text":"hi"}"#);
|
||||
// Declared through a local `$ref` and required: the plugin keeps it.
|
||||
let declared = serde_json::json!({
|
||||
"$ref": "#/$defs/call",
|
||||
"$defs": { "call": { "type": "object", "required": ["projectPath"], "additionalProperties": false,
|
||||
"properties": { "text": { "type": "string" }, "projectPath": { "type": "string" } } } }
|
||||
});
|
||||
let kept: serde_json::Value = serde_json::from_str(&arguments_for(&declared, call).unwrap()).unwrap();
|
||||
assert_eq!(kept["projectPath"], "/work/inventory");
|
||||
assert!(arguments_for(&strict, serde_json::json!({ "text": 12, "projectPath": "/p" })).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn validates_names_schema_files_versions_and_schema_keywords_at_install() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -422,6 +422,10 @@ pub struct PluginHost {
|
||||
initial_load: (Mutex<bool>, Condvar),
|
||||
/// `on-startup-finished` has fired.
|
||||
startup_finished: AtomicBool,
|
||||
/// Language, file and view activation events fired so far (with their project), so a plugin
|
||||
/// installed or synced afterwards (a remote server gets its packages after the window opened
|
||||
/// files) still activates for a Twig file that is already open.
|
||||
fired_activations: Mutex<Vec<(ActivationEvent, Option<PathBuf>)>>,
|
||||
/// The theme last announced with `ThemeChanged`.
|
||||
announced_theme: Mutex<Option<ActiveTheme>>,
|
||||
/// [`PluginLanguages::revision`] last announced with `LanguagesChanged`.
|
||||
@@ -541,6 +545,7 @@ impl PluginHost {
|
||||
lifecycle: Mutex::new(()),
|
||||
initial_load: (Mutex::new(false), Condvar::new()),
|
||||
startup_finished: AtomicBool::new(false),
|
||||
fired_activations: Mutex::new(Vec::new()),
|
||||
announced_theme: Mutex::new(None),
|
||||
announced_languages: AtomicU64::new(0),
|
||||
announced_skills: AtomicU64::new(0),
|
||||
@@ -699,6 +704,16 @@ impl PluginHost {
|
||||
|
||||
/// Fires an activation event from the UI (`on-language:rust`, `on-file:…`, `on-view:…`).
|
||||
pub fn activation_event(&self, event: &ActivationEvent, project: Option<&Path>) {
|
||||
{
|
||||
let mut fired = self.fired_activations.lock();
|
||||
let entry = (event.clone(), project.map(Path::to_path_buf));
|
||||
if !fired.contains(&entry) {
|
||||
if fired.len() >= MAX_FIRED_ACTIVATIONS {
|
||||
fired.remove(0);
|
||||
}
|
||||
fired.push(entry);
|
||||
}
|
||||
}
|
||||
let targets: Vec<_> = self
|
||||
.plugins
|
||||
.read()
|
||||
@@ -745,6 +760,11 @@ impl PluginHost {
|
||||
.filter(|(_, p)| p.dev_root.as_deref() == Some(root))
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
// Nothing to unload, nothing to announce: `CommandsChanged` makes every window list the
|
||||
// plugins again, and listing restricts an untrusted project again, which looped while idle.
|
||||
if ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
for id in ids {
|
||||
self.unload(&id);
|
||||
}
|
||||
@@ -2988,11 +3008,16 @@ impl PluginHost {
|
||||
{
|
||||
let mut plugins = self.plugins.write();
|
||||
if let Some(existing) = plugins.get(&id) {
|
||||
tracing::warn!(
|
||||
"plugin {id:?} at {} ignored: already loaded from {}",
|
||||
dir.display(),
|
||||
existing.dir().display()
|
||||
);
|
||||
// Every rescan meets the same duplicate again: say it once per directory, not on each scan.
|
||||
static WARNED: std::sync::LazyLock<Mutex<std::collections::HashSet<(String, PathBuf)>>> =
|
||||
std::sync::LazyLock::new(Default::default);
|
||||
if WARNED.lock().insert((id.clone(), dir.to_path_buf())) {
|
||||
tracing::warn!(
|
||||
"plugin {id:?} at {} ignored: already loaded from {}",
|
||||
dir.display(),
|
||||
existing.dir().display()
|
||||
);
|
||||
}
|
||||
return (id, None);
|
||||
}
|
||||
plugins.insert(id.clone(), plugin.clone());
|
||||
@@ -3096,8 +3121,12 @@ impl PluginHost {
|
||||
meta.pending = pending;
|
||||
meta.status = if plugin.manifest().wasm.is_some() { PluginStatus::Inactive } else { PluginStatus::Static };
|
||||
}
|
||||
let eager = plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
|
||||
&& self.startup_finished.load(Ordering::Acquire);
|
||||
let eager = (plugin.manifest().activation.contains(&ActivationEvent::StartupFinished)
|
||||
&& self.startup_finished.load(Ordering::Acquire))
|
||||
|| self.fired_activations.lock().iter().any(|(event, project)| {
|
||||
(plugin.dev_root.is_none() || plugin.dev_root == *project)
|
||||
&& plugin.manifest().activation.iter().any(|a| activation_matches(a, event))
|
||||
});
|
||||
if eager {
|
||||
let _ = self.ensure_active(plugin, None);
|
||||
}
|
||||
@@ -3725,6 +3754,9 @@ fn counts(m: &Manifest) -> Vec<ContributionCount> {
|
||||
m.declaration_counts().into_iter().map(|(point, count)| ContributionCount { point, count }).collect()
|
||||
}
|
||||
|
||||
/// How many fired activation events [`PluginHost::activation_event`] remembers (oldest dropped first).
|
||||
const MAX_FIRED_ACTIVATIONS: usize = 512;
|
||||
|
||||
fn activation_matches(declared: &ActivationEvent, fired: &ActivationEvent) -> bool {
|
||||
match (declared, fired) {
|
||||
(ActivationEvent::Language(a), ActivationEvent::Language(b)) => a == b || a == "*",
|
||||
|
||||
@@ -653,6 +653,11 @@ impl PluginHost {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a usable plugin offers ghost text for `language`.
|
||||
pub fn offers_inline_completion(&self, language: &str) -> bool {
|
||||
!self.provider_plugins(ProviderKind::InlineCompletion, language).is_empty()
|
||||
}
|
||||
|
||||
/// Ghost text from the first plugin that has some. Not bound by the
|
||||
/// edit-path soft deadline (it may need the network) but by `cancel`:
|
||||
/// the editor cancels a request as soon as the user types on.
|
||||
|
||||
@@ -5,6 +5,10 @@ use super::{
|
||||
network_inbox::{Inbox, Push},
|
||||
};
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use ide_core::{
|
||||
IdeResult,
|
||||
proxy_settings::{ProxyMode, ProxySettings},
|
||||
};
|
||||
use ide_plugin::WebSocketBatch;
|
||||
use parking_lot::Mutex;
|
||||
use std::{
|
||||
@@ -17,7 +21,7 @@ use std::{
|
||||
};
|
||||
use tokio::sync::{Notify, watch};
|
||||
use tokio_tungstenite::{
|
||||
Connector, connect_async_tls_with_config,
|
||||
Connector, client_async_tls_with_config,
|
||||
tungstenite::{
|
||||
Message,
|
||||
client::IntoClientRequest,
|
||||
@@ -128,11 +132,20 @@ impl WebSocketHub {
|
||||
.map(Arc::new)
|
||||
.map(Connector::Rustls)
|
||||
.map_err(|error| ConnectError::Failed(error.message))?;
|
||||
let (socket, response) =
|
||||
tokio::time::timeout(timeout, connect_async_tls_with_config(request, Some(config), false, Some(tls)))
|
||||
let target = reqwest::Url::parse(url).map_err(|_| ConnectError::Invalid("invalid WebSocket URL".into()))?;
|
||||
// Through the IDE's proxy settings, like the Jupyter kernel channels.
|
||||
let (socket, response) = tokio::time::timeout(timeout, async {
|
||||
// The tunnel's reason (a proxy that needs a login, refuses or is unreachable) helps the user.
|
||||
let stream = open_stream(&target, &ide_core::proxy_settings::proxy())
|
||||
.await
|
||||
.map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))?
|
||||
.map_err(|_| ConnectError::Failed("WebSocket connection failed".into()))?;
|
||||
.map_err(|error| format!("WebSocket connection failed: {}", error.message))?;
|
||||
client_async_tls_with_config(request, stream, Some(config), Some(tls))
|
||||
.await
|
||||
.map_err(|_| "WebSocket connection failed".to_owned())
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ConnectError::Failed("WebSocket connection timed out".into()))?
|
||||
.map_err(ConnectError::Failed)?;
|
||||
if !subprotocol.is_empty()
|
||||
&& response.headers().get("sec-websocket-protocol").and_then(|value| value.to_str().ok())
|
||||
!= Some(subprotocol)
|
||||
@@ -257,14 +270,30 @@ impl WebSocketHub {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_url(url: &str) -> Result<(), String> {
|
||||
let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?;
|
||||
// `host_str` keeps an IPv6 address in brackets.
|
||||
let loopback = parsed.host_str().is_some_and(|host| {
|
||||
/// `host_str` keeps an IPv6 address in brackets.
|
||||
fn is_loopback(url: &reqwest::Url) -> bool {
|
||||
url.host_str().is_some_and(|host| {
|
||||
let host = host.trim_start_matches('[').trim_end_matches(']');
|
||||
host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
|
||||
});
|
||||
if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && loopback) {
|
||||
})
|
||||
}
|
||||
|
||||
/// The TCP stream to `url` under `settings`. Loopback stays direct in every mode (plaintext `ws://` is
|
||||
/// loopback-only); a proxy the tunnel cannot speak to (SOCKS) keeps the direct connection plugins had before.
|
||||
async fn open_stream(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult<tokio::net::TcpStream> {
|
||||
if is_loopback(url) {
|
||||
return ide_http::tunnel::connect_best_effort(
|
||||
url,
|
||||
&ProxySettings { mode: ProxyMode::None, ..Default::default() },
|
||||
)
|
||||
.await;
|
||||
}
|
||||
ide_http::tunnel::connect_best_effort(url, settings).await
|
||||
}
|
||||
|
||||
fn validate_url(url: &str) -> Result<(), String> {
|
||||
let parsed = reqwest::Url::parse(url).map_err(|_| "invalid WebSocket URL")?;
|
||||
if parsed.scheme() != "wss" && !(parsed.scheme() == "ws" && is_loopback(&parsed)) {
|
||||
return Err("WebSocket requires WSS outside loopback".into());
|
||||
}
|
||||
if !parsed.username().is_empty() || parsed.password().is_some() || parsed.fragment().is_some() {
|
||||
@@ -392,6 +421,84 @@ mod tests {
|
||||
(url, task)
|
||||
}
|
||||
|
||||
fn manual(port: u16) -> ProxySettings {
|
||||
ProxySettings { mode: ProxyMode::Manual, host: "127.0.0.1".into(), port, ..Default::default() }
|
||||
}
|
||||
|
||||
async fn head_of_first_connection(listener: TcpListener) -> String {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let (mut client, _) = listener.accept().await.unwrap();
|
||||
let mut head = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
client.read_exact(&mut byte).await.unwrap();
|
||||
head.push(byte[0]);
|
||||
}
|
||||
client.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await.unwrap();
|
||||
String::from_utf8(head).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_manual_proxy_carries_the_connection() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let settings = manual(listener.local_addr().unwrap().port());
|
||||
let proxy = tokio::spawn(head_of_first_connection(listener));
|
||||
let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap();
|
||||
assert!(open_stream(&url, &settings).await.is_err());
|
||||
// A connection that bypasses the proxy leaves it waiting, so bound the wait.
|
||||
let asked = tokio::time::timeout(Duration::from_secs(2), proxy).await.expect("the proxy was never asked");
|
||||
assert!(asked.unwrap().starts_with("CONNECT ws-target.invalid:443 HTTP/1.1\r\n"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loopback_stays_direct_in_every_mode() {
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy_port = proxy.local_addr().unwrap().port();
|
||||
let proxy_task = tokio::spawn(head_of_first_connection(proxy));
|
||||
let target = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url =
|
||||
reqwest::Url::parse(&format!("ws://localhost:{}/socket", target.local_addr().unwrap().port())).unwrap();
|
||||
let settings = manual(proxy_port);
|
||||
open_stream(&url, &settings).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap();
|
||||
// Auto mode asks the system proxy, which may be set in the environment: loopback must not.
|
||||
open_stream(&url, &ProxySettings::default()).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(1), target.accept()).await.expect("no direct connection").unwrap();
|
||||
assert!(tokio::time::timeout(Duration::from_millis(200), proxy_task).await.is_err(), "the proxy was asked");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_ipv6_loopback_websocket_connects() {
|
||||
let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here
|
||||
let url = format!("ws://[::1]:{}/socket", listener.local_addr().unwrap().port());
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut socket = tokio_tungstenite::accept_async(stream).await.unwrap();
|
||||
socket.send(Message::Binary(vec![7].into())).await.unwrap();
|
||||
socket.close(None).await.unwrap();
|
||||
});
|
||||
let hub = WebSocketHub::default();
|
||||
hub.connect("plugin", "/project", &url, &[], "", Duration::from_secs(2)).await.unwrap();
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_refusing_proxy_says_why() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let settings = manual(listener.local_addr().unwrap().port());
|
||||
let proxy = tokio::spawn(async move {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
let (mut client, _) = listener.accept().await.unwrap();
|
||||
client.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n").await.unwrap();
|
||||
// Keep the socket open until the client has read the reply.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
});
|
||||
let url = reqwest::Url::parse("wss://ws-target.invalid/socket").unwrap();
|
||||
let error = open_stream(&url, &settings).await.unwrap_err();
|
||||
assert!(error.message.contains("needs a login"), "{}", error.message);
|
||||
proxy.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn outbound_message_reaches_the_websocket_server() {
|
||||
let (url, server) = server().await;
|
||||
|
||||
@@ -9,7 +9,7 @@ use ide_language::{FileTypes, LanguageRegistry, SyntaxCache};
|
||||
use ide_lsp::LspManager;
|
||||
use ide_syntax::StructureService;
|
||||
use ide_text::{AppliedChange, ByteEdit};
|
||||
use ide_vcs::{Backend, Repo, Repos};
|
||||
use ide_vcs::{Backend, BackendProvider, FileStatus, Repo, Repos};
|
||||
use ide_vfs::Watcher;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
use ide_workspace::{DocumentInfo, Documents, FileMoves, LocalHistory, ProjectRoots, SettingsStore, SourceFolder};
|
||||
@@ -41,6 +41,14 @@ pub struct Project {
|
||||
pub lsp: Arc<LspManager>,
|
||||
/// Git repositories: the one containing the project root and those nested below it.
|
||||
pub repos: Arc<RwLock<Repos>>,
|
||||
/// Working copies of the other version control systems ([`Host::with_vcs_provider`]) holding
|
||||
/// the project root or a content root. Found in a trusted project only: answering may run
|
||||
/// the system's client, and a `P4CONFIG` can name a program as its server.
|
||||
pub backends: Arc<RwLock<Vec<Arc<dyn Backend>>>>,
|
||||
pub(crate) vcs_providers: Arc<[Arc<dyn BackendProvider>]>,
|
||||
/// Held for a whole scan of `backends`, so overlapping scans (project open, trust change)
|
||||
/// finish in turn and the last one reads the current trust.
|
||||
backend_scan: Arc<Mutex<()>>,
|
||||
/// Explicitly opened external logs remain read-only and outside project indexing.
|
||||
pub(crate) external_log_repos: RwLock<Vec<Arc<Repo>>>,
|
||||
/// Incrementally maintained syntax trees of the open documents.
|
||||
@@ -77,6 +85,7 @@ pub struct Project {
|
||||
pub(crate) widget_preview: ide_flutter::ToolServer,
|
||||
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
|
||||
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
|
||||
pub(crate) swiftlint: Option<Arc<crate::swiftlint::SwiftLint>>,
|
||||
pub(crate) tsc_watch: Option<Arc<crate::tsc_watch::TscWatch>>,
|
||||
pub(crate) watcher: Arc<Watcher>,
|
||||
/// Watchers of the Project Structure content roots outside the project folder.
|
||||
@@ -385,8 +394,12 @@ impl Host {
|
||||
}));
|
||||
}
|
||||
{
|
||||
let documents = documents.clone();
|
||||
lsp.set_apply_edit_hook(Box::new(move |edit| documents.apply_workspace_edit(&edit).is_ok()));
|
||||
// Weak: `documents` keeps `lsp` alive through its observers, so a strong handle here would be
|
||||
// a cycle that leaks every closed project's documents, registry and language manager.
|
||||
let documents = Arc::downgrade(&documents);
|
||||
lsp.set_apply_edit_hook(Box::new(move |edit| {
|
||||
documents.upgrade().is_some_and(|documents| documents.apply_workspace_edit(&edit).is_ok())
|
||||
}));
|
||||
}
|
||||
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
|
||||
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
|
||||
@@ -419,9 +432,14 @@ impl Host {
|
||||
trusted.clone(),
|
||||
);
|
||||
documents.add_observer(phpstan.clone());
|
||||
let swiftlint = crate::swiftlint::SwiftLint::new(root.clone(), sink.clone(), trusted.clone());
|
||||
documents.add_observer(swiftlint.clone());
|
||||
let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone());
|
||||
documents.add_observer(tsc_watch.clone());
|
||||
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
|
||||
let backends: Arc<RwLock<Vec<Arc<dyn Backend>>>> = Arc::default();
|
||||
let vcs_providers: Arc<[Arc<dyn BackendProvider>]> = self.vcs_providers.clone().into();
|
||||
let backend_scan: Arc<Mutex<()>> = Arc::default();
|
||||
for repo in repos.read().all() {
|
||||
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
|
||||
}
|
||||
@@ -441,6 +459,7 @@ impl Host {
|
||||
let window = window.to_owned();
|
||||
let kotlin_bridge = kotlin_bridge.clone();
|
||||
let phpstan = phpstan.clone();
|
||||
let swiftlint = swiftlint.clone();
|
||||
let repos = repos.clone();
|
||||
let git_metadata = git_metadata.clone();
|
||||
let settings = settings.clone();
|
||||
@@ -459,6 +478,9 @@ impl Host {
|
||||
let build_cache = build_cache.clone();
|
||||
let notify_watch_exhausted = notify_watch_exhausted.clone();
|
||||
let watcher_weak = watcher_weak.clone();
|
||||
let (backends, vcs_providers, backend_scan) =
|
||||
(backends.clone(), vcs_providers.clone(), backend_scan.clone());
|
||||
let markers: Vec<String> = vcs_providers.iter().filter_map(|p| p.marker().map(str::to_owned)).collect();
|
||||
Watcher::start(
|
||||
&root.clone(),
|
||||
excludes.clone(),
|
||||
@@ -470,6 +492,7 @@ impl Host {
|
||||
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
|
||||
kotlin_bridge.files_changed(changed.iter().chain(&batch.removed));
|
||||
phpstan.files_removed(batch.removed.iter());
|
||||
swiftlint.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))
|
||||
@@ -560,6 +583,21 @@ impl Host {
|
||||
.collect();
|
||||
matches!(rest.as_slice(), [first, ..] if first == "worktrees" && rest.len() <= 2)
|
||||
});
|
||||
// `git worktree add` writes the worktree's gitfile before its gitdir's
|
||||
// `HEAD`: a rescan in between finds no repository there yet, so that `HEAD`
|
||||
// rescans too while its worktree is unknown and one a rescan would find.
|
||||
git_dirs |= batch.vcs.iter().any(|p| {
|
||||
let Some(gitdir) = p.parent().filter(|_| p.ends_with("HEAD")) else { return false };
|
||||
if !gitdir.parent().is_some_and(|d| d.ends_with(".git/worktrees")) {
|
||||
return false;
|
||||
}
|
||||
// `gitdir` may be relative to itself (`git worktree add --relative-paths`).
|
||||
let worktree = std::fs::read_to_string(gitdir.join("gitdir"))
|
||||
.and_then(|gitfile| dunce::canonicalize(gitdir.join(gitfile.trim())));
|
||||
worktree.ok().as_deref().and_then(Path::parent).is_some_and(|dir| {
|
||||
!known.iter().any(|r| r == dir) && repository_searched(&root, dir, &settings.effective())
|
||||
})
|
||||
});
|
||||
// A repository folder moved or restored into the project: no `.git` event is
|
||||
// written inside it before the watcher sees the new directory, its creation is
|
||||
// the signal. A `git clone` / `git init` inside the project already arrives
|
||||
@@ -580,6 +618,41 @@ impl Host {
|
||||
if git_dirs || vcs_moved {
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.clone().into() });
|
||||
}
|
||||
// A working copy appeared below the project (a checkout made inside it, a
|
||||
// folder moved in) or one went: its marker is the signal, as `.git` is above.
|
||||
// The marker itself may be an ignored name, so the folders of created paths
|
||||
// are checked for it. The scan asks providers, so it runs off this thread.
|
||||
if !markers.is_empty() && trusted.load(Ordering::Acquire) {
|
||||
let known: Vec<PathBuf> = backends.read().iter().map(|b| b.root().to_path_buf()).collect();
|
||||
let mut folders: HashSet<&Path> = HashSet::new();
|
||||
for p in &batch.created {
|
||||
let is_marker = p.file_name().is_some_and(|n| markers.iter().any(|m| n == m.as_str()));
|
||||
folders.extend(if !is_marker && p.is_dir() { Some(p.as_path()) } else { p.parent() });
|
||||
}
|
||||
let appeared = folders
|
||||
.iter()
|
||||
.any(|d| !known.iter().any(|r| r == d) && markers.iter().any(|m| d.join(m).exists()));
|
||||
let gone = batch.removed.iter().any(|p| known.iter().any(|r| r.starts_with(p)));
|
||||
if appeared || gone {
|
||||
let (backends, providers, lock, trust) =
|
||||
(backends.clone(), vcs_providers.clone(), backend_scan.clone(), trusted.clone());
|
||||
let (root, settings, sink, cache) =
|
||||
(root.clone(), settings.clone(), sink.clone(), build_cache.clone());
|
||||
let rescan = move || {
|
||||
let scan = BackendScan {
|
||||
backends: &backends,
|
||||
providers: &providers,
|
||||
lock: &lock,
|
||||
trusted: &trust,
|
||||
};
|
||||
scan.run(&root, &settings, &sink, &cache);
|
||||
};
|
||||
if let Err(e) = std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(rescan)
|
||||
{
|
||||
tracing::warn!("looking for working copies again: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// A watch limit hit after startup (per-directory mode, Linux):
|
||||
// folders past the limit never sync — surface it once, like
|
||||
// the polling fallback below (#1915). The check itself is
|
||||
@@ -661,9 +734,14 @@ impl Host {
|
||||
{
|
||||
let (root, repos, settings, sink) = (root.clone(), repos.clone(), settings.clone(), sink.clone());
|
||||
let (build_cache, git_metadata) = (build_cache.clone(), git_metadata.clone());
|
||||
let (backends, providers, trust) = (backends.clone(), vcs_providers.clone(), trusted.clone());
|
||||
let scan = backend_scan.clone();
|
||||
let trusted = trusted.load(Ordering::Acquire);
|
||||
std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(move || {
|
||||
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted)
|
||||
scan_repositories(&root, &repos, git_metadata.as_deref(), &settings, &sink, &build_cache, trusted);
|
||||
let backend_scan =
|
||||
BackendScan { backends: &backends, providers: &providers, lock: &scan, trusted: &trust };
|
||||
backend_scan.run(&root, &settings, &sink, &build_cache);
|
||||
})?;
|
||||
}
|
||||
mark("git");
|
||||
@@ -704,6 +782,9 @@ impl Host {
|
||||
index,
|
||||
lsp,
|
||||
repos,
|
||||
backends,
|
||||
vcs_providers,
|
||||
backend_scan,
|
||||
external_log_repos: RwLock::default(),
|
||||
structure: Arc::new(StructureService::new(syntax.clone())),
|
||||
syntax,
|
||||
@@ -720,6 +801,7 @@ impl Host {
|
||||
notebooks,
|
||||
kotlin_bridge: Some(kotlin_bridge),
|
||||
phpstan: Some(phpstan),
|
||||
swiftlint: Some(swiftlint),
|
||||
tsc_watch: Some(tsc_watch),
|
||||
watcher,
|
||||
content_watchers: Mutex::new(content_watchers),
|
||||
@@ -773,6 +855,8 @@ impl Host {
|
||||
let weak = Arc::downgrade(&project);
|
||||
project.agents.set_git_enabled_hook(Arc::new(move || weak.upgrade().is_some_and(|p| p.git_enabled())));
|
||||
}
|
||||
// Before anything starts a language server or a tool in the project; a trusted project only.
|
||||
crate::xcode_env::apply(&project);
|
||||
self.insert_project(window, project.clone());
|
||||
for (key, text, dirty) in &carried {
|
||||
let _ = project.documents.restore_untitled_buffer(key, text, *dirty);
|
||||
@@ -784,6 +868,9 @@ impl Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.start(&self.runtime);
|
||||
}
|
||||
if let Some(swiftlint) = &project.swiftlint {
|
||||
swiftlint.start(&self.runtime);
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.apply(&self.runtime);
|
||||
}
|
||||
@@ -999,6 +1086,9 @@ impl Host {
|
||||
index,
|
||||
lsp,
|
||||
repos: Arc::default(),
|
||||
backends: Arc::default(),
|
||||
vcs_providers: Arc::new([]),
|
||||
backend_scan: Arc::default(),
|
||||
external_log_repos: RwLock::default(),
|
||||
structure: Arc::new(StructureService::new(syntax.clone())),
|
||||
syntax,
|
||||
@@ -1015,6 +1105,7 @@ impl Host {
|
||||
notebooks,
|
||||
kotlin_bridge: None,
|
||||
phpstan: None,
|
||||
swiftlint: None,
|
||||
tsc_watch: None,
|
||||
watcher: Arc::new(watcher),
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
@@ -1036,17 +1127,16 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a tool that writes or runs refuses a project the user hasn't trusted.
|
||||
pub(crate) const RESTRICTED_MODE: &str = "Project is in Restricted Mode. Trust the project to enable execution.";
|
||||
|
||||
impl Project {
|
||||
pub fn is_trusted(&self) -> bool {
|
||||
self.trusted.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn require_trust(&self) -> IdeResult<()> {
|
||||
if self.is_trusted() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::unavailable("Project is in Restricted Mode. Trust the project to enable execution."))
|
||||
}
|
||||
if self.is_trusted() { Ok(()) } else { Err(IdeError::unavailable(RESTRICTED_MODE)) }
|
||||
}
|
||||
|
||||
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
|
||||
@@ -1174,18 +1264,122 @@ fn detect_repositories(
|
||||
build_cache: &Path,
|
||||
trusted: bool,
|
||||
) -> IdeResult<Repos> {
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
/// Folders the search for nested repositories leaves out, besides hidden and dependency ones.
|
||||
fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Path) -> bool {
|
||||
let ignored = settings.ignored_names();
|
||||
let skip = |p: &Path| {
|
||||
move |p: &Path| {
|
||||
p.file_name().is_some_and(|n| {
|
||||
let name = n.to_string_lossy();
|
||||
ignored.is_ignored_name(&name)
|
||||
|| (ide_workspace::unity::GENERATED_DIRS.contains(&name.as_ref())
|
||||
&& p.parent().is_some_and(ide_workspace::unity::is_project))
|
||||
})
|
||||
};
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
roots.extend(content_roots(settings, root, build_cache, trusted));
|
||||
Repos::discover_roots(&roots, &skip)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
|
||||
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
|
||||
settings.vcs.git.enabled
|
||||
&& !settings
|
||||
.vcs
|
||||
.mappings
|
||||
.excluded
|
||||
.iter()
|
||||
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
|
||||
&& Repos::searched(root, dir, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
/// Asks `providers` in order about `folder`; the first to answer adds its working copy to
|
||||
/// `found`, unless one with the same root is there already.
|
||||
fn ask_providers<'a>(
|
||||
folder: &Path,
|
||||
providers: impl IntoIterator<Item = &'a Arc<dyn BackendProvider>>,
|
||||
found: &mut Vec<Arc<dyn Backend>>,
|
||||
) {
|
||||
for provider in providers {
|
||||
match provider.discover(folder) {
|
||||
Ok(Some(backend)) => {
|
||||
if !found.iter().any(|b| b.root() == backend.root()) {
|
||||
found.push(backend);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!("looking for a working copy in {}: {e}", folder.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The working copy among `backends` that `path` belongs to ([`Project::backend_of`]): the
|
||||
/// deepest one holding it, unless a Git repository at or below its root holds the path.
|
||||
pub(crate) fn backend_for<'a>(
|
||||
backends: &'a [Arc<dyn Backend>],
|
||||
repos: &Repos,
|
||||
path: &Path,
|
||||
) -> Option<&'a Arc<dyn Backend>> {
|
||||
let backend =
|
||||
backends.iter().filter(|b| path.starts_with(b.root())).max_by_key(|b| b.root().components().count())?;
|
||||
let nested_git = repos.for_path(path).is_some_and(|r| r.root().starts_with(backend.root()));
|
||||
(!nested_git).then_some(backend)
|
||||
}
|
||||
|
||||
/// What a scan of the non-Git working copies works on: the list it replaces, the providers
|
||||
/// asked, the lock that serialises scans and the project's trust, read under that lock.
|
||||
struct BackendScan<'a> {
|
||||
backends: &'a RwLock<Vec<Arc<dyn Backend>>>,
|
||||
providers: &'a [Arc<dyn BackendProvider>],
|
||||
lock: &'a Mutex<()>,
|
||||
trusted: &'a AtomicBool,
|
||||
}
|
||||
|
||||
impl BackendScan<'_> {
|
||||
/// Asks the providers for the working copies holding the project root and its content
|
||||
/// roots; emits `VcsChanged` when the set changed. An untrusted project gets none and runs
|
||||
/// nothing. Scans run one at a time, each reading the trust when it starts, so a scan
|
||||
/// started before a trust change can't overwrite the one after it. Providers are asked in
|
||||
/// registration order and the first to answer for a folder wins it.
|
||||
fn run(&self, root: &Path, settings: &SettingsStore, sink: &SharedSink, build_cache: &Path) {
|
||||
let _scan = self.lock.lock();
|
||||
let trusted = self.trusted.load(Ordering::Acquire);
|
||||
let mut found: Vec<Arc<dyn Backend>> = Vec::new();
|
||||
if trusted && !self.providers.is_empty() {
|
||||
let settings = settings.effective();
|
||||
let mut folders = vec![root.to_path_buf()];
|
||||
folders.extend(content_roots(&settings, root, build_cache, trusted));
|
||||
let markers: Vec<&str> = self.providers.iter().filter_map(|p| p.marker()).collect();
|
||||
let skip = repository_scan_skips(&settings);
|
||||
for folder in &folders {
|
||||
// The folder itself (its working copy may start above it): every provider.
|
||||
if !found.iter().any(|b| folder.starts_with(b.root())) {
|
||||
ask_providers(folder, self.providers, &mut found);
|
||||
}
|
||||
// Working copies nested below it, like nested Git repositories: a separate
|
||||
// checkout or a directory external inside a working copy, or one inside a Git
|
||||
// repository. Only the providers whose marker the folder holds are asked.
|
||||
if markers.is_empty() {
|
||||
continue;
|
||||
}
|
||||
for nested in ide_vcs::marked_folders(folder, &markers, &skip) {
|
||||
if found.iter().any(|b| b.root() == nested) {
|
||||
continue;
|
||||
}
|
||||
let marked = self.providers.iter().filter(|p| p.marker().is_some_and(|m| nested.join(m).exists()));
|
||||
ask_providers(&nested, marked, &mut found);
|
||||
}
|
||||
}
|
||||
}
|
||||
let roots =
|
||||
|list: &[Arc<dyn Backend>]| list.iter().map(|b| (b.kind(), b.root().to_path_buf())).collect::<Vec<_>>();
|
||||
if roots(&found) != roots(&self.backends.read()) {
|
||||
*self.backends.write() = found;
|
||||
sink.emit(IdeEvent::VcsChanged { root: root.to_path_buf().into() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Project {
|
||||
@@ -1205,6 +1399,53 @@ impl Project {
|
||||
&self.build_cache_dir(),
|
||||
self.is_trusted(),
|
||||
);
|
||||
self.refresh_backends();
|
||||
}
|
||||
|
||||
/// Looks for the non-Git working copies again: they are found in a trusted project only,
|
||||
/// so trusting it (or restricting it) changes the answer.
|
||||
pub fn refresh_backends(&self) {
|
||||
let scan = BackendScan {
|
||||
backends: &self.backends,
|
||||
providers: &self.vcs_providers,
|
||||
lock: &self.backend_scan,
|
||||
trusted: &self.trusted,
|
||||
};
|
||||
scan.run(&self.root, &self.settings, &self.sink, &self.build_cache_dir());
|
||||
}
|
||||
|
||||
/// Tells the UI that what version control reports changed without a file event (a file
|
||||
/// was opened for edit).
|
||||
pub fn vcs_changed(&self) {
|
||||
self.sink.emit(IdeEvent::VcsChanged { root: self.root.clone().into() });
|
||||
}
|
||||
|
||||
/// The project's non-Git working copies; none while it is in Restricted Mode. A working
|
||||
/// copy rooted where a Git repository is (a folder with both `.git` and `.svn`) is left to
|
||||
/// Git, so each root is reported once.
|
||||
pub fn backends(&self) -> Vec<Arc<dyn Backend>> {
|
||||
if !self.is_trusted() {
|
||||
return Vec::new();
|
||||
}
|
||||
let repos = self.repos.read();
|
||||
self.backends.read().iter().filter(|b| repos.at_root(b.root()).is_none()).cloned().collect()
|
||||
}
|
||||
|
||||
/// The non-Git working copy `path` belongs to: the deepest one holding it, unless a Git
|
||||
/// repository at or below that working copy's root holds the path (a Git checkout inside
|
||||
/// a Perforce workspace stays Git's).
|
||||
pub fn backend_of(&self, path: &Path) -> Option<Arc<dyn Backend>> {
|
||||
backend_for(&self.backends(), &self.repos.read(), path).cloned()
|
||||
}
|
||||
|
||||
/// The non-Git working copy rooted at `at`; without `at`, the first one of a project that
|
||||
/// has no Git repository, where Git would use its primary repository.
|
||||
pub fn backend_at(&self, at: Option<&Path>) -> Option<Arc<dyn Backend>> {
|
||||
match at {
|
||||
Some(root) => self.backends().into_iter().find(|b| b.root() == root),
|
||||
None if self.repos.read().is_empty() => self.backends().into_iter().next(),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Git › Enable Git integration (effective value).
|
||||
@@ -1306,8 +1547,12 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// `with_repo_of` through the backend-agnostic Changes-view surface.
|
||||
/// Runs `f` with the backend `path` belongs to: its non-Git working copy, else its Git
|
||||
/// repository.
|
||||
pub fn with_backend_of<T>(&self, path: &Path, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
|
||||
if let Some(backend) = self.backend_of(path) {
|
||||
return f(backend.as_ref());
|
||||
}
|
||||
self.with_repo_of(path, |r| f(r as &dyn Backend))
|
||||
}
|
||||
|
||||
@@ -1323,8 +1568,12 @@ impl Project {
|
||||
f(repo)
|
||||
}
|
||||
|
||||
/// `with_repo_at` through the backend-agnostic Changes-view surface.
|
||||
/// `with_repo_at` through the backend-agnostic Changes-view surface; `at` may name a
|
||||
/// non-Git working copy ([`Self::backend_at`]).
|
||||
pub fn with_backend_at<T>(&self, at: Option<&Path>, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
|
||||
if let Some(backend) = self.backend_at(at) {
|
||||
return f(backend.as_ref());
|
||||
}
|
||||
self.with_repo_at(at, |r| f(r as &dyn Backend))
|
||||
}
|
||||
|
||||
@@ -1334,22 +1583,43 @@ impl Project {
|
||||
at: Option<&Path>,
|
||||
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
if let Some(backend) = self.backend_at(at) {
|
||||
return f(backend.as_ref());
|
||||
}
|
||||
self.with_log_repo_at(at, |r| f(r as &dyn Backend))
|
||||
}
|
||||
|
||||
/// `with_log_repo_of` through the backend-agnostic Changes-view surface.
|
||||
pub fn with_log_backend_of<T>(&self, path: &Path, f: impl FnOnce(&dyn Backend) -> IdeResult<T>) -> IdeResult<T> {
|
||||
if let Some(backend) = self.backend_of(path) {
|
||||
return f(backend.as_ref());
|
||||
}
|
||||
self.with_log_repo_of(path, |r| f(r as &dyn Backend))
|
||||
}
|
||||
|
||||
/// `with_repo_recorded` through the backend-agnostic Changes-view surface.
|
||||
/// `with_repo_recorded` through the backend-agnostic Changes-view surface: a non-Git
|
||||
/// working copy's operation (update, revert…) gets the same Local History labels and
|
||||
/// snapshots.
|
||||
pub fn with_backend_recorded<T>(
|
||||
&self,
|
||||
at: Option<&Path>,
|
||||
operation: Option<&str>,
|
||||
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
self.with_repo_recorded(at, operation, |r| f(r as &dyn Backend))
|
||||
match self.backend_at(at) {
|
||||
Some(backend) => self.backend_recorded(backend.as_ref(), operation, f),
|
||||
None => self.with_repo_recorded(at, operation, |r| f(r as &dyn Backend)),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::with_backend_recorded`] for a working copy already looked up.
|
||||
pub fn backend_recorded<T>(
|
||||
&self,
|
||||
backend: &dyn Backend,
|
||||
operation: Option<&str>,
|
||||
f: impl FnOnce(&dyn Backend) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
self.recorded(operation, || backend.status(), || f(backend))
|
||||
}
|
||||
|
||||
/// Runs `f` with the project's primary git repository, or fails when the project is not under git.
|
||||
@@ -1374,16 +1644,27 @@ impl Project {
|
||||
operation: Option<&str>,
|
||||
f: impl FnOnce(&Repo) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
let Some(name) = operation else { return self.with_disk_sync(|| self.with_repo_at(at, f)) };
|
||||
self.recorded(operation, || self.with_repo_at(at, Backend::status), || self.with_repo_at(at, f))
|
||||
}
|
||||
|
||||
/// Runs `run` with the Local History labels and snapshots of [`Self::with_repo_recorded`]:
|
||||
/// `changed` lists the files to snapshot.
|
||||
fn recorded<T>(
|
||||
&self,
|
||||
operation: Option<&str>,
|
||||
changed: impl FnOnce() -> IdeResult<Vec<FileStatus>>,
|
||||
run: impl FnOnce() -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
let Some(name) = operation else { return self.with_disk_sync(run) };
|
||||
self.history_label(&format!("Before {name}"));
|
||||
if let Ok(changed) = self.with_backend_at(at, |r| r.status()) {
|
||||
if let Ok(changed) = changed() {
|
||||
for file in changed.iter().take(HISTORY_BATCH_LIMIT) {
|
||||
if let Err(e) = self.history.record_file(&file.path, &format!("Before {name}"), false) {
|
||||
tracing::debug!("local history: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = self.with_disk_sync(|| self.with_repo_at(at, f));
|
||||
let result = self.with_disk_sync(run);
|
||||
self.history_label(&format!("After {name}"));
|
||||
result
|
||||
}
|
||||
@@ -1615,7 +1896,7 @@ impl Project {
|
||||
return encoding_rs::Encoding::for_label(loaded.encoding.as_bytes())
|
||||
.ok_or_else(|| ide_core::IdeError::invalid("unknown file encoding"));
|
||||
}
|
||||
let bytes = self.with_log_repo_of(path, |r| r.file_bytes_at(path, rev))?.unwrap_or_default();
|
||||
let bytes = self.with_log_backend_of(path, |b| b.file_bytes_at(path, rev))?.unwrap_or_default();
|
||||
Ok(self.documents.detect_encoding(path, &bytes))
|
||||
}
|
||||
|
||||
|
||||
@@ -500,6 +500,7 @@ mod tests {
|
||||
subject: "rm -rf".into(),
|
||||
project: "/srv/app".into(),
|
||||
detail: None,
|
||||
background: false,
|
||||
};
|
||||
let update = ide_core::updates::UpdateInfo {
|
||||
version: "9.9.9".into(),
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
//! Swift files below a `.swiftlint.yml` -> `swiftlint lint --reporter json` -> `swiftlint` diagnostics.
|
||||
//!
|
||||
//! A file as saved is linted by its path, so the configuration's `excluded` paths and nested
|
||||
//! configurations apply; an edited buffer is linted through stdin, unless its saved file was excluded.
|
||||
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::output_encoding::decode_tool_output;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
|
||||
use ide_text::AppliedChange;
|
||||
use ide_workspace::documents::{DocumentInfo, DocumentObserver};
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Output, Stdio};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
const DELAY: Duration = Duration::from_millis(400);
|
||||
const SOURCE: &str = "swiftlint";
|
||||
const CONFIG: &str = ".swiftlint.yml";
|
||||
|
||||
/// What to lint: the saved file, or the text of its edited buffer.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Job {
|
||||
Saved,
|
||||
Buffer(String),
|
||||
}
|
||||
|
||||
pub(crate) struct SwiftLint {
|
||||
root: PathBuf,
|
||||
sink: SharedSink,
|
||||
trusted: Arc<AtomicBool>,
|
||||
lifetime: CancellationToken,
|
||||
/// The latest job per file; a newer one replaces it, and its result is dropped.
|
||||
pending: Mutex<BTreeMap<PathBuf, Job>>,
|
||||
changed: Notify,
|
||||
/// Files with SwiftLint diagnostics, the only ones a clean result or a close clears.
|
||||
shown: Mutex<HashSet<PathBuf>>,
|
||||
/// Files the configuration excludes, as found by their last saved-file lint.
|
||||
excluded: Mutex<HashSet<PathBuf>>,
|
||||
/// Failures already reported (a missing `swiftlint` included), each once until a run succeeds.
|
||||
reported: Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
impl SwiftLint {
|
||||
pub(crate) fn new(root: PathBuf, sink: SharedSink, trusted: Arc<AtomicBool>) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
root,
|
||||
sink,
|
||||
trusted,
|
||||
lifetime: CancellationToken::new(),
|
||||
pending: Mutex::new(BTreeMap::new()),
|
||||
changed: Notify::new(),
|
||||
shown: Mutex::new(HashSet::new()),
|
||||
excluded: Mutex::new(HashSet::new()),
|
||||
reported: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn start(self: &Arc<Self>, runtime: &tokio::runtime::Handle) {
|
||||
let linter = self.clone();
|
||||
runtime.spawn(async move { linter.run().await });
|
||||
}
|
||||
|
||||
pub(crate) fn stop(&self) {
|
||||
self.lifetime.cancel();
|
||||
}
|
||||
|
||||
fn queue(&self, path: &Path, job: Job) {
|
||||
if self.lifetime.is_cancelled() || !path.extension().is_some_and(|e| e == "swift") {
|
||||
return;
|
||||
}
|
||||
self.pending.lock().insert(path.to_path_buf(), job);
|
||||
self.changed.notify_one();
|
||||
}
|
||||
|
||||
/// Trusting the project lints its open files; Restricted Mode drops what was shown.
|
||||
pub(crate) fn trust_changed(&self, trusted: bool, open: impl Iterator<Item = DocumentInfo>) {
|
||||
if trusted {
|
||||
open.for_each(|info| self.opened(&info));
|
||||
} else {
|
||||
self.pending.lock().clear();
|
||||
let shown: Vec<PathBuf> = self.shown.lock().iter().cloned().collect();
|
||||
for path in shown {
|
||||
self.publish(path, Vec::new());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deleted files and folders lose their diagnostics.
|
||||
pub(crate) fn files_removed<'a>(&self, removed: impl Iterator<Item = &'a PathBuf>) {
|
||||
let removed: Vec<&PathBuf> = removed.collect();
|
||||
self.excluded.lock().retain(|p| !removed.iter().any(|r| p.starts_with(r)));
|
||||
let gone: Vec<PathBuf> =
|
||||
self.shown.lock().iter().filter(|p| removed.iter().any(|r| p.starts_with(r))).cloned().collect();
|
||||
for path in gone {
|
||||
self.publish(path, Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
fn publish(&self, path: PathBuf, items: Vec<Diagnostic>) {
|
||||
let mut shown = self.shown.lock();
|
||||
if items.is_empty() {
|
||||
if !shown.remove(&path) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
shown.insert(path.clone());
|
||||
}
|
||||
self.sink.emit(IdeEvent::Diagnostics { path: path.into(), source: SOURCE.into(), items });
|
||||
}
|
||||
|
||||
async fn run(self: Arc<Self>) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = self.lifetime.cancelled() => return,
|
||||
_ = self.changed.notified() => {},
|
||||
}
|
||||
// Typing keeps replacing the pending job: lint once it pauses.
|
||||
tokio::select! {
|
||||
_ = self.lifetime.cancelled() => return,
|
||||
_ = tokio::time::sleep(DELAY) => {},
|
||||
}
|
||||
loop {
|
||||
let Some((path, job)) = self.pending.lock().pop_first() else { break };
|
||||
if !self.trusted.load(Ordering::Acquire) {
|
||||
continue;
|
||||
}
|
||||
let Some(dir) = config_dir(&self.root, &path) else {
|
||||
self.publish(path, Vec::new());
|
||||
continue;
|
||||
};
|
||||
if job != Job::Saved && self.excluded.lock().contains(&path) {
|
||||
continue;
|
||||
}
|
||||
let text = match &job {
|
||||
Job::Saved => None,
|
||||
Job::Buffer(text) => Some(text.as_str()),
|
||||
};
|
||||
let Some(output) = lint(&dir, &path, text, &self.lifetime).await else { return };
|
||||
// Edited again meanwhile: the newer job's result replaces this one. Restricted
|
||||
// meanwhile: `trust_changed` already cleared the findings.
|
||||
if self.pending.lock().contains_key(&path) || !self.trusted.load(Ordering::Acquire) {
|
||||
continue;
|
||||
}
|
||||
let result = output.map_err(|e| {
|
||||
if e.kind() == std::io::ErrorKind::NotFound {
|
||||
"swiftlint was not found on PATH. Install SwiftLint (brew install swiftlint), \
|
||||
or from Settings › Languages & Frameworks › Language Servers."
|
||||
.to_string()
|
||||
} else {
|
||||
format!("Cannot run swiftlint: {e}")
|
||||
}
|
||||
});
|
||||
let result = result.and_then(|o| parse(&decode_tool_output(&o.stdout), &decode_tool_output(&o.stderr)));
|
||||
match result {
|
||||
Ok(Report::Excluded) => {
|
||||
self.excluded.lock().insert(path.clone());
|
||||
self.publish(path, Vec::new());
|
||||
*self.reported.lock() = None;
|
||||
}
|
||||
Ok(Report::Violations(violations)) => {
|
||||
if job == Job::Saved {
|
||||
self.excluded.lock().remove(&path);
|
||||
}
|
||||
let text = match job {
|
||||
Job::Buffer(text) => text,
|
||||
Job::Saved => std::fs::read(&path)
|
||||
.map(|b| String::from_utf8_lossy(&b).into_owned())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let items = violations.into_iter().map(|v| diagnostic(v, &text)).collect();
|
||||
self.publish(path, items);
|
||||
*self.reported.lock() = None;
|
||||
}
|
||||
Err(text) => {
|
||||
self.publish(path, Vec::new());
|
||||
self.failure(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn failure(&self, text: String) {
|
||||
let mut reported = self.reported.lock();
|
||||
if reported.as_ref() == Some(&text) {
|
||||
return;
|
||||
}
|
||||
self.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Error,
|
||||
title: "SwiftLint check failed".into(),
|
||||
body: Some(text.clone()),
|
||||
});
|
||||
*reported = Some(text);
|
||||
}
|
||||
}
|
||||
|
||||
impl DocumentObserver for SwiftLint {
|
||||
fn opened(&self, info: &DocumentInfo) {
|
||||
let path = info.path.to_path_buf();
|
||||
self.queue(&path, if info.dirty { Job::Buffer(info.text.clone()) } else { Job::Saved });
|
||||
}
|
||||
|
||||
fn changed(
|
||||
&self,
|
||||
_doc: ide_core::DocId,
|
||||
path: &Path,
|
||||
_version: u32,
|
||||
_changes: &[AppliedChange],
|
||||
full_text: &dyn Fn() -> String,
|
||||
) {
|
||||
if path.extension().is_some_and(|e| e == "swift") {
|
||||
self.queue(path, Job::Buffer(full_text()));
|
||||
}
|
||||
}
|
||||
|
||||
fn saved(&self, _doc: ide_core::DocId, path: &Path, _text: &str) {
|
||||
self.queue(path, Job::Saved);
|
||||
}
|
||||
|
||||
/// A closed buffer's unsaved text is gone, and with it what its diagnostics described.
|
||||
fn closed(&self, _doc: ide_core::DocId, path: &Path) {
|
||||
self.pending.lock().remove(path);
|
||||
self.publish(path.to_path_buf(), Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder of the `.swiftlint.yml` nearest to `file` within the project, where SwiftLint
|
||||
/// runs so it finds that configuration. Files outside the project, or below no configuration,
|
||||
/// are not linted.
|
||||
fn config_dir(root: &Path, file: &Path) -> Option<PathBuf> {
|
||||
file.ancestors()
|
||||
.skip(1)
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find(|d| d.join(CONFIG).is_file())
|
||||
.map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// Runs `swiftlint lint` in `dir` on the saved `file`, or on `text` through stdin;
|
||||
/// `None` when `cancel` fires first, which kills it.
|
||||
async fn lint(
|
||||
dir: &Path,
|
||||
file: &Path,
|
||||
text: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
) -> Option<std::io::Result<Output>> {
|
||||
let mut cmd = std::process::Command::new("swiftlint");
|
||||
cmd.args(["lint", "--reporter", "json", "--quiet", "--no-cache"]).current_dir(dir);
|
||||
match text {
|
||||
Some(_) => cmd.arg("--use-stdin"),
|
||||
None => cmd.arg("--force-exclude").arg(file),
|
||||
};
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
cmd.stdin(if text.is_some() { Stdio::piped() } else { Stdio::null() });
|
||||
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut cmd = tokio::process::Command::from(cmd);
|
||||
cmd.kill_on_drop(true);
|
||||
let run = async {
|
||||
let mut child = cmd.spawn()?;
|
||||
if let (Some(text), Some(mut stdin)) = (text, child.stdin.take()) {
|
||||
stdin.write_all(text.as_bytes()).await?;
|
||||
}
|
||||
child.wait_with_output().await
|
||||
};
|
||||
tokio::select! {
|
||||
output = run => Some(output),
|
||||
() = cancel.cancelled() => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of SwiftLint's JSON report; `line` and `character` are 1-based, the
|
||||
/// character counted in UTF-16 units.
|
||||
#[derive(Debug, Deserialize, PartialEq)]
|
||||
struct Violation {
|
||||
line: Option<u32>,
|
||||
character: Option<u32>,
|
||||
reason: String,
|
||||
rule_id: String,
|
||||
severity: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Report {
|
||||
Violations(Vec<Violation>),
|
||||
/// `--force-exclude` dropped the file: the configuration's `excluded` lists it.
|
||||
Excluded,
|
||||
}
|
||||
|
||||
/// The `--reporter json` report (SwiftLint exits with 2 when it has errors), or the text
|
||||
/// to report when there is none.
|
||||
fn parse(stdout: &str, stderr: &str) -> Result<Report, String> {
|
||||
if let Ok(violations) = serde_json::from_str::<Vec<Violation>>(stdout.trim()) {
|
||||
return Ok(Report::Violations(violations));
|
||||
}
|
||||
if stderr.contains("No lintable files found") {
|
||||
return Ok(Report::Excluded);
|
||||
}
|
||||
let lines: Vec<&str> = stderr.lines().chain(stdout.lines()).map(str::trim).filter(|l| !l.is_empty()).collect();
|
||||
if lines.is_empty() {
|
||||
return Err("SwiftLint ended with no report".into());
|
||||
}
|
||||
Err(lines.iter().take(20).copied().collect::<Vec<_>>().join("\n"))
|
||||
}
|
||||
|
||||
fn diagnostic(v: Violation, text: &str) -> Diagnostic {
|
||||
Diagnostic {
|
||||
range: range(text, v.line, v.character),
|
||||
severity: if v.severity.eq_ignore_ascii_case("error") { Severity::Error } else { Severity::Warning },
|
||||
message: v.reason,
|
||||
source: Some("SwiftLint".into()),
|
||||
server: Some(SOURCE.into()),
|
||||
code: Some(v.rule_id),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The word at the reported position, or the line from its first non-blank character when
|
||||
/// SwiftLint gives no column (or the column has no word: a semicolon, a brace).
|
||||
fn range(text: &str, line: Option<u32>, character: Option<u32>) -> Range {
|
||||
let line = line.unwrap_or(1).max(1) - 1;
|
||||
let content = text.strip_prefix('\u{feff}').unwrap_or(text).split('\n').nth(line as usize).unwrap_or("");
|
||||
let content: Vec<u16> = content.trim_end().encode_utf16().collect();
|
||||
let len = u32::try_from(content.len()).unwrap_or(u32::MAX);
|
||||
let Some(start) = character.map(|c| c.max(1) - 1).filter(|&c| c < len) else {
|
||||
let indent = content.iter().take_while(|&&u| u == u16::from(b' ') || u == u16::from(b'\t')).count();
|
||||
return Range { start: Pos { line, col: indent as u32 }, end: Pos { line, col: len } };
|
||||
};
|
||||
let word = |u: &u16| char::from_u32(u32::from(*u)).is_some_and(|c| c.is_alphanumeric() || c == '_');
|
||||
let run = content[start as usize..].iter().take_while(|u| word(u)).count() as u32;
|
||||
Range { start: Pos { line, col: start }, end: Pos { line, col: start + run.max(1) } }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const REPORT: &str = r#"[
|
||||
{"character": 5, "file": null, "line": 1, "reason": "Variable name 'a_b' should only contain alphanumeric characters",
|
||||
"rule_id": "identifier_name", "severity": "Error", "type": "Identifier Name"},
|
||||
{"character": null, "file": "/p/A.swift", "line": 3, "reason": "Line should be 40 characters or less",
|
||||
"rule_id": "line_length", "severity": "Warning", "type": "Line Length"},
|
||||
{"character": 13, "file": null, "line": 2, "reason": "Lines should not have trailing semicolons",
|
||||
"rule_id": "trailing_semicolon", "severity": "Warning", "type": "Trailing Semicolon"}
|
||||
]"#;
|
||||
|
||||
#[test]
|
||||
fn violations_map_to_diagnostics() {
|
||||
let Ok(Report::Violations(violations)) = parse(REPORT, "") else { panic!() };
|
||||
let text = "let a_b = 1\nlet 😀x = 1 ;\n let long = 2\n";
|
||||
let items: Vec<Diagnostic> = violations.into_iter().map(|v| diagnostic(v, text)).collect();
|
||||
let summary: Vec<_> = items.iter().map(|d| (d.code.as_deref().unwrap(), d.severity, d.range)).collect();
|
||||
let r = |line, a, b| Range { start: Pos { line, col: a }, end: Pos { line, col: b } };
|
||||
assert_eq!(
|
||||
summary,
|
||||
[
|
||||
("identifier_name", Severity::Error, r(0, 4, 7)),
|
||||
// No column: the line from its first non-blank character.
|
||||
("line_length", Severity::Warning, r(2, 4, 16)),
|
||||
// UTF-16 columns: the emoji takes two, and a semicolon gets one.
|
||||
("trailing_semicolon", Severity::Warning, r(1, 12, 13)),
|
||||
]
|
||||
);
|
||||
assert_eq!((items[0].source.as_deref(), items[0].server.as_deref()), (Some("SwiftLint"), Some("swiftlint")));
|
||||
assert!(items[0].message.starts_with("Variable name 'a_b'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluded_files_and_failures_are_told_apart() {
|
||||
assert_eq!(parse("[]\n", ""), Ok(Report::Violations(vec![])));
|
||||
let excluded = "Error: No lintable files found at paths: 'Gen/g.swift'\n";
|
||||
assert_eq!(parse("", excluded), Ok(Report::Excluded));
|
||||
assert_eq!(parse("", "Fatal error: crashed\n\n"), Err("Fatal error: crashed".into()));
|
||||
assert_eq!(parse("", ""), Err("SwiftLint ended with no report".into()));
|
||||
// A bad column or line stays on the text.
|
||||
assert_eq!(
|
||||
range("x", Some(9), Some(40)),
|
||||
Range { start: Pos { line: 8, col: 0 }, end: Pos { line: 8, col: 0 } }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nearest_configuration_in_the_project_wins() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("p");
|
||||
std::fs::create_dir_all(root.join("Sources/App")).unwrap();
|
||||
std::fs::create_dir_all(root.join("Pkg/Sources")).unwrap();
|
||||
let file = root.join("Sources/App/A.swift");
|
||||
assert_eq!(config_dir(&root, &file), None);
|
||||
std::fs::write(dir.path().join(CONFIG), "").unwrap();
|
||||
assert_eq!(config_dir(&root, &file), None, "a configuration above the project is not the project's");
|
||||
std::fs::write(root.join(CONFIG), "").unwrap();
|
||||
std::fs::write(root.join("Pkg").join(CONFIG), "").unwrap();
|
||||
assert_eq!(config_dir(&root, &file), Some(root.clone()));
|
||||
assert_eq!(config_dir(&root, &root.join("Pkg/Sources/B.swift")), Some(root.join("Pkg")));
|
||||
}
|
||||
}
|
||||
@@ -260,6 +260,10 @@ impl crate::Host {
|
||||
let p = project.clone();
|
||||
tokio::task::spawn_blocking(move || p.refresh_repositories());
|
||||
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
|
||||
} else if !project.vcs_providers.is_empty() {
|
||||
// Non-Git working copies are found in a trusted project only: they show up (or go) now.
|
||||
let p = project.clone();
|
||||
tokio::task::spawn_blocking(move || p.refresh_backends());
|
||||
}
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.schedule();
|
||||
@@ -267,6 +271,10 @@ impl crate::Host {
|
||||
if let Some(phpstan) = &project.phpstan {
|
||||
phpstan.interrupt();
|
||||
}
|
||||
if let Some(swiftlint) = &project.swiftlint {
|
||||
let docs = project.documents.open_documents();
|
||||
swiftlint.trust_changed(trusted, docs.into_iter().filter_map(|d| project.documents.snapshot(d).ok()));
|
||||
}
|
||||
if let Some(watch) = &project.tsc_watch {
|
||||
watch.apply(&self.runtime);
|
||||
}
|
||||
@@ -276,6 +284,8 @@ impl crate::Host {
|
||||
}
|
||||
project.lsp.set_execution_allowed(false);
|
||||
}
|
||||
// Before anything runs `git` (a `/usr/bin` shim that follows `DEVELOPER_DIR`): set or cleared.
|
||||
crate::xcode_env::apply(&project);
|
||||
project.repos();
|
||||
if trusted {
|
||||
if let Some(cmd) = self.environment.project_opened(&project.root, &project.sink) {
|
||||
@@ -308,6 +318,7 @@ impl crate::Host {
|
||||
.map(|(window, _)| window.clone())
|
||||
.collect();
|
||||
for window in windows {
|
||||
self.mcp_requests.withdraw(&window);
|
||||
let requests = self.project_requests.write().remove(&window).unwrap_or_default();
|
||||
for request in requests {
|
||||
self.cancel_request(request);
|
||||
|
||||
@@ -370,7 +370,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
|
||||
("window_toggle_zoom", Always),
|
||||
("window_start_drag", Always),
|
||||
("window_drag_files", Always),
|
||||
("file_dialog_needs_gtk", Trusted),
|
||||
("file_dialog_needs_gtk", Always),
|
||||
("clipboard_has_files", Always),
|
||||
("clipboard_has_image", Always),
|
||||
] {
|
||||
@@ -387,7 +387,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
|
||||
for (empty_list, trust) in [
|
||||
("window_group_current", Always),
|
||||
("system_font_families", Always),
|
||||
("system_probe_hotkeys", Trusted),
|
||||
("system_probe_hotkeys", Always),
|
||||
("wsl_distros", Always),
|
||||
("web_browsers", Always),
|
||||
("plugin_catalog", Always),
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
//! The project's Xcode (`languages.swift.xcode`): every child started in the project gets it as
|
||||
//! `DEVELOPER_DIR` through [`ide_core::project_env`] — sourcekit-lsp, `xcodebuild` and `xcrun` of
|
||||
//! runs, tests, coverage and debugging, and terminals.
|
||||
|
||||
use crate::project::Project;
|
||||
use ide_core::settings::SwiftSettings;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The `DEVELOPER_DIR` a project's children get. Only a trusted project's: the setting lives in the
|
||||
/// repository (`.openidea/settings.toml`), and the `/usr/bin` shims (`git`, `xcrun`, `clang`, …)
|
||||
/// run `$DEVELOPER_DIR/usr/bin/<tool>`, so an untrusted one could point them at its own binaries.
|
||||
fn developer_dir(trusted: bool, swift: &SwiftSettings) -> Option<PathBuf> {
|
||||
trusted.then(|| swift.developer_dir()).flatten()
|
||||
}
|
||||
|
||||
/// Applies the project's Xcode to its environment, or clears it for an untrusted project; returns
|
||||
/// whether it changed.
|
||||
pub fn apply(project: &Project) -> bool {
|
||||
let trusted = project.is_trusted() && !project.light;
|
||||
let dir = developer_dir(trusted, &project.settings.effective().languages.swift).map(Into::into);
|
||||
let root = ide_core::project_env::set_developer_dir(&project.root, dir.clone());
|
||||
let worktrees = ide_core::project_env::set_developer_dir(project.agents.worktrees_dir(), dir);
|
||||
root || worktrees
|
||||
}
|
||||
|
||||
/// [`apply`], then restarts a running sourcekit-lsp when the Xcode changed.
|
||||
pub async fn apply_and_restart(project: &Project) {
|
||||
if !apply(project) {
|
||||
return;
|
||||
}
|
||||
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
|
||||
if let Err(e) = project.lsp.restart(server.id).await {
|
||||
tracing::warn!("restarting sourcekit-lsp for the new Xcode: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_a_trusted_project_gets_its_xcode() {
|
||||
let swift = SwiftSettings { xcode: "./x.app".into() };
|
||||
assert_eq!(developer_dir(false, &swift), None, "untrusted: the repository's own binaries must not run");
|
||||
assert_eq!(developer_dir(true, &swift), Some("./x.app/Contents/Developer".into()));
|
||||
assert_eq!(developer_dir(true, &SwiftSettings::default()), None);
|
||||
}
|
||||
}
|
||||
@@ -87,3 +87,46 @@ fn detached_close_returns_while_runtime_workers_wait_for_the_closing_thread() {
|
||||
host.shutdown_notebooks_on_exit();
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "exit joined the finished close instead of timing out");
|
||||
}
|
||||
|
||||
/// `Documents` keeps the language manager alive through its observers and the manager once held the
|
||||
/// documents back, so a closed project's documents (and everything they reference) were never freed.
|
||||
/// Checked for the synchronous close and for the detached close that a window uses.
|
||||
#[test]
|
||||
fn closing_a_project_frees_its_documents() {
|
||||
for detached in [false, true] {
|
||||
assert_close_frees_documents(detached);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_close_frees_documents(detached: bool) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();
|
||||
let _guard = runtime.enter();
|
||||
let host = Arc::new(Host::new(common::host_config(tmp.path())));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let (documents, languages) = {
|
||||
let project = host.project("main").unwrap();
|
||||
(Arc::downgrade(&project.documents), Arc::downgrade(&project.languages))
|
||||
};
|
||||
assert!(documents.upgrade().is_some(), "the open project owns its documents");
|
||||
|
||||
if detached {
|
||||
host.close_project_detached("main");
|
||||
} else {
|
||||
host.close_project("main");
|
||||
}
|
||||
// The detached close drops the project on its own thread.
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while documents.upgrade().is_some() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
|
||||
assert!(documents.upgrade().is_none(), "detached={detached}: the documents of a closed project are still alive");
|
||||
assert!(
|
||||
languages.upgrade().is_none(),
|
||||
"detached={detached}: the language registry of a closed project is still alive"
|
||||
);
|
||||
}
|
||||
@@ -107,7 +107,7 @@ async fn compose_target_is_the_python_interpreter() {
|
||||
eprintln!("run target interpreter: {after:?}");
|
||||
assert!(after.iter().all(|m| !m.contains("could not be resolved")), "{after:?}");
|
||||
|
||||
let info = ops::sdk::sdk_container_python(&host, WINDOW).unwrap().expect("a run target interpreter");
|
||||
let info = ops::sdk::sdk_container_python(&host, WINDOW).await.unwrap().expect("a run target interpreter");
|
||||
eprintln!("snapshot: version {:?}, image {:?}, folders {:?}", info.version, info.image, info.folders);
|
||||
assert_eq!(info.name, "Compose web");
|
||||
assert!(info.version.as_deref().is_some_and(|v| v.starts_with("3.12.")), "{info:?}");
|
||||
|
||||
@@ -742,38 +742,43 @@ async fn typescript_import_style() {
|
||||
..TYPESCRIPT
|
||||
};
|
||||
let smoke = Smoke::start("typescript", &checks).await;
|
||||
let set = |key: &str, value: &str| {
|
||||
let lsp = smoke.host.project(WINDOW).unwrap().lsp.clone();
|
||||
// Returns once vtsls has the change. A completion that runs before it fills tsserver's
|
||||
// module specifier cache for that file under the old preferences, and that cache is keyed
|
||||
// without `autoImportSpecifierExcludeRegexes`, so the file keeps the old answer.
|
||||
let set = async |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();
|
||||
lsp.reconfigure().await;
|
||||
};
|
||||
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""#);
|
||||
set("importModuleSpecifier", r#""relative""#).await;
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
set("importModuleSpecifier", r#""non-relative""#);
|
||||
set("importModuleSpecifier", r#""non-relative""#).await;
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
set("importModuleSpecifierEnding", r#""index""#);
|
||||
set("importModuleSpecifier", r#""relative""#).await;
|
||||
set("importModuleSpecifierEnding", r#""index""#).await;
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
|
||||
set("importModuleSpecifierEnding", r#""minimal""#);
|
||||
set("importModuleSpecifierEnding", r#""minimal""#).await;
|
||||
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"]"#);
|
||||
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#).await;
|
||||
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#).await;
|
||||
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", "[]");
|
||||
set("autoImportFileExcludePatterns", "[]").await;
|
||||
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
set("autoImportSpecifierExcludeRegexes", "[]");
|
||||
set("autoImportSpecifierExcludeRegexes", "[]").await;
|
||||
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
mod common;
|
||||
|
||||
use ide_core::{CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange};
|
||||
use ide_core::{
|
||||
CancellationToken, ChangeSet, Diagnostic, IdeEvent, Pos, Range, Severity, TextChange, event::McpUiRequest,
|
||||
};
|
||||
use ide_host::mcp::{BackgroundProjects, FileProblems, FocusedEditor, Registry};
|
||||
use ide_host::{Host, HostConfig};
|
||||
use ide_mcp::ToolRegistry;
|
||||
@@ -12,7 +14,8 @@ struct Harness {
|
||||
host: Arc<Host>,
|
||||
root: PathBuf,
|
||||
tmp: tempfile::TempDir,
|
||||
events: Arc<std::sync::Mutex<Vec<IdeEvent>>>,
|
||||
/// Every event, with the window whose sink it was emitted on.
|
||||
events: Arc<std::sync::Mutex<Vec<(String, IdeEvent)>>>,
|
||||
}
|
||||
impl Harness {
|
||||
fn new() -> Self {
|
||||
@@ -27,9 +30,9 @@ impl Harness {
|
||||
let events = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
sink_for: Box::new(move |_| {
|
||||
let events = sink.clone();
|
||||
Arc::new(move |e| events.lock().unwrap().push(e))
|
||||
sink_for: Box::new(move |window| {
|
||||
let (window, events) = (window.to_owned(), sink.clone());
|
||||
Arc::new(move |e| events.lock().unwrap().push((window.clone(), e)))
|
||||
}),
|
||||
local_data_dir: tmp.path().join("local"),
|
||||
..common::host_config(tmp.path())
|
||||
@@ -55,7 +58,7 @@ impl Harness {
|
||||
async fn request(&self) -> u32 {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
loop {
|
||||
if let Some(id) = self.events.lock().unwrap().iter().rev().find_map(|e| match e {
|
||||
if let Some(id) = self.events.lock().unwrap().iter().rev().find_map(|(_, e)| match e {
|
||||
IdeEvent::McpRequest { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
}) {
|
||||
@@ -67,6 +70,54 @@ impl Harness {
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
/// The requests `window` shows: asked there and not closed since.
|
||||
fn shown(&self, window: &str) -> Vec<(u32, McpUiRequest)> {
|
||||
let mut shown = Vec::new();
|
||||
for (_, event) in self.events.lock().unwrap().iter().filter(|(w, _)| w == window) {
|
||||
match event {
|
||||
IdeEvent::McpRequest { id, request } => shown.push((*id, request.clone())),
|
||||
IdeEvent::McpRequestClosed { id } => shown.retain(|(open, _)| open != id),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
shown
|
||||
}
|
||||
/// Waits until `window` shows `count` requests, and returns them.
|
||||
async fn shown_in(&self, window: &str, count: usize) -> Vec<(u32, McpUiRequest)> {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
loop {
|
||||
let shown = self.shown(window);
|
||||
if shown.len() >= count {
|
||||
return shown;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| panic!("{window} shows no {count} requests"))
|
||||
}
|
||||
/// The request `window` shows, once it shows one.
|
||||
async fn request_in(&self, window: &str) -> (u32, McpUiRequest) {
|
||||
self.shown_in(window, 1).await.pop().unwrap()
|
||||
}
|
||||
/// Whether `window` was told that request `id` closed.
|
||||
fn closed_in(&self, window: &str, id: u32) -> bool {
|
||||
let events = self.events.lock().unwrap();
|
||||
events
|
||||
.iter()
|
||||
.any(|(w, e)| w == window && matches!(e, IdeEvent::McpRequestClosed { id: closed } if *closed == id))
|
||||
}
|
||||
/// Reports `window` focused, as its frontend does when the user brings it to the front.
|
||||
fn focus(&self, window: &str) {
|
||||
self.host.mcp_reports.set_focused_editor(window, None, true);
|
||||
}
|
||||
/// Opens the window `second` on the folder `second` next to the open project.
|
||||
fn open_second(&self) -> PathBuf {
|
||||
let second = self.root.parent().unwrap().join("second");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
self.host.open_project("second", &second).unwrap();
|
||||
second
|
||||
}
|
||||
async fn call(&self, name: &str, args: Value) -> String {
|
||||
let (host, root, name) = (self.host.clone(), self.root.clone(), name.to_owned());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
@@ -252,6 +303,10 @@ async fn restricted_projects_have_only_read_tools_and_remote_projects_explain_th
|
||||
assert!(!h.host.project("main").unwrap().is_trusted());
|
||||
let registry = Registry::new(h.host.clone());
|
||||
assert!(registry.tools(&h.root).unwrap().iter().all(|t| t.read_only && !t.destructive));
|
||||
// A tool that writes, called all the same, says why it can't run.
|
||||
let refused = h.error("create_new_file", json!({"pathInProject":"x.txt","text":"no"})).await;
|
||||
assert_eq!(refused, "Project is in Restricted Mode. Trust the project to enable execution.");
|
||||
assert!(!h.root.join("x.txt").exists());
|
||||
assert!(!h.host.global_settings.effective().mcp_server.enabled);
|
||||
h.host.mcp_reports.set_remote("remote", PathBuf::from("/remote/project"));
|
||||
assert_eq!(
|
||||
@@ -391,7 +446,11 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
|
||||
assert!(p.documents.is_dirty(doc.id).unwrap());
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old text\nneedle needle\n");
|
||||
assert!(
|
||||
h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::DocPatched { doc: id, .. } if *id == doc.id))
|
||||
h.events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|(_, e)| matches!(e, IdeEvent::DocPatched { doc: id, .. } if *id == doc.id))
|
||||
);
|
||||
let edit_id = h
|
||||
.events
|
||||
@@ -399,7 +458,7 @@ async fn mutations_preserve_unsaved_text_and_reject_metadata_and_escapes() {
|
||||
.unwrap()
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|event| match event {
|
||||
.find_map(|(_, event)| match event {
|
||||
// Undoable like a refactoring, but marked as the agent's, so it isn't announced as one.
|
||||
IdeEvent::WorkspaceEditApplied { id, by_agent, .. } => {
|
||||
assert!(*by_agent, "an MCP edit is the agent's");
|
||||
@@ -438,14 +497,16 @@ async fn execution_requires_a_window_and_denial_never_runs_a_build() {
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let denied = h.error("build_project", json!({}));
|
||||
let answer = async {
|
||||
let id = h.request().await;
|
||||
let (id, request) = h.request_in("main").await;
|
||||
// A window's own project is not a background one.
|
||||
assert!(matches!(request, McpUiRequest::Confirm { background: false, .. }), "{request:?}");
|
||||
assert!(h.host.mcp_requests.answer("other", id, true, None).is_err());
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, answer);
|
||||
assert!(error.contains("denied by the user"), "{error}");
|
||||
assert!(h.host.processes.list().is_empty());
|
||||
assert!(h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequestClosed { .. })));
|
||||
assert!(h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequestClosed { .. })));
|
||||
h.events.lock().unwrap().clear();
|
||||
let closed = h.error("build_project", json!({}));
|
||||
let close = async {
|
||||
@@ -774,7 +835,7 @@ fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig
|
||||
tokio::spawn(async move {
|
||||
let mut handled = std::collections::HashSet::new();
|
||||
loop {
|
||||
let request = events.lock().unwrap().iter().find_map(|e| match e {
|
||||
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) =>
|
||||
{
|
||||
@@ -847,11 +908,9 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
|
||||
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 {
|
||||
/// A shell configuration named `MCP test` that prints `windowless` and exits with 3.
|
||||
fn windowless_config() -> ide_run::RunConfig {
|
||||
ide_run::RunConfig {
|
||||
id: "test".into(),
|
||||
name: "MCP test".into(),
|
||||
kind: "shell".into(),
|
||||
@@ -864,8 +923,14 @@ async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
ide_run::save_user_configs(&h.root, &[config]).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[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;
|
||||
ide_run::save_user_configs(&h.root, &[windowless_config()]).unwrap();
|
||||
h.host
|
||||
.global_settings
|
||||
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
|
||||
@@ -873,7 +938,7 @@ async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
|
||||
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");
|
||||
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -1020,7 +1085,7 @@ async fn brave_mode_runs_tools_without_asking_only_from_the_global_settings() {
|
||||
.expect("ran without waiting for an answer")
|
||||
.unwrap();
|
||||
assert!(!format!("{result:?}").contains("denied"), "{result:?}");
|
||||
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -1052,7 +1117,7 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
|
||||
tokio::spawn(async move {
|
||||
let mut handled = std::collections::HashSet::new();
|
||||
loop {
|
||||
let request = events.lock().unwrap().iter().find_map(|e| match e {
|
||||
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
|
||||
IdeEvent::McpRequest {
|
||||
id,
|
||||
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env },
|
||||
@@ -1166,8 +1231,12 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() {
|
||||
assert_eq!(stopped["state"], "stoppedByAgent", "{stopped}");
|
||||
assert!(stopped.get("interventions").is_none());
|
||||
|
||||
// The user's Stop, rerun and closing the tab are reported with their time.
|
||||
h.json("run_command", json!({"name": "server", "command": "sleep 30", "timeout": 0})).await;
|
||||
// The user's Stop, rerun and closing the tab are reported with their time. A stop waits for the command
|
||||
// itself: a Ctrl+C while the login shell still reads its profile can be taken by a profile command that
|
||||
// handles it, and the shell then runs the command anyway.
|
||||
let ready = json!({"name": "server", "command": "echo ready; sleep 30", "pattern": "(?m)^ready", "timeout": 10000});
|
||||
let ready = h.json("run_command", ready).await;
|
||||
assert_eq!((&ready["waitEnded"], &ready["state"]), (&json!("matched"), &json!("running")), "{ready}");
|
||||
ide_host::ops::run::run_stop(&h.host, "main", agent_process(&h, "_agent_server")).unwrap();
|
||||
let stop = h.json("wait_for_run", json!({"name": "server", "timeout": 10000})).await;
|
||||
assert!(stop["interventions"][0]["message"].as_str().unwrap().starts_with("The user stopped this command at"));
|
||||
@@ -1217,7 +1286,10 @@ async fn agent_commands_run_in_named_tabs_and_report_what_the_user_did() {
|
||||
assert_eq!(head["output"], "one\n<<<...content truncated...>>>\n", "{head}");
|
||||
|
||||
// Ctrl+C stops the command as stop_run does; terminal keys have no meaning on pipes.
|
||||
h.json("run_command", json!({"name": "interrupt", "command": "sleep 30", "timeout": 0})).await;
|
||||
let ready =
|
||||
json!({"name": "interrupt", "command": "echo ready; sleep 30", "pattern": "(?m)^ready", "timeout": 10000});
|
||||
let ready = h.json("run_command", ready).await;
|
||||
assert_eq!((&ready["waitEnded"], &ready["state"]), (&json!("matched"), &json!("running")), "{ready}");
|
||||
let key = h.error("send_run_input", json!({"name": "interrupt", "keys": ["Up"]})).await;
|
||||
assert!(key.contains("runs on pipes"), "{key}");
|
||||
h.json("send_run_input", json!({"name": "interrupt", "keys": ["Ctrl+C"]})).await;
|
||||
@@ -1539,22 +1611,91 @@ async fn a_folder_without_a_window_is_opened_by_its_first_tool_call() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn with_background_projects_off_a_folder_outside_the_open_projects_is_refused() {
|
||||
async fn with_background_projects_off_a_folder_outside_the_open_projects_lists_tools_and_refuses_calls() {
|
||||
let h = Harness::new();
|
||||
let inventory = h.root.parent().unwrap().join("inventory");
|
||||
std::fs::create_dir_all(&inventory).unwrap();
|
||||
let (_server, discovery) = h.server();
|
||||
let list = rpc(1, "tools/list", json!({}));
|
||||
let read = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"a.txt"}}));
|
||||
for reply in bridged(&discovery, &inventory, &[list, read]).await {
|
||||
assert_eq!(reply["error"]["code"], -32001, "{reply}");
|
||||
let message = reply["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't served in the background"), "{message}");
|
||||
}
|
||||
let replies = bridged(&discovery, &inventory, &[list, read]).await;
|
||||
let tools = replies[0]["result"]["tools"].as_array().unwrap();
|
||||
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
|
||||
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
|
||||
let message = replies[1]["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("isn't served in the background"), "{message}");
|
||||
assert!(h.background().is_empty());
|
||||
assert_eq!(h.host.projects().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_connection_in_a_folder_no_project_serves_lists_the_tools_and_each_call_names_its_project() {
|
||||
let h = Harness::new();
|
||||
// A folder that only holds repositories: one trusted, one not.
|
||||
let work = h.root.parent().unwrap().join("work");
|
||||
let (inventory, ledger) = (work.join("inventory"), work.join("ledger"));
|
||||
for project in [&inventory, &ledger] {
|
||||
std::fs::create_dir_all(project.join("src")).unwrap();
|
||||
}
|
||||
std::fs::write(inventory.join("src/stock.txt"), "forty crates\n").unwrap();
|
||||
h.set("enabled", json!(true));
|
||||
h.set("backgroundProjects", json!("listed"));
|
||||
h.set("backgroundProjectPaths", json!([inventory, ledger]));
|
||||
h.host.set_project_trust(&inventory, true, false).await.unwrap();
|
||||
let (_server, discovery) = h.server();
|
||||
|
||||
let requests =
|
||||
[rpc(1, "initialize", json!({})), rpc(2, "tools/list", json!({})), rpc(3, "openidea/servesFolder", json!({}))];
|
||||
let replies = bridged(&discovery, &work, &requests).await;
|
||||
let instructions = replies[0]["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains("no project of its own: pass `projectPath`"), "{instructions}");
|
||||
let tools = replies[1]["result"]["tools"].as_array().unwrap();
|
||||
assert!(tools.iter().any(|t| t["name"] == "create_new_file" && t["annotations"]["readOnlyHint"] == false));
|
||||
assert_eq!(replies[2]["result"], json!({ "root": null }), "{}", replies[2]);
|
||||
assert!(h.background().is_empty(), "initialize, tools/list and servesFolder open nothing");
|
||||
|
||||
// A tool that writes is refused for the untrusted project before it loads; a call that
|
||||
// names no project is refused too.
|
||||
let create = rpc(
|
||||
4,
|
||||
"tools/call",
|
||||
json!({"name":"create_new_file","arguments":{
|
||||
"projectPath":ledger,"pathInProject":"notes.txt","text":"no"}}),
|
||||
);
|
||||
let unnamed = rpc(5, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/stock.txt"}}));
|
||||
let replies = bridged(&discovery, &work, &[create, unnamed]).await;
|
||||
assert_eq!(replies[0]["result"]["isError"], true, "{}", replies[0]);
|
||||
let refused = replies[0]["result"]["content"][0]["text"].as_str().unwrap();
|
||||
assert!(refused.contains("Restricted Mode"), "{refused}");
|
||||
assert!(!ledger.join("notes.txt").exists());
|
||||
assert_eq!(replies[1]["error"]["code"], -32001, "{}", replies[1]);
|
||||
assert!(h.background().is_empty(), "refusals open nothing");
|
||||
|
||||
// Inside a served project, servesFolder names it, and loads nothing either.
|
||||
let serves = [rpc(7, "openidea/servesFolder", json!({}))];
|
||||
let replies = bridged(&discovery, &inventory.join("src"), &serves).await;
|
||||
assert_eq!(replies[0]["result"], json!({ "root": inventory }), "{}", replies[0]);
|
||||
assert!(h.background().is_empty());
|
||||
|
||||
let read = rpc(
|
||||
6,
|
||||
"tools/call",
|
||||
json!({"name":"read_file","arguments":{
|
||||
"projectPath":inventory,"file_path":"src/stock.txt"}}),
|
||||
);
|
||||
let replies = bridged(&discovery, &work, &[read]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: forty crates\nL2: ", "{replies:?}");
|
||||
assert_eq!(h.background(), std::slice::from_ref(&inventory));
|
||||
|
||||
// A remote window's root is that host's to serve.
|
||||
let remote = work.join("remote");
|
||||
std::fs::create_dir_all(&remote).unwrap();
|
||||
h.host.mcp_reports.set_remote("remote", remote.clone());
|
||||
let replies = bridged(&discovery, &remote, &serves).await;
|
||||
assert_eq!(replies[0]["result"], json!({ "root": null }), "{}", replies[0]);
|
||||
h.host.close_project_detached("remote");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_tools_of_a_background_project_are_the_same_before_and_after_it_opens() {
|
||||
let h = Harness::new();
|
||||
@@ -1596,14 +1737,15 @@ async fn post(server: &ide_mcp::McpServer, body: &Value) -> Value {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_open_in_a_window_answers_before_any_background_project() {
|
||||
async fn a_project_open_in_a_window_answers_for_its_folders_that_no_nested_project_holds() {
|
||||
let h = Harness::new();
|
||||
let inventory = h.serve_inventory();
|
||||
// A listed folder inside the open project: the window's project answers for it.
|
||||
h.set("backgroundProjectPaths", json!([inventory, h.root.join("src")]));
|
||||
// A listed folder around the open project leaves the project's folders to its window.
|
||||
let around = h.root.parent().unwrap().to_path_buf();
|
||||
h.set("backgroundProjectPaths", json!([inventory, around]));
|
||||
let (server, discovery) = h.server();
|
||||
let inside = json!({"projectPath": h.root.join("src"), "file_path": "src/b.txt"});
|
||||
let read = rpc(1, "tools/call", json!({"name":"read_file","arguments":inside.clone()}));
|
||||
let read = rpc(1, "tools/call", json!({"name":"read_file","arguments":inside}));
|
||||
let replies = bridged(&discovery, &inventory, &[read]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: needle\nL2: ", "{replies:?}");
|
||||
assert!(h.background().is_empty());
|
||||
@@ -1614,13 +1756,13 @@ async fn a_project_open_in_a_window_answers_before_any_background_project() {
|
||||
let unnamed = rpc(2, "tools/call", json!({"name":"read_file","arguments":{"file_path":"src/b.txt"}}));
|
||||
let reply = post(&server, &unnamed).await;
|
||||
assert_eq!(reply["result"]["content"][0]["text"], "L1: needle\nL2: ", "{reply}");
|
||||
// Nor does a background project loaded inside the window's project take its folder over.
|
||||
// A folder listed inside the window's project is a project of its own (#7040).
|
||||
let nested = h.root.join("src");
|
||||
h.call_at(&nested, "read_file", json!({"file_path":"b.txt"})).await.unwrap();
|
||||
assert_eq!(h.background(), [inventory.clone(), nested]);
|
||||
let read = rpc(3, "tools/call", json!({"name":"read_file","arguments":inside}));
|
||||
h.set("backgroundProjectPaths", json!([inventory, around, nested]));
|
||||
let read = rpc(3, "tools/call", json!({"name":"read_file","arguments":{"projectPath":nested,"file_path":"b.txt"}}));
|
||||
let replies = bridged(&discovery, &inventory, &[read]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: needle\nL2: ", "{replies:?}");
|
||||
assert_eq!(h.background(), [inventory.clone(), nested]);
|
||||
// A second window on another root is served as before.
|
||||
let second = h.root.parent().unwrap().join("second");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
@@ -1631,6 +1773,61 @@ async fn a_project_open_in_a_window_answers_before_any_background_project() {
|
||||
assert_eq!(h.background().len(), 2);
|
||||
}
|
||||
|
||||
/// The layout of #7040: `marker.txt` in the window's project and in `contracts`, a trusted
|
||||
/// repository inside it that trusted mode serves in the background.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_nested_trusted_project_answers_for_its_folders_whether_or_not_a_window_is_open_around_it() {
|
||||
let h = Harness::new();
|
||||
std::fs::write(h.root.join("marker.txt"), "from packages").unwrap();
|
||||
let contracts = h.root.join("contracts");
|
||||
std::fs::create_dir_all(contracts.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(contracts.join("src")).unwrap();
|
||||
std::fs::write(contracts.join("marker.txt"), "from contracts").unwrap();
|
||||
std::fs::write(contracts.join("src/only.txt"), "only in contracts").unwrap();
|
||||
h.trust().await;
|
||||
h.host.trust.decide(&contracts, true, false).unwrap();
|
||||
h.set("enabled", json!(true));
|
||||
h.set("backgroundProjects", json!("trusted"));
|
||||
let (server, discovery) = h.server();
|
||||
let read = |file: &str| {
|
||||
let arguments = json!({"projectPath": contracts, "file_path": file});
|
||||
rpc(1, "tools/call", json!({"name":"read_file","arguments":arguments}))
|
||||
};
|
||||
let text = |reply: Value| reply["result"]["content"][0]["text"].as_str().map(str::to_owned).ok_or(reply);
|
||||
|
||||
h.host.close_project("main");
|
||||
assert_eq!(text(post(&server, &read("marker.txt")).await), Ok("L1: from contracts".to_owned()));
|
||||
// A window opens on the folder around it between two calls.
|
||||
h.host.open_project("main", &h.root).unwrap();
|
||||
assert_eq!(text(post(&server, &read("marker.txt")).await), Ok("L1: from contracts".to_owned()));
|
||||
assert_eq!(text(post(&server, &read("src/only.txt")).await), Ok("L1: only in contracts".to_owned()));
|
||||
let roots = rpc(2, "tools/call", json!({"name":"get_workspace_roots","arguments":{"projectPath":contracts}}));
|
||||
let roots = post(&server, &roots).await;
|
||||
assert_eq!(roots["result"]["structuredContent"]["projectRoot"], json!(contracts), "{roots}");
|
||||
// The stdio bridge started in the nested project reaches it too.
|
||||
let unnamed = rpc(3, "tools/call", json!({"name":"read_file","arguments":{"file_path":"marker.txt"}}));
|
||||
let replies = bridged(&discovery, &contracts.join("src"), &[unnamed]).await;
|
||||
assert_eq!(replies[0]["result"]["content"][0]["text"], "L1: from contracts", "{replies:?}");
|
||||
assert_eq!(h.background(), std::slice::from_ref(&contracts));
|
||||
|
||||
// A folder of the window's project that no nested project holds stays with the window.
|
||||
let outside = json!({"projectPath": h.root.join("src"), "file_path": "marker.txt"});
|
||||
let reply = post(&server, &rpc(4, "tools/call", json!({"name":"read_file","arguments":outside}))).await;
|
||||
assert_eq!(text(reply), Ok("L1: from packages".to_owned()));
|
||||
assert_eq!(h.background(), std::slice::from_ref(&contracts), "it loads nothing");
|
||||
|
||||
// A remote window's project at the same path keeps its folders, the nested one included:
|
||||
// they are that host's.
|
||||
h.host.close_project("main");
|
||||
h.host.mcp_reports.set_remote("remote", h.root.clone());
|
||||
let reply = post(&server, &read("marker.txt")).await;
|
||||
assert_eq!(
|
||||
reply["result"]["content"][0]["text"],
|
||||
"project is on a remote host; connect to the MCP server on that host"
|
||||
);
|
||||
h.host.close_project_detached("remote");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn tools_fed_by_a_window_say_that_a_background_project_has_none() {
|
||||
let h = Harness::new();
|
||||
@@ -1657,31 +1854,215 @@ async fn tools_fed_by_a_window_say_that_a_background_project_has_none() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn tools_that_ask_the_user_fail_closed_in_a_background_project() {
|
||||
async fn tools_that_need_a_window_refuse_in_a_background_project_before_asking() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
for (tool, args) in [
|
||||
("build_project", json!({})),
|
||||
("run_command", json!({"name":"check","command":"true"})),
|
||||
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
|
||||
] {
|
||||
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
|
||||
assert!(error.contains("no project window"), "{tool}: {error}");
|
||||
let root = inventory.display();
|
||||
// Running without confirmation does not give them a window either.
|
||||
for brave in [false, true] {
|
||||
h.set("runWithoutConfirmation", json!(brave));
|
||||
for (tool, args) in [
|
||||
("run_command", json!({"name":"check","command":"true"})),
|
||||
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
|
||||
("xdebug_start_debugger_session", json!({"filePath":"src/stock.txt","line":1})),
|
||||
("xdebug_set_breakpoint", json!({"filePath":"src/stock.txt","line":1})),
|
||||
("xdebug_remove_breakpoint", json!({})),
|
||||
("xdebug_list_breakpoints", json!({})),
|
||||
] {
|
||||
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
|
||||
assert_eq!(
|
||||
error,
|
||||
format!("{tool} needs the project open in a window: {root} is served in the background.")
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
|
||||
assert!(h.host.processes.list().is_empty());
|
||||
// Running without confirmation does not give `run_command` or the editor a window.
|
||||
h.set("runWithoutConfirmation", json!(true));
|
||||
for (tool, args) in [
|
||||
("run_command", json!({"name":"check","command":"true"})),
|
||||
("open_file_in_editor", json!({"filePath":"src/stock.txt"})),
|
||||
] {
|
||||
let error = h.call_at(&inventory, tool, args).await.unwrap_err();
|
||||
assert!(error.contains("no project window"), "{tool}: {error}");
|
||||
}
|
||||
assert_eq!(h.background(), [inventory]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_background_project_asks_in_the_most_recently_focused_project_window() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let second = h.open_second();
|
||||
h.host.set_project_trust(&second, true, false).await.unwrap();
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
let error = h.call_at(&inventory, "build_project", json!({})).await.unwrap_err();
|
||||
assert!(error.contains("no project window is available"), "{error}");
|
||||
for window in ["main", "second"] {
|
||||
h.host.mcp_requests.set_ready(window, true);
|
||||
}
|
||||
h.focus("second");
|
||||
h.focus("main");
|
||||
let denied = h.call_at(&inventory, "build_project", json!({}));
|
||||
let deny = async {
|
||||
let (id, request) = h.request_in("main").await;
|
||||
let McpUiRequest::Confirm { background, project, .. } = request else { panic!("{request:?}") };
|
||||
assert!(background);
|
||||
assert_eq!(project, ide_core::ipc_path::to_ipc(&inventory));
|
||||
assert!(h.shown("second").is_empty());
|
||||
assert!(h.host.mcp_requests.answer("second", id, true, None).is_err());
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, deny);
|
||||
assert!(error.unwrap_err().contains("denied by the user"));
|
||||
assert!(h.host.processes.list().is_empty());
|
||||
|
||||
// Allowed there, a configuration runs on its own, as without a window under brave mode.
|
||||
ide_run::save_user_configs(&inventory, &[windowless_config()]).unwrap();
|
||||
let run =
|
||||
h.call_at(&inventory, "execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
|
||||
let allow = async {
|
||||
let (id, request) = h.request_in("main").await;
|
||||
assert!(matches!(request, McpUiRequest::Confirm { background: true, .. }), "{request:?}");
|
||||
h.host.mcp_requests.answer("main", id, true, None).unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(run, allow);
|
||||
let result: Value = serde_json::from_str(&result.unwrap()).unwrap();
|
||||
assert_eq!(result["exitCode"], 3, "{result}");
|
||||
assert!(result["output"].as_str().unwrap().contains("windowless"));
|
||||
|
||||
std::fs::write(inventory.join("api.http"), "### Health\nGET http://127.0.0.1:9/health\n").unwrap();
|
||||
let denied = h.call_at(&inventory, "http_run_request", json!({"path":"api.http","index":0}));
|
||||
let deny = async {
|
||||
let (id, request) = h.request_in("main").await;
|
||||
assert!(matches!(request, McpUiRequest::Confirm { background: true, .. }), "{request:?}");
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, deny);
|
||||
assert!(error.unwrap_err().contains("denied by the user"));
|
||||
assert!(h.shown("second").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn requests_for_two_background_projects_queue_in_one_window() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let inventory = h.serve_inventory();
|
||||
let ledger = h.root.parent().unwrap().join("ledger");
|
||||
std::fs::create_dir_all(&ledger).unwrap();
|
||||
h.set("backgroundProjectPaths", json!([inventory, ledger]));
|
||||
for root in [&inventory, &ledger] {
|
||||
h.host.trust.decide(root, true, false).unwrap();
|
||||
}
|
||||
let first = h.call_at(&inventory, "build_project", json!({}));
|
||||
let second = h.call_at(&ledger, "build_project", json!({}));
|
||||
let deny = async {
|
||||
let shown = h.shown_in("main", 2).await;
|
||||
let mut projects: Vec<_> = shown
|
||||
.iter()
|
||||
.map(|(_, request)| match request {
|
||||
McpUiRequest::Confirm { project, background: true, .. } => PathBuf::from(project),
|
||||
other => panic!("{other:?}"),
|
||||
})
|
||||
.collect();
|
||||
projects.sort();
|
||||
assert_eq!(projects, [inventory.clone(), ledger.clone()]);
|
||||
for (id, _) in shown {
|
||||
h.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
}
|
||||
};
|
||||
let (first, second, ()) = tokio::join!(first, second, deny);
|
||||
for error in [first.unwrap_err(), second.unwrap_err()] {
|
||||
assert!(error.contains("denied by the user"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_request_moves_when_its_window_closes_and_fails_when_none_is_left() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let second = h.open_second();
|
||||
h.host.set_project_trust(&second, true, false).await.unwrap();
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
for window in ["second", "main"] {
|
||||
h.host.mcp_requests.set_ready(window, true);
|
||||
h.focus(window);
|
||||
}
|
||||
let denied = h.call_at(&inventory, "build_project", json!({}));
|
||||
let moves = async {
|
||||
let (id, _) = h.request_in("main").await;
|
||||
h.host.close_project_detached("main");
|
||||
let (moved, _) = h.request_in("second").await;
|
||||
assert_eq!(moved, id);
|
||||
assert!(h.closed_in("main", id));
|
||||
h.host.mcp_requests.answer("second", id, false, None).unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(denied, moves);
|
||||
assert!(error.unwrap_err().contains("denied by the user"));
|
||||
|
||||
let closed = h.call_at(&inventory, "build_project", json!({}));
|
||||
let close = async {
|
||||
let (id, _) = h.request_in("second").await;
|
||||
h.host.close_project_detached("second");
|
||||
id
|
||||
};
|
||||
let (error, id) = tokio::join!(closed, close);
|
||||
assert!(error.unwrap_err().contains("project window closed"));
|
||||
assert!(h.closed_in("second", id));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_request_leaves_the_window_when_its_project_unloads_or_the_call_is_cancelled() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
h.host.mcp_requests.set_ready("main", true);
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
let unloaded = h.call_at(&inventory, "build_project", json!({}));
|
||||
let unload = async {
|
||||
let (id, _) = h.request_in("main").await;
|
||||
assert!(h.host.mcp_background.detach(&h.host, &inventory, None));
|
||||
id
|
||||
};
|
||||
let (error, id) = tokio::join!(unloaded, unload);
|
||||
assert!(error.unwrap_err().contains("project window closed"));
|
||||
assert!(h.closed_in("main", id));
|
||||
|
||||
let (host, root, cancel) = (h.host.clone(), inventory.clone(), CancellationToken::new());
|
||||
let token = cancel.clone();
|
||||
let cancelled = tokio::task::spawn_blocking(move || Registry::new(host).call(&root, "build_project", "{}", token));
|
||||
let (id, _) = h.request_in("main").await;
|
||||
cancel.cancel();
|
||||
assert!(cancelled.await.unwrap().is_err());
|
||||
assert!(h.closed_in("main", id));
|
||||
assert!(h.shown("main").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_untrusted_window_never_shows_a_background_request() {
|
||||
let h = Harness::new();
|
||||
h.trust().await;
|
||||
let second = h.open_second();
|
||||
let inventory = h.serve_inventory();
|
||||
h.host.trust.decide(&inventory, true, false).unwrap();
|
||||
// `second` is untrusted and focused last; its ready mark is a stale one.
|
||||
for window in ["main", "second"] {
|
||||
h.host.mcp_requests.set_ready(window, true);
|
||||
h.focus(window);
|
||||
}
|
||||
let call = h.call_at(&inventory, "build_project", json!({}));
|
||||
let moves = async {
|
||||
let (id, _) = h.request_in("main").await;
|
||||
assert!(h.shown("second").is_empty());
|
||||
h.host.set_project_trust(&second, true, false).await.unwrap();
|
||||
h.host.set_project_trust(&h.root, false, false).await.unwrap();
|
||||
let (moved, _) = h.request_in("second").await;
|
||||
assert_eq!(moved, id);
|
||||
assert!(h.closed_in("main", id));
|
||||
h.host.set_project_trust(&second, false, false).await.unwrap();
|
||||
};
|
||||
let (error, ()) = tokio::join!(call, moves);
|
||||
assert!(error.unwrap_err().contains("project window closed"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_cancelled_or_failed_call_leaves_nothing_holding_the_project() {
|
||||
let h = Harness::new();
|
||||
@@ -1787,7 +2168,7 @@ fn debugger_window(h: &Harness) {
|
||||
tokio::spawn(async move {
|
||||
let mut handled = std::collections::HashSet::new();
|
||||
loop {
|
||||
let request = events.lock().unwrap().iter().find_map(|e| match e {
|
||||
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
|
||||
IdeEvent::McpRequest { id, request }
|
||||
if !handled.contains(id)
|
||||
&& matches!(
|
||||
|
||||
@@ -70,6 +70,20 @@ impl Harness {
|
||||
fn run(&self, id: &str, arg: Option<&str>) -> ide_core::IdeResult<Option<String>> {
|
||||
self.plugins.run_command(ID, id, arg, self.invocation())
|
||||
}
|
||||
/// The folder `inventory` next to the project, listed to be served without a window.
|
||||
fn serve_inventory(&self) -> PathBuf {
|
||||
let inventory = self.root.parent().unwrap().join("inventory");
|
||||
std::fs::create_dir(&inventory).unwrap();
|
||||
for (key, value) in [
|
||||
("enabled", serde_json::json!(true)),
|
||||
("backgroundProjects", serde_json::json!("listed")),
|
||||
("backgroundProjectPaths", serde_json::json!([inventory])),
|
||||
] {
|
||||
let key = format!("mcpServer.{key}");
|
||||
self.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
|
||||
}
|
||||
inventory
|
||||
}
|
||||
fn source(&self) -> String {
|
||||
serde_json::json!({"id":"local","name":"Example","driver":"sqlite","database":self.root.join("db.sqlite").to_string_lossy(),"options":[]}).to_string()
|
||||
}
|
||||
@@ -189,21 +203,66 @@ async fn mcp_listing_dispatch_confirmation_and_lifecycle_use_plugin_authority()
|
||||
assert!(spin.await.unwrap().is_err(), "command budget interrupts wasm");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_destructive_plugin_tool_of_a_background_project_asks_in_a_project_window() {
|
||||
let f = Harness::with_timeout(Duration::from_secs(10));
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
let inventory = f.serve_inventory();
|
||||
f.host.trust.decide(&inventory, true, false).unwrap();
|
||||
f.host.mcp_requests.set_ready("main", true);
|
||||
let (registry, root) = (Registry::new(f.host.clone()), inventory.clone());
|
||||
let call = tokio::task::spawn_blocking(move || {
|
||||
registry.call(&root, "test_data_tools__erase", "{}", CancellationToken::new())
|
||||
});
|
||||
let (window, id, background) = tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
if let Some(found) = f.events.lock().unwrap().iter().find_map(|(w, e)| match e {
|
||||
IdeEvent::McpRequest { id, request: McpUiRequest::Confirm { background, .. } } => {
|
||||
Some((w.clone(), *id, *background))
|
||||
}
|
||||
_ => None,
|
||||
}) {
|
||||
break found;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((window.as_str(), background), ("main", true));
|
||||
f.host.mcp_requests.answer("main", id, false, None).unwrap();
|
||||
let denied = call.await.unwrap().unwrap_err();
|
||||
assert!(format!("{denied:?}").contains("denied by the user"), "{denied:?}");
|
||||
f.host.close_project(&ide_host::mcp::BackgroundProjects::key(&inventory));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plugin_tools_take_the_project_path_and_refuse_an_untrusted_project_before_it_loads() {
|
||||
let f = Harness::with_timeout(Duration::from_secs(10));
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
let inventory = f.serve_inventory();
|
||||
let registry = Registry::new(f.host.clone());
|
||||
// A connection without a project of its own lists the tool with `projectPath`, which its
|
||||
// calls have to pass, and the plugin's strict schema still takes the call.
|
||||
let listed = registry.tools_without_project();
|
||||
let echo = listed.iter().find(|t| t.name == "test_data_tools__echo").unwrap();
|
||||
assert!(echo.input_schema["properties"]["projectPath"].is_object(), "{}", echo.input_schema);
|
||||
let arguments = serde_json::json!({ "text": "hello", "projectPath": f.root }).to_string();
|
||||
let result = registry.call(&f.root, "test_data_tools__echo", &arguments, CancellationToken::new()).unwrap();
|
||||
assert!(result.contains("hello"), "{result}");
|
||||
// A tool that writes refuses the untrusted folder, and nothing loads.
|
||||
let refused = registry.call(&inventory, "test_data_tools__write", "{}", CancellationToken::new()).unwrap_err();
|
||||
let restricted = "Project is in Restricted Mode. Trust the project to enable execution.";
|
||||
assert_eq!(refused, ToolCallError::Failed(restricted.into()));
|
||||
assert!(f.host.mcp_background.snapshot(&f.host, std::time::Instant::now()).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_plugin_tool_call_holds_its_background_project_until_it_ends() {
|
||||
use ide_host::mcp::{BackgroundProjects, McpBackgroundHold};
|
||||
// The fixture's `spin` runs until it is cancelled or its budget ends.
|
||||
let f = Harness::with_timeout(Duration::from_secs(10));
|
||||
let inventory = f.root.parent().unwrap().join("inventory");
|
||||
std::fs::create_dir(&inventory).unwrap();
|
||||
for (key, value) in [
|
||||
("enabled", serde_json::json!(true)),
|
||||
("backgroundProjects", serde_json::json!("listed")),
|
||||
("backgroundProjectPaths", serde_json::json!([inventory])),
|
||||
] {
|
||||
let key = format!("mcpServer.{key}");
|
||||
f.host.global_settings.set(ide_workspace::SettingsScope::Global, &key, value).unwrap();
|
||||
}
|
||||
let inventory = f.serve_inventory();
|
||||
let held_by = || {
|
||||
let loaded = f.host.mcp_background.snapshot(&f.host, std::time::Instant::now());
|
||||
loaded.into_iter().next().map(|project| project.kept_open_by)
|
||||
|
||||
@@ -1590,6 +1590,28 @@ fn misbehave_with_language(dir: &Path) -> PathBuf {
|
||||
pkg
|
||||
}
|
||||
|
||||
/// A language activation fired before the plugin was there (a remote server gets the desktop's
|
||||
/// packages after the window opened its files; a plugin installed with such a file open)
|
||||
/// activates it once it loads; one that never fired doesn't.
|
||||
#[test]
|
||||
fn plugins_loaded_after_their_activation_event_fired_activate() {
|
||||
use ide_extension::ActivationEvent;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = Arc::new(
|
||||
PluginHost::new(tmp.path().join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap(),
|
||||
);
|
||||
host.load_all();
|
||||
host.startup_finished();
|
||||
host.activation_event(&ActivationEvent::Language("other".into()), None);
|
||||
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
|
||||
assert_eq!(host.info_of("misbehave").unwrap().status, PluginStatus::Inactive);
|
||||
host.uninstall("misbehave").unwrap();
|
||||
|
||||
host.activation_event(&ActivationEvent::Language("mis".into()), None);
|
||||
host.install_from_dir(&misbehave_with_language(tmp.path()), &Consent::all()).unwrap();
|
||||
assert!(eventually(|| host.info_of("misbehave").is_ok_and(|i| i.status == PluginStatus::Active)));
|
||||
}
|
||||
|
||||
/// Edit-path calls stop waiting at the soft deadline (the result is
|
||||
/// dropped, the instance kept) and are interrupted at the hard one.
|
||||
#[test]
|
||||
@@ -3027,6 +3049,38 @@ fn official_ai_completion_cancels_superseded_requests() {
|
||||
assert!(times[9] < Duration::from_millis(500), "{times:?}");
|
||||
}
|
||||
|
||||
/// Installed with the optional network permission refused (it is not ticked by
|
||||
/// default), a suggestion request says so in the window instead of failing silently.
|
||||
#[test]
|
||||
fn official_ai_completion_explains_a_refused_network_permission() {
|
||||
let f = fixture(Limits::default());
|
||||
f.host.install_from_dir(&official("ai-completion"), &Consent::default()).unwrap();
|
||||
let (port, seen) = http_server(r#"{"choices":[{"text":"a + b\n"}]}"#, |_| Duration::ZERO);
|
||||
f.run("openidea.ai-completion", "set-endpoint", Some(&format!("http://localhost:{port}"))).unwrap();
|
||||
f.take_events();
|
||||
let doc = ide_plugin::ProviderDocument {
|
||||
path: f.project.join("src/a.rs"),
|
||||
language: "rust".into(),
|
||||
version: 1,
|
||||
text: "let x = ".into(),
|
||||
};
|
||||
for _ in 0..2 {
|
||||
assert!(f.host.provide_inline_completion(&doc, ide_core::Pos::new(0, 8), &Default::default()).is_none());
|
||||
}
|
||||
assert!(seen.lock().is_empty(), "denied before connecting");
|
||||
let notices: Vec<String> = f
|
||||
.take_events()
|
||||
.into_iter()
|
||||
.filter_map(|(_, e)| match e {
|
||||
PluginEvent::Notification { level: NotificationLevel::Warning, body, .. } => Some(body),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(notices.len(), 1, "once: {notices:?}");
|
||||
assert!(notices[0].contains("Settings › Plugins › AI Completion"), "{notices:?}");
|
||||
assert_eq!(f.status("openidea.ai-completion"), PluginStatus::Active, "not a crash");
|
||||
}
|
||||
|
||||
/// Checkstyle: a save runs the approved `checkstyle` and publishes
|
||||
/// diagnostics; quick fixes come through the code-action provider; saving
|
||||
/// again cancels the check still running.
|
||||
@@ -8116,3 +8170,20 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent
|
||||
assert_eq!(dirs.len(), 1);
|
||||
assert!(dirs[0].ends_with("skills/good-skill"), "{dirs:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricting_a_project_without_its_plugins_announces_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let events: Events = Arc::default();
|
||||
let sink = {
|
||||
let events = events.clone();
|
||||
move |client: Option<&str>, e: PluginEvent| events.lock().push((client.map(str::to_owned), e))
|
||||
};
|
||||
let host = PluginHost::new(tmp.path().join("plugins"), Arc::new(sink), Limits::default()).unwrap();
|
||||
host.load_all();
|
||||
events.lock().clear();
|
||||
// A restricted window lists the plugins, which restricts its project again each time.
|
||||
host.restrict_project(tmp.path());
|
||||
host.restrict_project(tmp.path());
|
||||
assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged)));
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
//! A version control system besides Git plugs in through `BackendProvider`, the way
|
||||
//! Perforce and Subversion do: an in-memory fake here, so nothing but `git` has to be
|
||||
//! installed.
|
||||
mod common;
|
||||
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_host::{
|
||||
Host,
|
||||
ops::{fs, vcs},
|
||||
};
|
||||
use ide_vcs::{
|
||||
Backend, BackendChangelist, BackendProvider, BlameLine, BlockHistory, Branch, ChangeKind, ChangedFile, Commit,
|
||||
CommitOptions, FileStatus, LineHunk, LogDetails, LogQuery, PendingChange, RevisionChange, TextEncoding, VcsKind,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A working copy whose root holds a `.fake-vcs` file. Its changes are whatever the test
|
||||
/// says; it remembers what it was asked to stage and open for edit.
|
||||
struct Fake {
|
||||
root: PathBuf,
|
||||
changed: Mutex<Vec<PathBuf>>,
|
||||
unreachable: AtomicBool,
|
||||
staged: Mutex<Vec<PathBuf>>,
|
||||
opened: Mutex<Vec<PathBuf>>,
|
||||
/// The line of development checked out (`trunk` until switched).
|
||||
head: Mutex<String>,
|
||||
/// Its own changelists, named lists like Subversion's.
|
||||
lists: Mutex<Vec<BackendChangelist>>,
|
||||
}
|
||||
|
||||
impl Backend for Fake {
|
||||
fn root(&self) -> &Path {
|
||||
&self.root
|
||||
}
|
||||
fn kind(&self) -> VcsKind {
|
||||
VcsKind::Perforce
|
||||
}
|
||||
fn head_label(&self) -> Option<String> {
|
||||
Some(self.head.lock().clone())
|
||||
}
|
||||
fn update(&self, _: &CancellationToken, output: &dyn Fn(String)) -> IdeResult<()> {
|
||||
std::fs::write(self.root.join("a.txt"), "updated\n")?;
|
||||
output("Updated to revision 8.".into());
|
||||
Ok(())
|
||||
}
|
||||
fn branches(&self) -> IdeResult<Vec<Branch>> {
|
||||
let head = self.head.lock().clone();
|
||||
Ok(["trunk", "branches/x"]
|
||||
.map(|name| Branch {
|
||||
name: name.into(),
|
||||
remote: false,
|
||||
current: name == head,
|
||||
upstream: None,
|
||||
tracked_tip: None,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
outgoing: None,
|
||||
last_commit_ms: 0.0,
|
||||
commit: String::new(),
|
||||
})
|
||||
.into())
|
||||
}
|
||||
fn switch_to(&self, branch: &str) -> IdeResult<()> {
|
||||
*self.head.lock() = branch.into();
|
||||
Ok(())
|
||||
}
|
||||
fn changelists(&self) -> IdeResult<Option<Vec<BackendChangelist>>> {
|
||||
Ok(Some(self.lists.lock().clone()))
|
||||
}
|
||||
fn create_changelist(&self, name: &str, comment: &str) -> IdeResult<String> {
|
||||
let list = BackendChangelist { id: name.into(), name: name.into(), comment: comment.into(), files: Vec::new() };
|
||||
self.lists.lock().push(list);
|
||||
Ok(name.into())
|
||||
}
|
||||
fn edit_changelist(&self, id: &str, name: &str, comment: &str) -> IdeResult<()> {
|
||||
let mut lists = self.lists.lock();
|
||||
let list = lists.iter_mut().find(|l| l.id == id).ok_or_else(|| IdeError::not_found(id))?;
|
||||
(list.name, list.comment) = (name.into(), comment.into());
|
||||
Ok(())
|
||||
}
|
||||
fn delete_changelist(&self, id: &str) -> IdeResult<()> {
|
||||
self.lists.lock().retain(|l| l.id != id);
|
||||
Ok(())
|
||||
}
|
||||
fn move_to_changelist(&self, paths: &[PathBuf], id: &str) -> IdeResult<()> {
|
||||
let mut lists = self.lists.lock();
|
||||
for list in lists.iter_mut() {
|
||||
list.files.retain(|f| !paths.contains(&f.0));
|
||||
}
|
||||
if let Some(list) = lists.iter_mut().find(|l| l.id == id) {
|
||||
list.files.extend(paths.iter().map(|p| p.clone().into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn status(&self) -> IdeResult<Vec<FileStatus>> {
|
||||
if self.unreachable.load(Ordering::Acquire) {
|
||||
return Err(IdeError::unavailable("server unreachable"));
|
||||
}
|
||||
Ok(self
|
||||
.changed
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|p| FileStatus {
|
||||
path: p.clone().into(),
|
||||
rel_path: p.strip_prefix(&self.root).unwrap().to_string_lossy().into_owned(),
|
||||
staged: None,
|
||||
unstaged: Some(ChangeKind::Modified),
|
||||
renamed_from: None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
fn file_bytes_at(&self, _: &Path, _: Option<&str>) -> IdeResult<Option<Vec<u8>>> {
|
||||
Ok(None)
|
||||
}
|
||||
fn file_at(&self, _: &Path, _: Option<&str>, _: TextEncoding) -> IdeResult<Option<String>> {
|
||||
Ok(None)
|
||||
}
|
||||
fn file_mode_at(&self, _: &Path, _: Option<&str>) -> IdeResult<Option<String>> {
|
||||
Ok(None)
|
||||
}
|
||||
fn diff_text(&self, _: &Path, _: bool, _: TextEncoding) -> IdeResult<String> {
|
||||
Ok(String::new())
|
||||
}
|
||||
fn working_tree_patch(
|
||||
&self,
|
||||
_: Option<&Path>,
|
||||
_: Option<&str>,
|
||||
_: usize,
|
||||
_: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
Ok(String::new())
|
||||
}
|
||||
fn line_hunks(&self, _: &Path, _: &str, _: bool, _: TextEncoding) -> IdeResult<Vec<LineHunk>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn blame(&self, _: &Path, _: Option<&str>, _: Option<&str>, _: TextEncoding) -> IdeResult<Vec<BlameLine>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn block_history(
|
||||
&self,
|
||||
_: &Path,
|
||||
_: Option<&str>,
|
||||
_: (u32, u32),
|
||||
_: TextEncoding,
|
||||
_: &CancellationToken,
|
||||
) -> IdeResult<BlockHistory> {
|
||||
Err(IdeError::unavailable("no block history"))
|
||||
}
|
||||
fn log(&self, _: &LogQuery, _: &CancellationToken) -> IdeResult<Vec<Commit>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn log_details(&self, revision: &str) -> IdeResult<LogDetails> {
|
||||
Ok(LogDetails {
|
||||
message: format!("change {revision}"),
|
||||
containing_branches: Vec::new(),
|
||||
signature: "N".into(),
|
||||
signer: String::new(),
|
||||
key: String::new(),
|
||||
fingerprint: String::new(),
|
||||
})
|
||||
}
|
||||
fn commit_files(&self, _: &str) -> IdeResult<Vec<ChangedFile>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn commits_changes(&self, _: &[String]) -> IdeResult<Vec<RevisionChange>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn diff_revisions(&self, _: &str, _: &str) -> IdeResult<Vec<ChangedFile>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn diff_with_worktree(&self, _: &str) -> IdeResult<Vec<ChangedFile>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn numstat_with_worktree(&self, _: &str) -> IdeResult<Vec<(String, u32, u32)>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn stage(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
self.staged.lock().extend_from_slice(paths);
|
||||
Ok(())
|
||||
}
|
||||
fn unstage(&self, _: &[PathBuf]) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
/// Reverts: the file gets its depot text back.
|
||||
fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
for path in paths {
|
||||
std::fs::write(path, "depot\n")?;
|
||||
}
|
||||
self.changed.lock().retain(|p| !paths.contains(p));
|
||||
Ok(())
|
||||
}
|
||||
fn commit(&self, _: &str, _: &CommitOptions, _: &dyn Fn(&Path) -> IdeResult<TextEncoding>) -> IdeResult<String> {
|
||||
Err(IdeError::unavailable("no submit"))
|
||||
}
|
||||
fn pending_changes(
|
||||
&self,
|
||||
_: &CommitOptions,
|
||||
_: usize,
|
||||
_: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
|
||||
) -> IdeResult<Vec<PendingChange>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
fn open_for_edit(&self, paths: &[PathBuf]) -> IdeResult<bool> {
|
||||
self.opened.lock().extend_from_slice(paths);
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the folder holding `.fake-vcs` at or above the one asked about; counts the questions.
|
||||
#[derive(Default)]
|
||||
struct Provider {
|
||||
asked: AtomicUsize,
|
||||
/// While set, `discover` waits (a slow client); `answered` counts the answers given.
|
||||
hold: AtomicBool,
|
||||
answered: AtomicUsize,
|
||||
found: Mutex<Vec<Arc<Fake>>>,
|
||||
}
|
||||
|
||||
impl Provider {
|
||||
fn fake(&self) -> Arc<Fake> {
|
||||
self.found.lock().first().cloned().expect("a working copy was discovered")
|
||||
}
|
||||
fn fake_at(&self, root: &Path) -> Arc<Fake> {
|
||||
self.found.lock().iter().find(|f| f.root == root).cloned().expect("a working copy at that root")
|
||||
}
|
||||
}
|
||||
|
||||
impl BackendProvider for Provider {
|
||||
fn marker(&self) -> Option<&str> {
|
||||
Some(".fake-vcs")
|
||||
}
|
||||
fn discover(&self, folder: &Path) -> IdeResult<Option<Arc<dyn Backend>>> {
|
||||
self.asked.fetch_add(1, Ordering::AcqRel);
|
||||
while self.hold.load(Ordering::Acquire) {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let _answered = Answered(&self.answered);
|
||||
let Some(root) = folder.ancestors().find(|dir| dir.join(".fake-vcs").is_file()) else { return Ok(None) };
|
||||
let mut found = self.found.lock();
|
||||
let fake = match found.iter().find(|f| f.root == root) {
|
||||
Some(fake) => fake.clone(),
|
||||
None => {
|
||||
let fake = Arc::new(Fake {
|
||||
root: root.to_path_buf(),
|
||||
changed: Mutex::default(),
|
||||
unreachable: AtomicBool::new(false),
|
||||
staged: Mutex::default(),
|
||||
opened: Mutex::default(),
|
||||
head: Mutex::new("trunk".into()),
|
||||
lists: Mutex::default(),
|
||||
});
|
||||
found.push(fake.clone());
|
||||
fake
|
||||
}
|
||||
};
|
||||
Ok(Some(fake))
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts an answer when `discover` returns, whichever way.
|
||||
struct Answered<'a>(&'a AtomicUsize);
|
||||
|
||||
impl Drop for Answered<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
fn git(root: &Path, args: &[&str]) -> String {
|
||||
let output = Command::new("git").current_dir(root).args(args).output().unwrap();
|
||||
assert!(output.status.success(), "{args:?}: {}", String::from_utf8_lossy(&output.stderr));
|
||||
String::from_utf8(output.stdout).unwrap().trim().to_owned()
|
||||
}
|
||||
|
||||
fn host(base: &Path, provider: &Arc<Provider>) -> Host {
|
||||
Host::new(common::host_config(base)).with_vcs_provider(provider.clone())
|
||||
}
|
||||
|
||||
async fn until(what: &str, done: impl Fn() -> bool) {
|
||||
for _ in 0..500 {
|
||||
if done() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("timed out waiting for {what}");
|
||||
}
|
||||
|
||||
fn paths(status: &[FileStatus]) -> BTreeSet<PathBuf> {
|
||||
status.iter().map(|f| f.path.0.clone()).collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_working_copy_answers_the_shared_vcs_commands() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join(".fake-vcs"), "").unwrap();
|
||||
let file = root.join("a.txt");
|
||||
std::fs::write(&file, "edited\n").unwrap();
|
||||
let provider = Arc::new(Provider::default());
|
||||
let host = host(&base, &provider);
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
until("the working copy", || !project.backends().is_empty()).await;
|
||||
let fake = provider.fake();
|
||||
fake.changed.lock().push(file.clone());
|
||||
|
||||
assert_eq!(paths(&vcs::vcs_status(&host, "main").await.unwrap()), BTreeSet::from([file.clone()]));
|
||||
assert_eq!(paths(&vcs::vcs_status_paths(&host, "main", vec![file.clone()]).await.unwrap()).len(), 1);
|
||||
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
|
||||
assert_eq!(roots.len(), 1);
|
||||
assert_eq!((roots[0].root.0.as_path(), roots[0].kind), (root.as_path(), VcsKind::Perforce));
|
||||
assert_eq!(roots[0].head.as_deref(), Some("trunk"));
|
||||
let info = vcs::vcs_branch_info(&host, "main", None).await.unwrap();
|
||||
assert_eq!(info.head.as_deref(), Some("trunk"));
|
||||
// The log comes from the working copy; Git-only reads (refs, stashes) answer nothing.
|
||||
assert!(vcs::vcs_log(&host, "main", None, LogQuery::default()).await.unwrap().is_empty());
|
||||
assert_eq!(vcs::vcs_log_details(&host, "main", None, "7".into()).await.unwrap().message, "change 7");
|
||||
assert!(vcs::vcs_log_refs(&host, "main", Some(root.clone())).await.unwrap().is_empty());
|
||||
assert!(vcs::vcs_stashes(&host, "main", None).await.unwrap().is_empty());
|
||||
|
||||
vcs::vcs_stage(&host, "main", vec![file.clone()]).await.unwrap();
|
||||
assert_eq!(*fake.staged.lock(), std::slice::from_ref(&file));
|
||||
fs::fs_set_writable(&host, "main", file.clone(), true).unwrap();
|
||||
assert_eq!(*fake.opened.lock(), std::slice::from_ref(&file));
|
||||
|
||||
// Rollback rewrites the file: Local History keeps the text from before, between labels.
|
||||
vcs::vcs_discard(&host, "main", vec![file.clone()]).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), "depot\n");
|
||||
let history = project.history.list(&file).unwrap();
|
||||
let labels: Vec<&str> = history.iter().map(|e| e.label.as_str()).collect();
|
||||
assert!(labels.contains(&"After Rollback") && labels.contains(&"Before Rollback"), "{labels:?}");
|
||||
let snapshot = history.iter().find(|e| !e.id.is_empty() && e.label == "Before Rollback").expect("a snapshot");
|
||||
assert_eq!(project.history.content(&snapshot.id).unwrap(), "edited\n");
|
||||
|
||||
// Update Project and the branch widget use the shared commands too.
|
||||
let output = Arc::new(Mutex::new(Vec::new()));
|
||||
let lines = output.clone();
|
||||
let channel = ide_host::ops::Channel::new(move |line: String| lines.lock().push(line));
|
||||
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
|
||||
let report = vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap();
|
||||
assert!(report.is_none());
|
||||
assert_eq!(*output.lock(), ["Updated to revision 8."]);
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), "updated\n");
|
||||
let labels: Vec<String> = project.history.list(&file).unwrap().into_iter().map(|e| e.label).collect();
|
||||
assert!(labels.iter().any(|l| l == "Before Update") && labels.iter().any(|l| l == "After Update"), "{labels:?}");
|
||||
let branches = vcs::vcs_branches(&host, "main", None).await.unwrap();
|
||||
assert_eq!(
|
||||
branches.iter().map(|b| (b.name.as_str(), b.current)).collect::<Vec<_>>(),
|
||||
[("trunk", true), ("branches/x", false)]
|
||||
);
|
||||
let outcome = vcs::vcs_checkout(&host, "main", None, "branches/x".into(), false, None, None).await.unwrap();
|
||||
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
|
||||
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("branches/x"));
|
||||
assert!(vcs::vcs_checkout(&host, "main", None, "branches/y".into(), true, None, None).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn git_inside_a_working_copy_keeps_its_files_and_its_changes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let lib = root.join("lib");
|
||||
std::fs::create_dir_all(&lib).unwrap();
|
||||
std::fs::write(root.join(".fake-vcs"), "").unwrap();
|
||||
git(&lib, &["init", "-q", "-b", "main"]);
|
||||
git(&lib, &["config", "user.name", "Test"]);
|
||||
git(&lib, &["config", "user.email", "[email protected]"]);
|
||||
std::fs::write(lib.join("tracked.txt"), "one\n").unwrap();
|
||||
git(&lib, &["add", "."]);
|
||||
git(&lib, &["commit", "-qm", "first"]);
|
||||
let (outside, tracked, untracked) = (root.join("a.txt"), lib.join("tracked.txt"), lib.join("new.txt"));
|
||||
std::fs::write(&outside, "edited\n").unwrap();
|
||||
std::fs::write(&untracked, "new\n").unwrap();
|
||||
|
||||
let provider = Arc::new(Provider::default());
|
||||
let host = host(&base, &provider);
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
until("Git and the working copy", || !project.backends().is_empty() && !project.repos().is_empty()).await;
|
||||
let fake = provider.fake();
|
||||
// The working copy claims a file of the nested Git repository too: Git keeps it.
|
||||
fake.changed.lock().extend([outside.clone(), tracked.clone()]);
|
||||
assert!(project.backend_of(&outside).is_some());
|
||||
assert!(project.backend_of(&tracked).is_none() && project.backend_of(&lib).is_none());
|
||||
|
||||
let status = vcs::vcs_status(&host, "main").await.unwrap();
|
||||
assert_eq!(paths(&status), BTreeSet::from([outside.clone(), untracked.clone()]));
|
||||
let kinds: Vec<VcsKind> = vcs::vcs_roots(&host, "main").await.unwrap().iter().map(|r| r.kind).collect();
|
||||
assert_eq!(kinds, [VcsKind::Git, VcsKind::Perforce]);
|
||||
|
||||
// Each path goes to its own backend.
|
||||
vcs::vcs_stage(&host, "main", vec![outside.clone(), untracked.clone()]).await.unwrap();
|
||||
assert_eq!(*fake.staged.lock(), std::slice::from_ref(&outside));
|
||||
assert_eq!(git(&lib, &["status", "--porcelain", "new.txt"]), "A new.txt");
|
||||
|
||||
// The working copy's own changelists; the Git root keeps the IDE's lists.
|
||||
assert_eq!(vcs::vcs_backend_changelists(&host, "main", Some(lib.clone())).await.unwrap(), None);
|
||||
let id = vcs::vcs_backend_changelist_create(&host, "main", Some(root.clone()), "ui".into(), String::new())
|
||||
.await
|
||||
.unwrap();
|
||||
vcs::vcs_backend_changelist_move(&host, "main", vec![outside.clone()], id.clone()).await.unwrap();
|
||||
assert!(vcs::vcs_backend_changelist_move(&host, "main", vec![untracked.clone()], id.clone()).await.is_err());
|
||||
// A list with a path in no working copy is refused whole: nothing moves, not even the
|
||||
// paths that would have been valid on their own.
|
||||
vcs::vcs_backend_changelist_move(&host, "main", vec![outside.clone()], "default".into()).await.unwrap();
|
||||
let mixed = vec![outside.clone(), untracked.clone()];
|
||||
assert!(vcs::vcs_backend_changelist_move(&host, "main", mixed, id.clone()).await.is_err());
|
||||
let lists = vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap().unwrap();
|
||||
assert!(lists.iter().all(|l| l.files.is_empty()), "{lists:?}");
|
||||
vcs::vcs_backend_changelist_move(&host, "main", vec![outside.clone()], id.clone()).await.unwrap();
|
||||
vcs::vcs_backend_changelist_edit(&host, "main", Some(root.clone()), id.clone(), "UI".into(), "menus".into())
|
||||
.await
|
||||
.unwrap();
|
||||
let lists = vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap().unwrap();
|
||||
assert_eq!(lists.len(), 1);
|
||||
assert_eq!((lists[0].name.as_str(), lists[0].comment.as_str()), ("UI", "menus"));
|
||||
assert_eq!(lists[0].files.iter().map(|f| f.0.clone()).collect::<Vec<_>>(), std::slice::from_ref(&outside));
|
||||
vcs::vcs_backend_changelist_delete(&host, "main", Some(root.clone()), id).await.unwrap();
|
||||
assert_eq!(vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap(), Some(Vec::new()));
|
||||
assert!(
|
||||
vcs::vcs_backend_changelist_create(&host, "main", Some(lib.clone()), "x".into(), String::new()).await.is_err()
|
||||
);
|
||||
|
||||
// A server that cannot be reached leaves the Git changes visible.
|
||||
fake.unreachable.store(true, Ordering::Release);
|
||||
let status = vcs::vcs_status(&host, "main").await.unwrap();
|
||||
assert_eq!(paths(&status), BTreeSet::from([untracked.clone()]));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_working_copy_at_a_git_root_is_left_to_git() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join(".fake-vcs"), "").unwrap();
|
||||
git(&root, &["init", "-q", "-b", "main"]);
|
||||
let untracked = root.join("new.txt");
|
||||
std::fs::write(&untracked, "new\n").unwrap();
|
||||
let provider = Arc::new(Provider::default());
|
||||
let host = host(&base, &provider);
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
until("the working copy", || !project.backends.read().is_empty()).await;
|
||||
provider.fake().changed.lock().push(untracked.clone());
|
||||
|
||||
// Found, but shadowed: the root is reported once, as Git's, and Git answers for it.
|
||||
assert!(project.backends().is_empty() && project.backend_at(Some(&root)).is_none());
|
||||
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
|
||||
let roots: Vec<_> = roots.iter().map(|r| (r.root.0.clone(), r.kind)).collect();
|
||||
assert_eq!(roots, [(root.clone(), VcsKind::Git)]);
|
||||
let status = vcs::vcs_status(&host, "main").await.unwrap();
|
||||
assert_eq!(paths(&status), BTreeSet::from([root.join(".fake-vcs"), untracked.clone()]));
|
||||
assert!(status.iter().all(|f| f.unstaged == Some(ChangeKind::Untracked)));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn restricted_mode_asks_no_provider_until_the_project_is_trusted() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join(".fake-vcs"), "").unwrap();
|
||||
std::fs::create_dir_all(root.join("inner")).unwrap();
|
||||
std::fs::write(root.join("inner/.fake-vcs"), "").unwrap();
|
||||
let provider = Arc::new(Provider::default());
|
||||
let host = host(&base, &provider);
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
project.refresh_backends();
|
||||
assert_eq!(provider.asked.load(Ordering::Acquire), 0);
|
||||
assert!(project.backends().is_empty() && project.backend_of(&root.join("a.txt")).is_none());
|
||||
assert!(vcs::vcs_status(&host, "main").await.is_err());
|
||||
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
until("both working copies", || project.backends().len() == 2).await;
|
||||
assert!(provider.asked.load(Ordering::Acquire) > 0);
|
||||
assert!(vcs::vcs_status(&host, "main").await.unwrap().is_empty());
|
||||
|
||||
host.set_project_trust(&root, false, false).await.unwrap();
|
||||
assert!(project.backends().is_empty());
|
||||
until("the working copy to go", || project.backends.read().is_empty()).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_slow_scan_started_before_restricting_does_not_bring_the_working_copy_back() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join(".fake-vcs"), "").unwrap();
|
||||
let provider = Arc::new(Provider::default());
|
||||
provider.hold.store(true, Ordering::Release);
|
||||
let host = host(&base, &provider);
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
until("the opening scan to ask", || provider.asked.load(Ordering::Acquire) > 0).await;
|
||||
|
||||
// Restricted while the opening scan still waits for its answer: the rescan this starts
|
||||
// must come after it, not before.
|
||||
host.set_project_trust(&root, false, false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
provider.hold.store(false, Ordering::Release);
|
||||
until("the opening scan's answer", || provider.answered.load(Ordering::Acquire) > 0).await;
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
assert!(project.backends.read().is_empty());
|
||||
}
|
||||
|
||||
fn roots_of(project: &ide_host::Project) -> BTreeSet<PathBuf> {
|
||||
project.backends().iter().map(|b| b.root().to_path_buf()).collect()
|
||||
}
|
||||
|
||||
fn marked(dir: &Path) {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join(".fake-vcs"), "").unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn working_copies_nested_in_a_working_copy_are_found_like_nested_git_repositories() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
// A separate checkout inside the working copy, a directory external two levels down, and
|
||||
// one in a dependency folder that is never searched.
|
||||
let (inner, external) = (root.join("inner"), root.join("ext/lib"));
|
||||
for dir in [&root, &inner, &external, &root.join("node_modules/pkg")] {
|
||||
marked(dir);
|
||||
}
|
||||
let provider = Arc::new(Provider::default());
|
||||
let host = host(&base, &provider);
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
until("the nested working copies", || project.backends().len() == 3).await;
|
||||
assert_eq!(roots_of(&project), BTreeSet::from([root.clone(), inner.clone(), external.clone()]));
|
||||
|
||||
// The deepest working copy owns a path.
|
||||
let owner = |path: &Path| project.backend_of(path).map(|b| b.root().to_path_buf());
|
||||
assert_eq!(owner(&inner.join("b.txt")), Some(inner.clone()));
|
||||
assert_eq!(owner(&external.join("x.txt")), Some(external.clone()));
|
||||
assert_eq!(owner(&root.join("ext/y.txt")), Some(root.clone()));
|
||||
assert_eq!(owner(&root.join("node_modules/pkg/z.txt")), Some(root.clone()));
|
||||
|
||||
// Each changed file is listed once, by its own working copy.
|
||||
let (outer_file, inner_file) = (root.join("a.txt"), inner.join("b.txt"));
|
||||
provider.fake_at(&root).changed.lock().extend([outer_file.clone(), inner_file.clone()]);
|
||||
provider.fake_at(&inner).changed.lock().push(inner_file.clone());
|
||||
let status = vcs::vcs_status(&host, "main").await.unwrap();
|
||||
assert_eq!(status.len(), 2, "{status:?}");
|
||||
assert_eq!(paths(&status), BTreeSet::from([outer_file, inner_file]));
|
||||
let kinds: Vec<VcsKind> = vcs::vcs_roots(&host, "main").await.unwrap().iter().map(|r| r.kind).collect();
|
||||
assert_eq!(kinds, [VcsKind::Perforce; 3]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_working_copy_inside_a_git_project_is_found() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let wc = root.join("vendor-src/wc");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
git(&root, &["init", "-q", "-b", "main"]);
|
||||
marked(&wc);
|
||||
let provider = Arc::new(Provider::default());
|
||||
let host = host(&base, &provider);
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
until("Git and the working copy", || !project.repos().is_empty() && !project.backends().is_empty()).await;
|
||||
assert_eq!(roots_of(&project), BTreeSet::from([wc.clone()]));
|
||||
assert!(project.backend_of(&wc.join("a.txt")).is_some());
|
||||
assert!(project.backend_of(&root.join("a.txt")).is_none());
|
||||
let roots: Vec<_> =
|
||||
vcs::vcs_roots(&host, "main").await.unwrap().iter().map(|r| (r.root.0.clone(), r.kind)).collect();
|
||||
assert_eq!(roots, [(root.clone(), VcsKind::Git), (wc.clone(), VcsKind::Perforce)]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_working_copy_checked_out_in_the_open_project_shows_up_and_goes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::write(root.join("src/main.txt"), "x\n").unwrap();
|
||||
let provider = Arc::new(Provider::default());
|
||||
let host = host(&base, &provider);
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
until("the opening scan", || provider.answered.load(Ordering::Acquire) > 0).await;
|
||||
assert!(project.backends().is_empty());
|
||||
|
||||
// A checkout writes its folder, the marker, then the files.
|
||||
let checkout = root.join("checkout");
|
||||
marked(&checkout);
|
||||
std::fs::write(checkout.join("a.txt"), "a\n").unwrap();
|
||||
until("the new working copy", || roots_of(&project) == BTreeSet::from([checkout.clone()])).await;
|
||||
|
||||
std::fs::remove_dir_all(&checkout).unwrap();
|
||||
until("the removed working copy to go", || project.backends().is_empty()).await;
|
||||
}
|
||||
@@ -572,3 +572,60 @@ async fn a_repository_created_in_the_project_is_known_when_init_returns() {
|
||||
let roots: Vec<_> = project.repos().all().iter().map(|r| r.root().to_path_buf()).collect();
|
||||
assert_eq!(roots, [project_root]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn vcs_roots_reports_unavailable_root_until_it_returns() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let project_root = base.join("project");
|
||||
let external_main = base.join("external-main");
|
||||
let wt = project_root.join("wt");
|
||||
let healthy = project_root.join("healthy");
|
||||
for root in [&external_main, &healthy] {
|
||||
std::fs::create_dir_all(root).unwrap();
|
||||
git(root, &["init", "-b", "main"]);
|
||||
git(root, &["config", "user.name", "Test"]);
|
||||
git(root, &["config", "user.email", "[email protected]"]);
|
||||
std::fs::write(root.join("file.txt"), "hello\n").unwrap();
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-m", "initial"]);
|
||||
}
|
||||
git(&external_main, &["worktree", "add", "-b", "wt-branch", wt.to_str().unwrap()]);
|
||||
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if project.repos().all().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(project.repos().all().len(), 2);
|
||||
|
||||
// Move the linked worktree's metadata dir (outside project_root) aside so the project FileWatcher never races.
|
||||
let wt_git_dir = external_main.join(".git/worktrees/wt");
|
||||
let parked_git_dir = base.join("parked-wt-git");
|
||||
std::fs::rename(&wt_git_dir, &parked_git_dir).unwrap();
|
||||
|
||||
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
|
||||
let wt_root = roots.iter().find(|r| r.root.0 == wt).unwrap();
|
||||
let healthy_root = roots.iter().find(|r| r.root.0 == healthy).unwrap();
|
||||
assert!(wt_root.unavailable);
|
||||
assert!(wt_root.head.is_none());
|
||||
assert!(wt_root.head_commit.is_none());
|
||||
assert!(wt_root.operation.is_none());
|
||||
assert!(wt_root.has_remotes.is_none());
|
||||
assert_eq!(wt_root.branch_root.0, wt);
|
||||
assert!(!healthy_root.unavailable);
|
||||
assert_eq!(healthy_root.head.as_deref(), Some("main"));
|
||||
|
||||
std::fs::rename(&parked_git_dir, &wt_git_dir).unwrap();
|
||||
let restored = vcs::vcs_roots(&host, "main").await.unwrap();
|
||||
let wt_restored = restored.iter().find(|r| r.root.0 == wt).unwrap();
|
||||
let healthy_restored = restored.iter().find(|r| r.root.0 == healthy).unwrap();
|
||||
assert!(!wt_restored.unavailable);
|
||||
assert_eq!(wt_restored.head.as_deref(), Some("wt-branch"));
|
||||
assert!(!healthy_restored.unavailable);
|
||||
host.close_project("main");
|
||||
}
|
||||
Loaded 100 of 736 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача