дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-01 14:44:34 +02:00
Порівняти коміти
117
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
a466ec7425 | ||
|
|
98e375f524 | ||
|
|
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 | ||
|
|
38a964040b | ||
|
|
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 | ||
|
|
f80be658ea | ||
|
|
1c377b7f66 | ||
|
|
093cf6fdf8 | ||
|
|
9b578c2fad | ||
|
|
f5bb97babd | ||
|
|
e23088d558 | ||
|
|
7279f515db | ||
|
|
710d120689 | ||
|
|
38709947fe | ||
|
|
d9fbb19787 | ||
|
|
6aa613d4ec | ||
|
|
60ef498deb | ||
|
|
719b73ecd9 | ||
|
|
6c3284c300 | ||
|
|
69cec11761 | ||
|
|
6c76cfd316 | ||
|
|
66496221b9 | ||
|
|
e9f3aef5ae |
No files matched your search
@@ -21,6 +21,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
|
||||
@@ -23,6 +23,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
cask:
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
|
||||
@@ -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/localAppearance.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
- "src/editor/lsp/files.ts"
|
||||
@@ -106,9 +107,9 @@ jobs:
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
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)|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|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
|
||||
@@ -19,6 +19,7 @@ env:
|
||||
jobs:
|
||||
plugin-keys:
|
||||
permissions: {}
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
keys: ${{ steps.keys.outputs.keys }}
|
||||
@@ -43,6 +44,7 @@ jobs:
|
||||
contents: write
|
||||
needs: plugin-keys
|
||||
name: Build (${{ matrix.name }})
|
||||
environment: release
|
||||
env:
|
||||
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
|
||||
strategy:
|
||||
@@ -227,6 +229,7 @@ jobs:
|
||||
permissions:
|
||||
contents: write
|
||||
needs: server
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Signing configured
|
||||
|
||||
@@ -7,19 +7,27 @@ 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
|
||||
# the `release` environment, which holds those secrets.
|
||||
jobs:
|
||||
# Creates (or reuses) one draft release that every platform build uploads into.
|
||||
create-release:
|
||||
@@ -50,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;
|
||||
@@ -61,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,
|
||||
});
|
||||
@@ -78,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
|
||||
|
||||
@@ -96,13 +111,18 @@ jobs:
|
||||
contents: write
|
||||
needs: create-release
|
||||
name: Official plugins
|
||||
environment: release
|
||||
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
|
||||
@@ -175,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
|
||||
Створено
+62
-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",
|
||||
@@ -4183,7 +4183,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4195,7 +4195,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4207,7 +4207,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4225,7 +4225,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4239,7 +4239,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4250,7 +4250,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4261,7 +4261,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 +4283,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4296,7 +4296,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4326,7 +4326,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4365,7 +4365,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4378,7 +4378,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4392,7 +4392,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4412,7 +4412,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4423,7 +4423,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4435,7 +4435,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4447,7 +4447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4466,7 +4466,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4549,7 +4549,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"http",
|
||||
@@ -4572,7 +4572,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4595,7 +4595,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4607,7 +4607,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4623,7 +4623,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4632,7 +4632,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4643,7 +4643,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4684,6 +4684,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 +4703,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4732,7 +4733,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4751,7 +4752,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4776,7 +4777,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4798,7 +4799,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4812,7 +4813,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4832,7 +4833,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4858,7 +4859,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4874,7 +4875,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 +4901,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4921,7 +4922,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4934,7 +4935,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4959,7 +4960,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4972,7 +4973,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4987,7 +4988,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -5001,7 +5002,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -5014,7 +5015,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -5041,7 +5042,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5063,7 +5064,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5090,7 +5091,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5106,7 +5107,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5116,6 +5117,7 @@ dependencies = [
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"parking_lot 0.12.5",
|
||||
"quick-xml 0.42.0",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -6754,7 +6756,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -10641,6 +10643,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"
|
||||
|
||||
@@ -2762,7 +2762,6 @@ impl AgentManager {
|
||||
}
|
||||
s.task.title = title;
|
||||
s.title_renamed = true;
|
||||
s.task.updated_ms = now_ms();
|
||||
}
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
@@ -3126,7 +3125,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 +3156,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 +3191,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())
|
||||
};
|
||||
|
||||
@@ -6928,3 +6928,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();
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,28 @@ 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() {
|
||||
for _ in 0..5 {
|
||||
debounce(&DUE, Duration::from_millis(100), count);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(RUNS.load(SeqCst), 0);
|
||||
std::thread::sleep(Duration::from_millis(400));
|
||||
assert_eq!(RUNS.load(SeqCst), 1);
|
||||
release_free_pages_soon();
|
||||
}
|
||||
}
|
||||
@@ -1176,6 +1176,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");
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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() };
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -362,21 +362,24 @@ 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`.
|
||||
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))
|
||||
}
|
||||
|
||||
/// `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
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
mod swiftpm;
|
||||
pub mod unity;
|
||||
|
||||
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
@@ -613,6 +614,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");
|
||||
@@ -625,7 +636,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,
|
||||
@@ -1080,6 +1095,9 @@ impl DebugManager {
|
||||
.await?;
|
||||
arguments["program"] = json!(program);
|
||||
}
|
||||
if let Some(spm) = arguments.as_object_mut().and_then(|o| o.remove("swiftpm")) {
|
||||
arguments["program"] = json!(swiftpm::program(&cwd, &spm, &cancel).await?);
|
||||
}
|
||||
// Attach to a Node process started without `--inspect`: open its inspector first.
|
||||
if config.adapter == "js-debug" && config.request == "attach" && arguments.get("port").is_none() {
|
||||
let pid = arguments.get("processId").and_then(|p| match p {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
//! SwiftPM launch integration: a launch request may carry
|
||||
//! `"swiftpm": {"product": "greet", "buildArgs": ["-c", "release"]}` instead of `program`.
|
||||
//! The run configuration's before launch task has built the product; this asks
|
||||
//! `swift build <buildArgs> --show-bin-path` where it went (`.build/<triple>/<configuration>`,
|
||||
//! or wherever `--scratch-path` / `--build-path` put it) and launches it from there.
|
||||
|
||||
use crate::adapter::find_binary;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
|
||||
/// `swift build` arguments that print the bin path for `buildArgs` without building.
|
||||
pub fn bin_path_args(swiftpm: &Value) -> Vec<String> {
|
||||
let mut args = vec!["build".to_owned()];
|
||||
if let Some(a) = swiftpm.get("buildArgs").and_then(Value::as_array) {
|
||||
args.extend(a.iter().filter_map(|v| v.as_str().map(str::to_owned)));
|
||||
}
|
||||
args.push("--show-bin-path".into());
|
||||
args
|
||||
}
|
||||
|
||||
/// The built product of `swiftpm` (see the module docs).
|
||||
pub async fn program(cwd: &Path, swiftpm: &Value, cancel: &ide_core::CancellationToken) -> IdeResult<PathBuf> {
|
||||
let product = swiftpm
|
||||
.get("product")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|p| !p.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("the SwiftPM launch names no product"))?;
|
||||
let swift = find_binary("swift", cwd).ok_or_else(|| IdeError::unavailable("`swift` not found on PATH"))?;
|
||||
let args = bin_path_args(swiftpm);
|
||||
let mut cmd = tokio::process::Command::new(swift);
|
||||
cmd.current_dir(cwd);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
|
||||
let out = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
out = cmd.output() => out.map_err(|e| IdeError::unavailable(format!("failed to run swift: {e}")))?,
|
||||
};
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("swift {} failed: {}", args.join(" "), err.trim())));
|
||||
}
|
||||
// The bin path is the last line: SwiftPM may print warnings about the manifest first.
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let dir = stdout.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or_default();
|
||||
if dir.is_empty() {
|
||||
return Err(IdeError::invalid("swift build --show-bin-path printed no path"));
|
||||
}
|
||||
let exe = if cfg!(windows) { format!("{product}.exe") } else { product.to_owned() };
|
||||
Ok(cwd.join(dir).join(exe))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn asks_swift_build_for_the_bin_path_of_the_run_configurations_build() {
|
||||
assert_eq!(bin_path_args(&json!({"product": "greet"})), ["build", "--show-bin-path"]);
|
||||
assert_eq!(
|
||||
bin_path_args(&json!({"product": "greet", "buildArgs": ["-c", "release"]})),
|
||||
["build", "-c", "release", "--show-bin-path"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -463,6 +465,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 +551,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 +710,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"]);
|
||||
}
|
||||
|
||||
@@ -119,7 +119,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,8 +138,13 @@ 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)?;
|
||||
|
||||
@@ -173,6 +173,21 @@ pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools";
|
||||
pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild";
|
||||
/// Id (and `menu.` label key) of the Build › Flutter submenu.
|
||||
pub const FLUTTER_BUILD_MENU: &str = "build.flutter";
|
||||
/// Build › Xcode: Clean Build Folder and Delete DerivedData, filled only when the project has
|
||||
/// Xcode schemes. A submenu after Build › Flutter when it has items, like it.
|
||||
pub const DYNAMIC_XCODE_BUILD: &str = "xcodeBuild";
|
||||
/// Id (and `menu.` label key) of the Build › Xcode submenu.
|
||||
pub const XCODE_BUILD_MENU: &str = "build.xcode";
|
||||
|
||||
/// The submenu (id, English label) a dynamic slot is shown as when it has items, followed by a
|
||||
/// separator; `None`: its items are listed in place.
|
||||
pub fn dynamic_submenu(slot: &str) -> Option<(&'static str, &'static str)> {
|
||||
match slot {
|
||||
DYNAMIC_FLUTTER_BUILD => Some((FLUTTER_BUILD_MENU, "Flutter")),
|
||||
DYNAMIC_XCODE_BUILD => Some((XCODE_BUILD_MENU, "Xcode")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu bar for `os`. Labels are English defaults; the frontend replaces
|
||||
/// them with `menu.<id>` strings from the active locale catalog.
|
||||
@@ -262,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"),
|
||||
],
|
||||
),
|
||||
@@ -469,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…"),
|
||||
@@ -622,6 +639,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"Build",
|
||||
vec![
|
||||
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD),
|
||||
Entry::Dynamic(DYNAMIC_XCODE_BUILD),
|
||||
act("build.buildProject", "Build Project"),
|
||||
act("build.buildModule", "Build Module"),
|
||||
act("build.compileFile", "Recompile"),
|
||||
@@ -1298,12 +1316,12 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
|
||||
}
|
||||
}));
|
||||
}
|
||||
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
|
||||
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
|
||||
Entry::Dynamic(slot) if let Some((id, label)) = dynamic_submenu(slot) => {
|
||||
let items = config.dynamic_items(slot);
|
||||
if !items.is_empty() {
|
||||
out.push(MenuNode::Submenu {
|
||||
id: FLUTTER_BUILD_MENU.into(),
|
||||
label: "Flutter".into(),
|
||||
id: id.into(),
|
||||
label: label.into(),
|
||||
current: None,
|
||||
children: items.iter().map(DynamicItem::model).collect(),
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -544,38 +544,24 @@ 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;
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
@@ -709,8 +695,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 +813,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
|
||||
@@ -1259,6 +1300,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 +1494,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,6 +655,73 @@ pub async fn lsp_file_references(
|
||||
result
|
||||
}
|
||||
|
||||
/// The header of the document's source file or the source of its header (C, C++,
|
||||
/// Objective-C) as clangd finds it; `None` without clangd or an answer. Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_switch_source_header(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::select! {
|
||||
result = lsp.switch_source_header(doc, cancel.clone()) => result,
|
||||
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
|
||||
};
|
||||
host.end_request(request);
|
||||
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)`.
|
||||
@@ -2409,6 +2492,19 @@ pub fn plugin_formatters() -> IdeResult<Vec<crate::plugins::language_features::F
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[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::*;
|
||||
@@ -3294,6 +3390,10 @@ ide_command::domain!(
|
||||
lsp_hover,
|
||||
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,
|
||||
|
||||
@@ -52,6 +52,8 @@ pub mod tools;
|
||||
pub mod vcs;
|
||||
pub mod web;
|
||||
pub mod xcode_bsp;
|
||||
pub mod xcode_clean;
|
||||
pub mod xcode_files;
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -140,6 +142,8 @@ ide_command::domains!(
|
||||
vcs_commands: crate::ops::vcs::commands,
|
||||
web: crate::ops::web,
|
||||
xcode_bsp: crate::ops::xcode_bsp,
|
||||
xcode_clean: crate::ops::xcode_clean,
|
||||
xcode_files: crate::ops::xcode_files,
|
||||
);
|
||||
|
||||
/// A blocking task that panicked or was cancelled, as the error a command returns.
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -454,7 +454,10 @@ async fn start_inner(
|
||||
if ide_run::is_python_kind(&config.kind) {
|
||||
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
|
||||
}
|
||||
let config = container::prepare(host, &project.root, target, config).await?;
|
||||
let (config, note) = container::prepare(host, &project.root, target, config).await?;
|
||||
if let Some(note) = note {
|
||||
on_output(OutputChunk::System { text: format!("{note}\n") });
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
@@ -552,6 +555,15 @@ async fn start_inner(
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == ide_run::xcode_clean::KIND {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode_clean::prepare(&dir, &cache, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == "go" && config.extras.params.get("scope").is_some_and(|s| s == "file") {
|
||||
let root = project.root.clone();
|
||||
config = host
|
||||
@@ -563,9 +575,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?;
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,8 @@ use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_remote::docker::{
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root,
|
||||
compose_service, container_config, container_name, default_container_root,
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, NODE_DEBUG_FOLDER,
|
||||
compose_container_root, compose_service, container_config, container_name, default_container_root, node_debug,
|
||||
};
|
||||
use ide_remote::target::DEBUG_PARAM;
|
||||
use ide_run::RunConfig;
|
||||
@@ -16,15 +16,21 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service.
|
||||
pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config: RunConfig) -> IdeResult<RunConfig> {
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service, and for a
|
||||
/// Node.js debug run the line telling the debugger the project folder in the container.
|
||||
pub(super) async fn prepare(
|
||||
host: &Host,
|
||||
root: &Path,
|
||||
target: RunTarget,
|
||||
config: RunConfig,
|
||||
) -> IdeResult<(RunConfig, Option<String>)> {
|
||||
if config.kind == "dotnet" || config.kind == "dotnet-test" {
|
||||
return Err(IdeError::invalid(".NET Project requires the local machine"));
|
||||
}
|
||||
let debug = config.extras.params.get(DEBUG_PARAM).is_some_and(|v| v == "true");
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") {
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") && !node_debug(&config) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' can't be debugged in a container: only Python run configurations can",
|
||||
"'{}' can't be debugged in a container: only Python and Node.js run configurations can",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
@@ -41,7 +47,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
let (service_env, service_ports) = server_context(&data_dir, &root, &target, &config);
|
||||
let name = container_name(&config.id, &unique());
|
||||
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
|
||||
container_config(
|
||||
let note = (debug && node_debug(&config)).then(|| format!("{NODE_DEBUG_FOLDER}{container_root}"));
|
||||
let config = container_config(
|
||||
&config,
|
||||
&ContainerRun {
|
||||
target: &target,
|
||||
@@ -60,7 +67,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
debugpy: d.debugpy.as_deref(),
|
||||
}),
|
||||
},
|
||||
)
|
||||
)?;
|
||||
Ok((config, note))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Deleting an Xcode project's DerivedData (#6665 C6). Clean Build Folder is a run of
|
||||
//! `ide_run::xcode_clean::KIND`; this is the part a run can't do: moving folders to the Trash.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
async fn dirs(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: Option<String>,
|
||||
params: BTreeMap<String, String>,
|
||||
) -> IdeResult<Vec<PathBuf>> {
|
||||
let project = host.project(window)?;
|
||||
let dir = project.root.join(cwd.unwrap_or_default());
|
||||
let cache = project.cache_dir.clone();
|
||||
super::blocking(move || ide_run::xcode_clean::derived_data_dirs(&dir, &cache, ¶ms)).await
|
||||
}
|
||||
|
||||
/// The DerivedData folders [`xcode_delete_derived_data`] would delete for an `xcode`
|
||||
/// configuration (its `cwd` and `params`), for the user to confirm.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_derived_data(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: Option<String>,
|
||||
params: BTreeMap<String, String>,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
Ok(dirs(host, window, cwd, params).await?.iter().map(|d| d.to_string_lossy().into_owned()).collect())
|
||||
}
|
||||
|
||||
/// Moves the configuration's DerivedData folders to the Trash, then restarts sourcekit-lsp: a
|
||||
/// build server config (xcode-build-server's `build_root`) reads build logs and the index there.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_delete_derived_data(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: Option<String>,
|
||||
params: BTreeMap<String, String>,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let found = dirs(host, window, cwd, params).await?;
|
||||
let deleted = found.clone();
|
||||
super::blocking(move || found.iter().try_for_each(|d| ide_vfs::delete(d))).await?;
|
||||
let project = host.project(window)?;
|
||||
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
|
||||
project.lsp.restart(server.id).await?;
|
||||
}
|
||||
Ok(deleted.iter().map(|d| d.to_string_lossy().into_owned()).collect())
|
||||
}
|
||||
|
||||
ide_command::domain!(xcode_clean: xcode_derived_data, xcode_delete_derived_data);
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Source files created, renamed or deleted in an Xcode project (#6665 C7). `xcodebuild` compiles
|
||||
//! only the files a target lists, so a new file in a classic `.xcodeproj` group is silently left
|
||||
//! out. The IDE does not edit `project.pbxproj`: for XcodeGen / Tuist projects it offers to
|
||||
//! regenerate the project, and for a classic project it says which new files the project doesn't
|
||||
//! name, unless the project uses Xcode 16 synchronized folders, which pick new files up themselves.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Source files a target compiles; other files don't make `xcodebuild` miss code.
|
||||
const SOURCE_EXTENSIONS: [&str; 9] = ["swift", "m", "mm", "h", "c", "cc", "cpp", "hpp", "metal"];
|
||||
|
||||
/// What the changed files need in their Xcode project.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum XcodeFileSync {
|
||||
/// The project is generated from `project.yml` (`xcodegen`) or `Project.swift` (`tuist`) in `dir`.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Generated { dir: PathBuf, tool: String },
|
||||
/// `files` (file names) are not named in `project`, a classic `.xcodeproj`.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
NotInProject { project: PathBuf, files: Vec<String> },
|
||||
}
|
||||
|
||||
fn is_source(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| SOURCE_EXTENSIONS.contains(&e))
|
||||
}
|
||||
|
||||
/// Hidden folders and the bundles themselves are not project sources.
|
||||
fn is_project_file(path: &Path, root: &Path) -> bool {
|
||||
path.strip_prefix(root).is_ok_and(|rel| {
|
||||
rel.components().all(|c| {
|
||||
let name = c.as_os_str().to_string_lossy();
|
||||
!name.starts_with('.') && !name.ends_with(".xcodeproj") && !name.ends_with(".xcworkspace")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
enum Owner {
|
||||
Generated(PathBuf, &'static str),
|
||||
Classic(Vec<PathBuf>),
|
||||
}
|
||||
|
||||
/// The nearest folder from `path` up to `root` with a project spec or `.xcodeproj` bundles.
|
||||
fn owner(path: &Path, root: &Path) -> Option<Owner> {
|
||||
let mut dir = path.parent()?;
|
||||
loop {
|
||||
if dir.join("project.yml").is_file() {
|
||||
return Some(Owner::Generated(dir.to_path_buf(), "xcodegen"));
|
||||
}
|
||||
if dir.join("Project.swift").is_file() {
|
||||
return Some(Owner::Generated(dir.to_path_buf(), "tuist"));
|
||||
}
|
||||
// A local Swift package builds its files from the folder layout, not from a project.
|
||||
if dir.join("Package.swift").is_file() {
|
||||
return None;
|
||||
}
|
||||
let mut projects: Vec<PathBuf> = std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "xcodeproj") && p.is_dir())
|
||||
.collect();
|
||||
if !projects.is_empty() {
|
||||
projects.sort();
|
||||
return Some(Owner::Classic(projects));
|
||||
}
|
||||
if dir == root {
|
||||
return None;
|
||||
}
|
||||
dir = dir.parent()?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `text` names `file` as a whole name (`/* View.swift */`, `path = View.swift;`,
|
||||
/// `"My View.swift"`), not as the end of another one (`AppView.swift`).
|
||||
fn names(text: &str, file: &str) -> bool {
|
||||
let part_of_name = |c: char| c.is_alphanumeric() || "_-.+".contains(c);
|
||||
text.match_indices(file).any(|(at, _)| {
|
||||
!text[..at].chars().next_back().is_some_and(part_of_name)
|
||||
&& !text[at + file.len()..].chars().next().is_some_and(part_of_name)
|
||||
})
|
||||
}
|
||||
|
||||
/// What `created` (created or renamed to) and `removed` source files under `root` need; the
|
||||
/// first Xcode project they belong to wins.
|
||||
pub fn file_sync(root: &Path, created: &[PathBuf], removed: &[PathBuf]) -> Option<XcodeFileSync> {
|
||||
let relevant = |p: &&PathBuf| is_source(p) && is_project_file(p, root);
|
||||
let mut classic: Option<(Vec<PathBuf>, Vec<String>)> = None;
|
||||
for (path, is_new) in
|
||||
created.iter().filter(relevant).map(|p| (p, true)).chain(removed.iter().filter(relevant).map(|p| (p, false)))
|
||||
{
|
||||
match owner(path, root) {
|
||||
Some(Owner::Generated(dir, tool)) => return Some(XcodeFileSync::Generated { dir, tool: tool.into() }),
|
||||
// A deleted file is still named in the project; Xcode shows it in red.
|
||||
Some(Owner::Classic(projects)) if is_new => {
|
||||
let (owner_projects, files) = classic.get_or_insert_with(|| (projects.clone(), Vec::new()));
|
||||
if *owner_projects == projects {
|
||||
files.push(path.file_name()?.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (projects, files) = classic?;
|
||||
// Plain string checks on project.pbxproj, no parsing; a project mixing groups and
|
||||
// synchronized folders counts as synchronized, as does a name that's taken by another file.
|
||||
let texts: Vec<String> =
|
||||
projects.iter().filter_map(|p| std::fs::read_to_string(p.join("project.pbxproj")).ok()).collect();
|
||||
if texts.is_empty() || texts.iter().any(|t| t.contains("PBXFileSystemSynchronizedRootGroup")) {
|
||||
return None;
|
||||
}
|
||||
let mut files: Vec<String> = files.into_iter().filter(|f| !texts.iter().any(|t| names(t, f))).collect();
|
||||
files.sort();
|
||||
files.dedup();
|
||||
(!files.is_empty()).then(|| XcodeFileSync::NotInProject { project: projects[0].clone(), files })
|
||||
}
|
||||
|
||||
/// What source files created, renamed or deleted in the project need in their Xcode project;
|
||||
/// `None` when they are in none, or it picks them up itself.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_file_sync(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
created: Vec<PathBuf>,
|
||||
removed: Vec<PathBuf>,
|
||||
) -> IdeResult<Option<XcodeFileSync>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
host.blocking(move || Ok(file_sync(&root, &created, &removed))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(xcode_files: xcode_file_sync);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn project(files: &[(&str, &str)]) -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (path, text) in files {
|
||||
let path = dir.path().join(path);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
const CLASSIC: &str = "/* Begin PBXFileReference section */ AppView.swift /* End */";
|
||||
|
||||
#[test]
|
||||
fn names_new_sources_a_classic_project_does_not_mention() {
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC), ("App/AppView.swift", "")]);
|
||||
let root = dir.path();
|
||||
let created = [
|
||||
root.join("App/AppView.swift"),
|
||||
root.join("App/New.swift"),
|
||||
root.join("App/View.swift"),
|
||||
root.join("App/notes.md"),
|
||||
];
|
||||
assert_eq!(
|
||||
file_sync(root, &created, &[]),
|
||||
Some(XcodeFileSync::NotInProject {
|
||||
project: root.join("App.xcodeproj"),
|
||||
files: vec!["New.swift".into(), "View.swift".into()]
|
||||
})
|
||||
);
|
||||
// Deleting a file needs nothing in a classic project.
|
||||
assert_eq!(file_sync(root, &[], &[root.join("App/AppView.swift")]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusts_synchronized_folders() {
|
||||
let text = "/* Begin PBXFileSystemSynchronizedRootGroup section */";
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", text)]);
|
||||
assert_eq!(file_sync(dir.path(), &[dir.path().join("App/New.swift")], &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offers_the_generator_of_the_nearest_spec() {
|
||||
let dir =
|
||||
project(&[("project.yml", ""), ("App.xcodeproj/project.pbxproj", CLASSIC), ("Mod/Project.swift", "")]);
|
||||
let root = dir.path();
|
||||
let generated = |dir: PathBuf, tool: &str| Some(XcodeFileSync::Generated { dir, tool: tool.into() });
|
||||
assert_eq!(file_sync(root, &[], &[root.join("Sources/Old.swift")]), generated(root.into(), "xcodegen"));
|
||||
assert_eq!(file_sync(root, &[root.join("Mod/A.m")], &[]), generated(root.join("Mod"), "tuist"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_files_of_a_local_package_next_to_the_project() {
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC), ("Packages/Feature/Package.swift", "")]);
|
||||
let root = dir.path();
|
||||
assert_eq!(file_sync(root, &[root.join("Packages/Feature/Sources/Feature/New.swift")], &[]), None);
|
||||
// Files of the app itself are still checked.
|
||||
assert!(file_sync(root, &[root.join("App/New.swift")], &[]).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_files_outside_any_project() {
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC)]);
|
||||
let root = dir.path();
|
||||
assert_eq!(file_sync(&root.join("Sub"), &[root.join("Sub/A.swift")], &[]), None);
|
||||
assert_eq!(file_sync(root, &[root.join(".build/A.swift"), PathBuf::from("/elsewhere/A.swift")], &[]), None);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -3096,8 +3111,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 +3744,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;
|
||||
|
||||
@@ -77,6 +77,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.
|
||||
@@ -222,6 +223,8 @@ impl Host {
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
|
||||
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
|
||||
let styled = ide_tools::managed_npm_plugin(&data_dir, "typescript-styled-plugin");
|
||||
ide_sdk::apply::configure_styled(cfg, server_root, styled.as_deref());
|
||||
// After the global plugins: they keep the IDE's copies.
|
||||
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
|
||||
let container_python = effective.languages.python.run_target().is_some();
|
||||
@@ -417,6 +420,8 @@ 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)?));
|
||||
@@ -439,6 +444,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();
|
||||
@@ -468,6 +474,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))
|
||||
@@ -718,6 +725,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),
|
||||
@@ -771,6 +779,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);
|
||||
@@ -782,6 +792,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);
|
||||
}
|
||||
@@ -1013,6 +1026,7 @@ impl Host {
|
||||
notebooks,
|
||||
kotlin_bridge: None,
|
||||
phpstan: None,
|
||||
swiftlint: None,
|
||||
tsc_watch: None,
|
||||
watcher: Arc::new(watcher),
|
||||
content_watchers: Mutex::new(Vec::new()),
|
||||
|
||||
@@ -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")));
|
||||
}
|
||||
}
|
||||
@@ -267,6 +267,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 +280,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) {
|
||||
|
||||
@@ -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),
|
||||
@@ -414,7 +414,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
|
||||
});
|
||||
|
||||
// Caches & LSP & Web & Workspace & HTTP helpers already available through ide-host dependencies.
|
||||
dispatcher.add("caches_local_data_info", TrustClass::Trusted, |c| async move {
|
||||
dispatcher.add("caches_local_data_info", TrustClass::Always, |c| async move {
|
||||
let current = c.host.local_data_dir.to_string_lossy().into_owned();
|
||||
Ok(LocalDataInfo {
|
||||
default_dir: current.clone(),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1166,8 +1166,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 +1221,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;
|
||||
@@ -1596,14 +1603,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 +1622,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 +1639,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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! speak (a WebSocket): direct, or through an HTTP proxy's `CONNECT` tunnel.
|
||||
|
||||
use base64::Engine;
|
||||
use ide_core::proxy_settings::ProxyRoute;
|
||||
use hyper_util::client::proxy::matcher::Matcher;
|
||||
use ide_core::proxy_settings::{ProxyRoute, ProxySettings};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
@@ -10,32 +11,84 @@ use tokio::net::TcpStream;
|
||||
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// The PAC lookup of the system proxy settings; none outside macOS.
|
||||
#[cfg(target_os = "macos")]
|
||||
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = crate::system_pac_route;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
const SYSTEM_PAC: fn(&str) -> Option<ProxyRoute> = |_| None;
|
||||
|
||||
/// A connection to `url`'s host and port, through the proxy System Settings › HTTP Proxy
|
||||
/// (or, in Auto mode, the system) routes that host to.
|
||||
pub async fn connect(url: &reqwest::Url) -> IdeResult<TcpStream> {
|
||||
let route = ide_core::proxy_settings::proxy().route(url.host_str());
|
||||
connect_with(url, route, SYSTEM_PAC, Matcher::from_system, false).await
|
||||
}
|
||||
|
||||
/// [`connect`] under explicit proxy `settings`; a proxy the tunnel cannot speak to (SOCKS) is skipped and
|
||||
/// the connection goes direct, as it did before the proxy was consulted at all.
|
||||
pub async fn connect_best_effort(url: &reqwest::Url, settings: &ProxySettings) -> IdeResult<TcpStream> {
|
||||
connect_with(url, settings.route(url.host_str()), SYSTEM_PAC, Matcher::from_system, true).await
|
||||
}
|
||||
|
||||
/// `host:port`; `host_str` already brackets an IPv6 address (the same rule as `pac.rs`'s `authority`).
|
||||
fn authority(host: &str, port: u16) -> String {
|
||||
if host.contains(':') && !host.starts_with('[') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }
|
||||
}
|
||||
|
||||
/// The URI the system proxy settings are asked about: the scheme reqwest would use (`ws` → `http`).
|
||||
fn system_uri(url: &reqwest::Url) -> IdeResult<http::Uri> {
|
||||
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
|
||||
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
|
||||
let target = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") };
|
||||
let proxy = match ide_core::proxy_settings::proxy().route(Some(host)) {
|
||||
let target = authority(host, port);
|
||||
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
|
||||
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))
|
||||
}
|
||||
|
||||
/// `connect` with the proxy settings' `route`, the PAC lookup and the system matcher injected;
|
||||
/// `skip_unusable` sends a route the tunnel cannot speak to direct instead of failing.
|
||||
async fn connect_with(
|
||||
url: &reqwest::Url,
|
||||
route: ProxyRoute,
|
||||
pac: impl FnOnce(&str) -> Option<ProxyRoute> + Send + 'static,
|
||||
matcher: impl FnOnce() -> Matcher,
|
||||
skip_unusable: bool,
|
||||
) -> IdeResult<TcpStream> {
|
||||
let host = url.host_str().ok_or_else(|| IdeError::invalid("the URL has no host"))?;
|
||||
let port = url.port_or_known_default().ok_or_else(|| IdeError::invalid("the URL has no port"))?;
|
||||
let target = authority(host, port);
|
||||
let proxy = match route {
|
||||
ProxyRoute::Direct => None,
|
||||
ProxyRoute::Via(via) => Some(via),
|
||||
ProxyRoute::System => {
|
||||
// The system proxy of the scheme reqwest would use (`ws` → `http`).
|
||||
let scheme = if url.scheme() == "wss" || url.scheme() == "https" { "https" } else { "http" };
|
||||
let uri: http::Uri =
|
||||
format!("{scheme}://{target}/").parse().map_err(|_| IdeError::invalid("invalid host"))?;
|
||||
hyper_util::client::proxy::matcher::Matcher::from_system().intercept(&uri).map(|intercept| {
|
||||
let auth =
|
||||
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
|
||||
let uri = intercept.uri();
|
||||
format!(
|
||||
"{}://{auth}{}",
|
||||
uri.scheme_str().unwrap_or("http"),
|
||||
uri.authority().map(|a| a.as_str()).unwrap_or_default()
|
||||
)
|
||||
})
|
||||
let uri = system_uri(url)?;
|
||||
// On macOS the resolver may run the PAC script (`dnsResolve`), so it stays off the async threads. A
|
||||
// script still loading answers with the matcher's route.
|
||||
let probe = uri.to_string();
|
||||
#[cfg(target_os = "macos")]
|
||||
let pac = tokio::task::spawn_blocking(move || pac(&probe))
|
||||
.await
|
||||
.map_err(|error| IdeError::unavailable(format!("proxy lookup failed: {error}")))?;
|
||||
// Nothing to evaluate outside macOS: no hop to the blocking pool.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let pac = pac(&probe);
|
||||
match pac {
|
||||
Some(ProxyRoute::Via(via)) if via.starts_with("http://") => Some(via),
|
||||
Some(ProxyRoute::Direct) => None,
|
||||
// No PAC applies, or it names a proxy this tunnel cannot speak to (SOCKS): the matcher's route.
|
||||
_ => matcher().intercept(&uri).map(|intercept| {
|
||||
let auth =
|
||||
intercept.raw_auth().map(|(user, password)| format!("{user}:{password}@")).unwrap_or_default();
|
||||
let uri = intercept.uri();
|
||||
format!(
|
||||
"{}://{auth}{}",
|
||||
uri.scheme_str().unwrap_or("http"),
|
||||
uri.authority().map(|a| a.as_str()).unwrap_or_default()
|
||||
)
|
||||
}),
|
||||
}
|
||||
}
|
||||
};
|
||||
let proxy = proxy.filter(|proxy| !skip_unusable || proxy.starts_with("http://"));
|
||||
let connecting = async {
|
||||
let Some(proxy) = proxy else {
|
||||
return TcpStream::connect(&target).await.map_err(|error| reach(&target, &error));
|
||||
@@ -157,6 +210,93 @@ mod tests {
|
||||
assert!(error.message.contains("needs a login"), "{}", error.message);
|
||||
}
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn matcher_via(address: &str) -> impl FnOnce() -> Matcher {
|
||||
let address = address.to_owned();
|
||||
move || Matcher::builder().all(format!("http://{address}")).build()
|
||||
}
|
||||
|
||||
/// The CONNECT line a proxy was asked for, or `None` when nothing connected within a moment.
|
||||
async fn asked(task: tokio::task::JoinHandle<String>) -> Option<String> {
|
||||
tokio::time::timeout(Duration::from_millis(300), task).await.ok().map(|head| head.unwrap())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_pac_route_wins_over_the_matcher_and_ws_is_looked_up_as_http() {
|
||||
let (pac_proxy, pac_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let seen = Arc::new(Mutex::new(String::new()));
|
||||
let recorded = Arc::clone(&seen);
|
||||
let pac = move |probe: &str| {
|
||||
*recorded.lock().unwrap() = probe.to_owned();
|
||||
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
|
||||
};
|
||||
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
|
||||
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap();
|
||||
assert_eq!(*seen.lock().unwrap(), "http://pac-target.invalid:8080/");
|
||||
assert!(asked(pac_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
|
||||
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wss_is_looked_up_as_https() {
|
||||
let (pac_proxy, _) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let seen = Arc::new(Mutex::new(String::new()));
|
||||
let recorded = Arc::clone(&seen);
|
||||
let pac = move |probe: &str| {
|
||||
*recorded.lock().unwrap() = probe.to_owned();
|
||||
Some(ProxyRoute::Via(format!("http://{pac_proxy}")))
|
||||
};
|
||||
let url = reqwest::Url::parse("wss://pac-target.invalid/s").unwrap();
|
||||
connect_with(&url, ProxyRoute::System, pac, || Matcher::builder().build(), false).await.unwrap();
|
||||
assert_eq!(*seen.lock().unwrap(), "https://pac-target.invalid:443/");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_resolved_direct_route_skips_the_matchers_proxy() {
|
||||
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
|
||||
connect_with(&url, ProxyRoute::System, |_| Some(ProxyRoute::Direct), matcher_via(&matcher_proxy), false)
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::timeout(Duration::from_millis(300), listener.accept())
|
||||
.await
|
||||
.expect("no direct connection")
|
||||
.unwrap();
|
||||
assert_eq!(asked(matcher_asked).await, None, "the matcher's proxy must not be used");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_socks_pac_route_keeps_the_matchers_route() {
|
||||
let (matcher_proxy, matcher_asked) = proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;
|
||||
let url = reqwest::Url::parse("ws://pac-target.invalid:8080/s").unwrap();
|
||||
let pac = |_: &str| Some(ProxyRoute::Via("socks5h://127.0.0.1:1080".into()));
|
||||
connect_with(&url, ProxyRoute::System, pac, matcher_via(&matcher_proxy), false).await.unwrap();
|
||||
assert!(asked(matcher_asked).await.unwrap().starts_with("CONNECT pac-target.invalid:8080 HTTP/1.1\r\n"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unusable_proxy_is_skipped_only_when_asked() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
|
||||
let socks = || ProxyRoute::Via("socks5h://127.0.0.1:1".into());
|
||||
let none = || Matcher::builder().build();
|
||||
assert!(connect_with(&url, socks(), |_| None, none, false).await.unwrap_err().message.contains("socks5h"));
|
||||
connect_with(&url, socks(), |_| None, none, true).await.unwrap();
|
||||
listener.accept().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_ipv6_literal_is_connected_to() {
|
||||
let Ok(listener) = TcpListener::bind("[::1]:0").await else { return }; // no IPv6 loopback here
|
||||
let url = reqwest::Url::parse(&format!("ws://{}/s", listener.local_addr().unwrap())).unwrap();
|
||||
connect_with(&url, ProxyRoute::Direct, |_| None, || Matcher::builder().build(), false).await.unwrap();
|
||||
listener.accept().await.unwrap();
|
||||
assert_eq!(authority("[::1]", 9), "[::1]:9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_credentials_are_percent_decoded() {
|
||||
assert_eq!(percent_decode("a%40b%3Ac"), "a@b:c");
|
||||
|
||||
@@ -258,7 +258,8 @@ impl ProjectIndex {
|
||||
}
|
||||
|
||||
/// Bounded file inventory for background plugin indexers; honors the same
|
||||
/// project/exclude scope as search and never walks the filesystem.
|
||||
/// project/exclude scope as search, leaves VCS-ignored files out and never
|
||||
/// walks the filesystem.
|
||||
pub fn files_with_extensions(&self, extensions: &[String], limit: usize) -> Vec<PathBuf> {
|
||||
self.shared
|
||||
.data
|
||||
@@ -266,6 +267,7 @@ impl ProjectIndex {
|
||||
.files
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|f| !f.ignored)
|
||||
.filter(|f| f.path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e)))
|
||||
.take(limit)
|
||||
.map(|f| f.path.clone())
|
||||
|
||||
@@ -895,15 +895,19 @@ fn workspace_scope_excludes_state_from_scans_updates_and_cached_results() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_inventory_respects_excludes_and_symbols_require_matching_text() {
|
||||
fn plugin_inventory_respects_excludes_and_ignores_and_symbols_require_matching_text() {
|
||||
let java = "package demo; interface UserMapper { void find(); }";
|
||||
let f = Fixture::new(&[
|
||||
("src/UserMapper.java", java),
|
||||
("src/mapper.xml", "<mapper/>"),
|
||||
("target/Generated.java", "class Generated {}"),
|
||||
("other.txt", "ignored"),
|
||||
(".gitignore", "gen/\n"),
|
||||
("gen/Ignored.java", "class Ignored {}"),
|
||||
]);
|
||||
let index = f.open();
|
||||
// Go to File lists the git-ignored file; plugin navigation leaves it out.
|
||||
assert_eq!(files(&index, "Ignored"), ["gen/Ignored.java"]);
|
||||
let paths = index.files_with_extensions(&["java".into(), "xml".into()], 100);
|
||||
assert_eq!(paths.len(), 2);
|
||||
assert!(paths.iter().all(|p| p.starts_with(f.root.join("src"))));
|
||||
|
||||
@@ -32,6 +32,7 @@ tree-sitter-java = "0.23.5"
|
||||
tree-sitter-kotlin-ng = "1.1.0"
|
||||
tree-sitter-c = "0.24.2"
|
||||
tree-sitter-cpp = "0.23.4"
|
||||
tree-sitter-objc = "3.0.2"
|
||||
tree-sitter-c-sharp = "0.23.5"
|
||||
tree-sitter-ruby = "0.23.1"
|
||||
tree-sitter-php = "0.25.1"
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
(class_interface . (identifier) @name category: (identifier) @detail) @def.extension
|
||||
(class_implementation . (identifier) @name category: (identifier) @detail) @def.extension
|
||||
(class_interface . (identifier) @name) @def.class
|
||||
(class_implementation . (identifier) @name) @def.class
|
||||
(protocol_declaration . (identifier) @name) @def.interface
|
||||
|
||||
(method_declaration ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method
|
||||
(method_definition ["+" "-"] @detail [(identifier) @name (method_parameter)]+) @def.method
|
||||
(property_declaration (struct_declaration (struct_declarator [
|
||||
(identifier) @name
|
||||
(pointer_declarator declarator: (identifier) @name)
|
||||
(function_declarator declarator: (parenthesized_declarator (block_pointer_declarator declarator: (identifier) @name)))
|
||||
]))) @def.property
|
||||
(instance_variable (struct_declaration (struct_declarator [
|
||||
(identifier) @name
|
||||
(pointer_declarator declarator: (identifier) @name)
|
||||
]))) @def.field
|
||||
|
||||
(preproc_call directive: (preproc_directive) @_d argument: (preproc_arg) @name
|
||||
(#eq? @_d "#pragma") (#match? @name "^mark\\s")) @outline.heading
|
||||
|
||||
(function_definition
|
||||
declarator: [
|
||||
(function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)
|
||||
(pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail))
|
||||
(pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)))
|
||||
]) @def.function
|
||||
(translation_unit (declaration
|
||||
declarator: [
|
||||
(function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail)
|
||||
(pointer_declarator declarator: (function_declarator declarator: (identifier) @name parameters: (parameter_list) @detail))
|
||||
]) @def.function)
|
||||
|
||||
(struct_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct
|
||||
(union_specifier name: (type_identifier) @name body: (field_declaration_list)) @def.struct
|
||||
(enum_specifier name: (type_identifier) @name body: (enumerator_list)) @def.enum
|
||||
(enumerator name: (identifier) @name) @def.enum_member
|
||||
(field_declaration_list (field_declaration declarator: [
|
||||
(field_identifier) @name
|
||||
(pointer_declarator declarator: (field_identifier) @name)
|
||||
(array_declarator declarator: (field_identifier) @name)
|
||||
]) @def.field)
|
||||
(type_definition declarator: (type_identifier) @name) @def.type
|
||||
(preproc_def name: (identifier) @name) @def.macro
|
||||
(preproc_function_def name: (identifier) @name parameters: (preproc_params) @detail) @def.macro
|
||||
(translation_unit (declaration declarator: [
|
||||
(identifier) @name
|
||||
(init_declarator declarator: (identifier) @name)
|
||||
(init_declarator declarator: (pointer_declarator declarator: (identifier) @name))
|
||||
]) @def.variable)
|
||||
@@ -90,6 +90,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("slint", include_str!("../../../languages/slint.toml")),
|
||||
("sql", include_str!("../../../languages/sql.toml")),
|
||||
("svelte", include_str!("../../../languages/svelte.toml")),
|
||||
("strings", include_str!("../../../languages/strings.toml")),
|
||||
("swift", include_str!("../../../languages/swift.toml")),
|
||||
("terraform", include_str!("../../../languages/terraform.toml")),
|
||||
("terraform-vars", include_str!("../../../languages/terraform-vars.toml")),
|
||||
@@ -98,6 +99,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("typescriptreact", include_str!("../../../languages/typescriptreact.toml")),
|
||||
("typst", include_str!("../../../languages/typst.toml")),
|
||||
("vue", include_str!("../../../languages/vue.toml")),
|
||||
("xcconfig", include_str!("../../../languages/xcconfig.toml")),
|
||||
("xml", include_str!("../../../languages/xml.toml")),
|
||||
("yaml", include_str!("../../../languages/yaml.toml")),
|
||||
("zig", include_str!("../../../languages/zig.toml")),
|
||||
@@ -1277,6 +1279,11 @@ mod tests {
|
||||
("P.cs", "csharp"),
|
||||
("V.swift", "swift"),
|
||||
("AppDelegate.m", "objective-c"),
|
||||
("App.entitlements", "xml"),
|
||||
("PrivacyInfo.xcprivacy", "xml"),
|
||||
("Localizable.xcstrings", "json"),
|
||||
("Debug.xcconfig", "xcconfig"),
|
||||
("en.lproj/Localizable.strings", "strings"),
|
||||
("a.rb", "ruby"),
|
||||
("Gemfile", "ruby"),
|
||||
("show.html.erb", "erb"),
|
||||
|
||||
@@ -156,6 +156,24 @@ pub(crate) static SPECS: &[Spec] = &[
|
||||
imports: &["preproc_include", "using_declaration"],
|
||||
constructors: NONE,
|
||||
},
|
||||
Spec {
|
||||
name: "objc",
|
||||
language: tree_sitter_objc::LANGUAGE,
|
||||
outline: outline!("objc"),
|
||||
highlights: None,
|
||||
// `@interface` / `@implementation` / `@protocol` ... `@end` have no brackets.
|
||||
fold_nodes: &[
|
||||
"class_interface",
|
||||
"class_implementation",
|
||||
"protocol_declaration",
|
||||
"preproc_if",
|
||||
"preproc_ifdef",
|
||||
"preproc_function_def",
|
||||
],
|
||||
fold_bodies: NONE,
|
||||
imports: &["preproc_include", "module_import"],
|
||||
constructors: NONE,
|
||||
},
|
||||
Spec {
|
||||
name: "csharp",
|
||||
language: tree_sitter_c_sharp::LANGUAGE,
|
||||
|
||||
@@ -180,7 +180,11 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
|
||||
}
|
||||
names.sort_by_key(|n| n.start_byte());
|
||||
names.dedup_by_key(|n| n.id());
|
||||
let base = names.iter().map(|n| name_text(n, text)).collect::<Vec<_>>().join(".");
|
||||
let mut base = names.iter().map(|n| name_text(n, text)).collect::<Vec<_>>().join(".");
|
||||
// Objective-C selectors: `- (id)initWithName:(id)n age:(int)a` is `initWithName:age:`.
|
||||
if g.spec.name == "objc" && node.children(&mut node.walk()).any(|c| c.kind() == "method_parameter") {
|
||||
base = names.iter().map(|n| format!("{}:", name_text(n, text))).collect();
|
||||
}
|
||||
if base.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -539,6 +543,12 @@ fn name_text(n: &Node, text: &str) -> String {
|
||||
let t = node_text(n, text);
|
||||
// Ruby / Elixir symbols: `:total` -> `total`.
|
||||
let t = if matches!(n.kind(), "simple_symbol" | "atom") { t.trim_start_matches(':') } else { t };
|
||||
// Objective-C `#pragma mark - Lifecycle` -> `Lifecycle` (a bare `mark -` is a separator, so empty).
|
||||
let t = if n.kind() == "preproc_arg" {
|
||||
t.trim().trim_start_matches("mark").trim_start().trim_start_matches('-')
|
||||
} else {
|
||||
t
|
||||
};
|
||||
clean(t, 120)
|
||||
}
|
||||
|
||||
|
||||
@@ -546,6 +546,119 @@ int main() { return 0; }
|
||||
assert_eq!(t.iter().filter(|(n, k, _)| n == "draw" && *k == SymbolKind::Method).count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_objc() {
|
||||
let src = r#"#import <Foundation/Foundation.h>
|
||||
#define MAX 10
|
||||
@protocol Greeting <NSObject>
|
||||
- (NSString *)greet;
|
||||
@optional
|
||||
@property (nonatomic) int level;
|
||||
@end
|
||||
|
||||
@interface Person : NSObject <Greeting> {
|
||||
int _age;
|
||||
}
|
||||
@property (nonatomic, copy) NSString *name;
|
||||
+ (instancetype)personWithName:(NSString *)name age:(int)age;
|
||||
- (void)run;
|
||||
@end
|
||||
|
||||
@interface Person (Extra)
|
||||
- (void)extra;
|
||||
@end
|
||||
|
||||
@implementation Person
|
||||
#pragma mark - Lifecycle
|
||||
+ (instancetype)personWithName:(NSString *)name age:(int)age {
|
||||
return nil;
|
||||
}
|
||||
- (void)run {
|
||||
}
|
||||
@end
|
||||
|
||||
static int helper(int x) { return x; }
|
||||
"#;
|
||||
check_outline(
|
||||
"objective-c",
|
||||
src,
|
||||
"
|
||||
Macro MAX
|
||||
Interface Greeting
|
||||
Method greet
|
||||
Property level
|
||||
Class Person
|
||||
Field _age
|
||||
Property name
|
||||
Method personWithName:age:
|
||||
Method run
|
||||
Namespace Person
|
||||
Method extra
|
||||
Class Person
|
||||
Key Lifecycle
|
||||
Method personWithName:age:
|
||||
Method run
|
||||
Function helper
|
||||
",
|
||||
);
|
||||
let t = tags("objective-c", src);
|
||||
assert!(has_tag(&t, "greet", SymbolKind::Method, Some("Greeting")));
|
||||
assert!(has_tag(&t, "personWithName:age:", SymbolKind::Method, Some("Person")));
|
||||
assert!(has_tag(&t, "extra", SymbolKind::Method, Some("Person")));
|
||||
assert!(has_tag(&t, "name", SymbolKind::Property, Some("Person")));
|
||||
assert!(!t.iter().any(|(n, _, _)| n == "Lifecycle"));
|
||||
let t = tags("objective-c", "@interface A\n@property (copy) void (^onTap)(int i);\n@end\n");
|
||||
assert!(has_tag(&t, "onTap", SymbolKind::Property, Some("A")), "{t:?}");
|
||||
// `@interface` / `@protocol` / `@implementation` ... `@end` fold like a braced body.
|
||||
let f = folds("objective-c", src);
|
||||
for range in [(2, 6), (8, 14), (16, 18), (20, 27), (22, 24)] {
|
||||
assert!(f.contains(&(range.0, range.1, FoldKind::Region)), "{range:?} not in {f:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_objective_cpp_keeps_the_objc_structure() {
|
||||
// C++ declarations outside the ObjC blocks are lost to error recovery; the ObjC
|
||||
// classes and methods, which are why a file is `.mm`, stay.
|
||||
check_outline(
|
||||
"objective-cpp",
|
||||
r#"#import "Bridge.h"
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
namespace engine {
|
||||
class Renderer {
|
||||
public:
|
||||
void draw(const std::vector<int> &xs);
|
||||
};
|
||||
}
|
||||
|
||||
@implementation Bridge {
|
||||
std::unique_ptr<engine::Renderer> _renderer;
|
||||
}
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
_renderer = std::make_unique<engine::Renderer>();
|
||||
return self;
|
||||
}
|
||||
- (void)drawValues:(NSArray<NSNumber *> *)values {
|
||||
std::vector<int> xs;
|
||||
for (NSNumber *n in values) { xs.push_back(n.intValue); }
|
||||
_renderer->draw(xs);
|
||||
}
|
||||
@end
|
||||
|
||||
static std::string helper() { return "x"; }
|
||||
"#,
|
||||
"
|
||||
Class Bridge
|
||||
Method init
|
||||
Method drawValues:
|
||||
Function helper
|
||||
",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_csharp() {
|
||||
check_outline(
|
||||
|
||||
@@ -9,7 +9,8 @@ use crate::LspManager;
|
||||
use crate::server::{Running, Server};
|
||||
use ide_core::error::{ErrorData, ErrorKind};
|
||||
use ide_core::event::LspRefreshKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Location, Pos};
|
||||
use lsp_types as lsp;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use specta::Type;
|
||||
@@ -20,6 +21,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
pub(crate) const SERVER: &str = "jdtls";
|
||||
const GENERATED_SOURCES: &str = "openidea.java.generatedSources";
|
||||
const METHOD_REFERENCE_DEFINITION: &str = "openidea.java.methodReferenceDefinition";
|
||||
|
||||
pub(crate) mod configuration;
|
||||
pub(crate) mod exception_breakpoints;
|
||||
@@ -120,10 +122,24 @@ pub fn configure_project_structure(
|
||||
// JDT resolves relative library globs against its own root, which may be a submodule.
|
||||
Some(root.join(trimmed).to_string_lossy().replace('\\', "/"))
|
||||
};
|
||||
let normalize_class = |entry: &str| -> Option<String> {
|
||||
let trimmed = entry.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let resolved = root.join(trimmed);
|
||||
let path = resolved.to_string_lossy().replace('\\', "/");
|
||||
// A directory library root (e.g. `WebRoot/WEB-INF/lib`) needs a `**/*.jar` glob so jdtls
|
||||
// indexes the JAR archives inside it rather than ignoring the bare folder path.
|
||||
if resolved.is_dir() && !ide_core::settings::jar_files(&resolved, true).is_empty() {
|
||||
return Some(format!("{}/**/*.jar", path.trim_end_matches('/')));
|
||||
}
|
||||
Some(path)
|
||||
};
|
||||
let mut include: Vec<String> = Vec::new();
|
||||
let mut sources = serde_json::Map::new();
|
||||
for lib in &structure.libraries {
|
||||
let class_entries: Vec<String> = lib.classes.iter().filter_map(|c| normalize(c)).collect();
|
||||
let class_entries: Vec<String> = lib.classes.iter().filter_map(|c| normalize_class(c)).collect();
|
||||
let source_entries: Vec<String> = lib.sources.iter().filter_map(|s| normalize(s)).collect();
|
||||
for c in &class_entries {
|
||||
if !include.contains(c) {
|
||||
@@ -131,7 +147,9 @@ pub fn configure_project_structure(
|
||||
}
|
||||
}
|
||||
for (class, source) in class_entries.iter().zip(&source_entries) {
|
||||
sources.insert(class.clone(), json!(source));
|
||||
if !class.contains('*') {
|
||||
sources.insert(class.clone(), json!(source));
|
||||
}
|
||||
}
|
||||
}
|
||||
for facet in &structure.facets {
|
||||
@@ -771,6 +789,19 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The declaration of a Java method named by `Type::method` / `expr::method` at `pos`.
|
||||
/// JDT's selection-based definition can return the functional interface method when the
|
||||
/// referenced method is inherited; the extension resolves the AST binding instead.
|
||||
pub(crate) async fn java_method_reference_definition(&self, path: &Path, pos: Pos) -> IdeResult<Vec<Location>> {
|
||||
let uri = crate::path_to_uri_string(path);
|
||||
let value = self
|
||||
.jdtls_command(path, METHOD_REFERENCE_DEFINITION, vec![json!(uri), json!(pos.line), json!(pos.col)])
|
||||
.await?;
|
||||
let locations: Vec<lsp::Location> = serde_json::from_value(value).unwrap_or_default();
|
||||
let conv = self.conv(crate::text::Encoding::Utf16);
|
||||
Ok(locations.iter().filter_map(|location| conv.location(location)).collect())
|
||||
}
|
||||
|
||||
/// The jdtls instance serving `path` (a module directory or source file),
|
||||
/// started if needed and waited for.
|
||||
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
|
||||
@@ -1938,4 +1969,51 @@ mod tests {
|
||||
configure_project_structure(&mut cfg, tmp.path(), tmp.path(), &structure);
|
||||
assert!(cfg.launch_error.as_deref().unwrap().contains("inside its module"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_library_root_expands_to_recursive_jar_glob_for_jdtls() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let web_lib = root.join("WebRoot/WEB-INF/lib");
|
||||
std::fs::create_dir_all(&web_lib).unwrap();
|
||||
std::fs::write(web_lib.join("gson.jar"), b"").unwrap();
|
||||
|
||||
let structure = ide_core::settings::ProjectStructureSettings {
|
||||
libraries: vec![ide_core::settings::ProjectLibrary {
|
||||
name: "lib".into(),
|
||||
classes: vec!["WebRoot/WEB-INF/lib".into()],
|
||||
sources: vec![],
|
||||
javadocs: vec![],
|
||||
scope: ide_core::settings::DependencyScope::Runtime,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let mut cfg: ide_language::LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
|
||||
configure_project_structure(&mut cfg, root, root, &structure);
|
||||
|
||||
let include = cfg
|
||||
.settings
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.pointer("/java/project/referencedLibraries/include")
|
||||
.and_then(Value::as_array)
|
||||
.unwrap();
|
||||
let expected = format!("{}/**/*.jar", web_lib.to_string_lossy().replace('\\', "/"));
|
||||
assert!(include.contains(&json!(expected)), "include={include:?}");
|
||||
// A class folder without jars stays a plain path.
|
||||
let classes = root.join("classes");
|
||||
std::fs::create_dir_all(&classes).unwrap();
|
||||
let structure = ide_core::settings::ProjectStructureSettings {
|
||||
libraries: vec![ide_core::settings::ProjectLibrary {
|
||||
name: "classes".into(),
|
||||
classes: vec!["classes".into()],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let mut cfg: ide_language::LanguageServerConfig = toml::from_str("name = 'jdtls'\ncommand = 'jdtls'").unwrap();
|
||||
configure_project_structure(&mut cfg, root, root, &structure);
|
||||
let include = cfg.settings.as_ref().unwrap().pointer("/java/project/referencedLibraries/include").cloned();
|
||||
assert!(!format!("{include:?}").contains("classes/**"), "include={include:?}");
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ mod pull;
|
||||
mod scope;
|
||||
mod server;
|
||||
mod source_actions;
|
||||
mod switch_source_header;
|
||||
mod tcp;
|
||||
mod text;
|
||||
mod ts_file_moves;
|
||||
@@ -57,7 +58,7 @@ pub use jdtls::stream_trace::JdtStreamTracer;
|
||||
pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable};
|
||||
pub use launch::{LaunchError, Launcher, ProcessLauncher};
|
||||
pub use message_requests::answer as answer_message_request;
|
||||
pub use notebook::{NotebookCell, NotebookCellDoc, cell_uri};
|
||||
pub use notebook::{NotebookCell, NotebookCellDoc, NotebookCellText, cell_uri};
|
||||
pub use plugin_requests::plugin_method_allowed;
|
||||
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
|
||||
pub use uri::{path_to_uri_string, uri_target, uri_to_path};
|
||||
@@ -326,6 +327,25 @@ fn goto_is_empty(r: &Option<lsp::GotoDefinitionResponse>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the caret is on the method name of a Java method reference (`Type::method`).
|
||||
/// A method reference can name a functional interface's method through JDT's selection-based
|
||||
/// definition when the referenced method is inherited, so ask the AST binding command instead.
|
||||
fn java_method_reference_at(text: &DocText, pos: Pos) -> bool {
|
||||
let line = text.line(pos.line as usize);
|
||||
let mut utf16 = 0u32;
|
||||
let mut at = line.len();
|
||||
for (i, c) in line.char_indices() {
|
||||
if utf16 >= pos.col {
|
||||
at = i;
|
||||
break;
|
||||
}
|
||||
utf16 += c.len_utf16() as u32;
|
||||
}
|
||||
let before = line[..at].trim_end();
|
||||
let Some(colon) = before.rfind("::") else { return false };
|
||||
before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
|
||||
}
|
||||
|
||||
fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
|
||||
match e {
|
||||
RpcError::Cancelled => IdeError::cancelled(),
|
||||
@@ -1792,7 +1812,31 @@ impl LspManager {
|
||||
}
|
||||
let (method, cap, feature) = goto_method(kind);
|
||||
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
|
||||
self.goto_in(&snap, &targets, method, pos, None, None).await
|
||||
let result = self.goto_in(&snap, &targets, method, pos, None, None).await;
|
||||
// JDT's selection-based definition can name the functional interface method for an
|
||||
// inherited method reference. Ask the Java binding command when that is what came back,
|
||||
// when the caret is on a method reference, or when the server found no target at all.
|
||||
let method_reference = snap.language.as_str() == "java" && java_method_reference_at(&snap.text, pos);
|
||||
if kind == GotoKind::Definition
|
||||
&& snap.language.as_str() == "java"
|
||||
&& (method_reference
|
||||
|| result.as_ref().is_ok_and(|locs| {
|
||||
locs.is_empty()
|
||||
|| locs.iter().any(|l| {
|
||||
let path = l.path.to_string_lossy().replace('\\', "/");
|
||||
let uri = l.uri.as_deref().unwrap_or_default();
|
||||
path.contains("java/util/function")
|
||||
|| path.contains("java.util.function")
|
||||
|| uri.contains("java/util/function")
|
||||
|| uri.contains("java.util.function")
|
||||
})
|
||||
}))
|
||||
&& let Ok(found) = self.java_method_reference_definition(&snap.path, pos).await
|
||||
&& !found.is_empty()
|
||||
{
|
||||
return Ok(found);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Go to Implementation, with the implementations found first passed to `partial` while
|
||||
@@ -2767,6 +2811,79 @@ impl LspManager {
|
||||
Ok(ts_file_moves::file_references(&result))
|
||||
}
|
||||
|
||||
/// Runs vtsls' own `command` for `doc`. typescript-language-server, TypeScript 7 and the
|
||||
/// Vue / Astro servers have none of these commands: they need vtsls.
|
||||
async fn vtsls_command(
|
||||
&self,
|
||||
doc: DocId,
|
||||
command: &str,
|
||||
arguments: impl FnOnce(&DocSnap, &Target) -> Option<Value>,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<(Target, Value)> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let t = self
|
||||
.ready_targets(&snap.servers, |c| c.commands().iter().any(|c| c == command))
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|t| t.server.name == "vtsls")
|
||||
.ok_or_else(|| IdeError::unavailable("This needs the vtsls TypeScript language server"))?;
|
||||
let arguments =
|
||||
arguments(&snap, &t).ok_or_else(|| IdeError::invalid(format!("invalid `{command}` arguments")))?;
|
||||
let params = json!({ "command": command, "arguments": arguments });
|
||||
let result = self.call(&t, "workspace/executeCommand", params, cancel, LONG_TIMEOUT).await?;
|
||||
Ok((t, result))
|
||||
}
|
||||
|
||||
/// Go to Source Definition: the JavaScript implementation of what `pos` refers to, not its
|
||||
/// `.d.ts` declaration (vtsls' `typescript.goToSourceDefinition`).
|
||||
pub async fn source_definition(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult<Vec<Location>> {
|
||||
let (t, result) = self
|
||||
.vtsls_command(
|
||||
doc,
|
||||
"typescript.goToSourceDefinition",
|
||||
|snap, t| Some(json!([snap.uri, snap.position(t, pos)])),
|
||||
Some(&cancel),
|
||||
)
|
||||
.await?;
|
||||
let locs: Vec<lsp::Location> = serde_json::from_value::<Option<_>>(result)
|
||||
.map_err(|e| IdeError::internal(format!("typescript.goToSourceDefinition: {e}")))?
|
||||
.unwrap_or_default();
|
||||
let conv = self.conv(t.enc());
|
||||
Ok(locs.iter().filter_map(|l| conv.location(l)).collect())
|
||||
}
|
||||
|
||||
/// Opens the `tsconfig.json` / `jsconfig.json` of `doc`'s project, or the TS Server log:
|
||||
/// vtsls answers with `window/showDocument` (or a message when there is none).
|
||||
pub async fn open_typescript_file(&self, doc: DocId, what: TypeScriptFile) -> IdeResult<()> {
|
||||
let (command, with_uri) = match what {
|
||||
TypeScriptFile::ProjectConfig => {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let js = snap.language.as_str().starts_with("javascript");
|
||||
(if js { "javascript.goToProjectConfig" } else { "typescript.goToProjectConfig" }, true)
|
||||
}
|
||||
TypeScriptFile::ServerLog => ("typescript.openTsServerLog", false),
|
||||
};
|
||||
self.vtsls_command(doc, command, |snap, _| Some(if with_uri { json!([snap.uri]) } else { json!([]) }), None)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The files tsserver suggests for vtsls' Move to File `command` (from a code action).
|
||||
pub async fn move_to_file_targets(
|
||||
&self,
|
||||
doc: DocId,
|
||||
command: Command,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Vec<PathBuf>> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let request = ts_file_moves::move_to_file_suggestions_request(&snap.path, &command.arguments)
|
||||
.ok_or_else(|| IdeError::invalid("invalid Move to File command"))?;
|
||||
let (_, result) = self
|
||||
.vtsls_command(doc, ts_file_moves::COMMAND, |_, _| request.get("arguments").cloned(), Some(&cancel))
|
||||
.await?;
|
||||
Ok(ts_file_moves::move_to_file_suggestions(&result))
|
||||
}
|
||||
|
||||
/// Whether a server of `doc` (`server`, when given) provides the command `name`. Code actions
|
||||
/// can carry commands other editors' extensions run themselves after the edit (vtsls'
|
||||
/// `_typescript.didOrganizeImports`): no server provides those.
|
||||
@@ -4676,6 +4793,36 @@ mod code_action_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod java_method_reference_tests {
|
||||
use super::java_method_reference_at;
|
||||
use crate::text::DocText;
|
||||
use ide_core::Pos;
|
||||
|
||||
#[test]
|
||||
fn finds_the_method_name_of_a_method_reference() {
|
||||
let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);");
|
||||
let col = "wrapper.set(XbkBtbOutNotice::get".len() as u32;
|
||||
assert!(java_method_reference_at(&text, Pos::new(0, col)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allows_whitespace_around_the_method_reference_operator() {
|
||||
let text = DocText::new("wrapper.set(XbkBtbOutNotice :: getUpdateTime, now);");
|
||||
let col = "wrapper.set(XbkBtbOutNotice :: get".len() as u32;
|
||||
assert!(java_method_reference_at(&text, Pos::new(0, col)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_regular_calls_and_the_referenced_type() {
|
||||
let text = DocText::new("wrapper.set(XbkBtbOutNotice::getUpdateTime, now);");
|
||||
let type_col = "wrapper.set(XbkBtbOutNotice".len() as u32;
|
||||
assert!(!java_method_reference_at(&text, Pos::new(0, type_col)));
|
||||
let call = DocText::new("wrapper.set(getUpdateTime(), now);");
|
||||
assert!(!java_method_reference_at(&call, Pos::new(0, "wrapper.set(get".len() as u32)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod did_change_content_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -40,6 +40,14 @@ pub struct NotebookCellDoc {
|
||||
pub uri: String,
|
||||
}
|
||||
|
||||
/// A cell document's buffer, as the notebook service keeps it.
|
||||
pub struct NotebookCellText {
|
||||
pub path: std::path::PathBuf,
|
||||
pub language: LanguageId,
|
||||
pub text: String,
|
||||
pub version: u32,
|
||||
}
|
||||
|
||||
pub(crate) struct NotebookState {
|
||||
uri: lsp::Uri,
|
||||
language: LanguageId,
|
||||
@@ -154,6 +162,22 @@ impl LspManager {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A cell document's buffer, for work that runs without asking a server — formatting reads
|
||||
/// it from `documents`, which only holds files the editor opened, never a notebook's cells.
|
||||
pub fn cell_text(&self, doc: DocId) -> Option<NotebookCellText> {
|
||||
let docs = self.docs.lock();
|
||||
let d = docs.get(&doc)?;
|
||||
// The notebook file, not the cell's own `vscode-notebook-cell:` uri: a formatter
|
||||
// looks the file up to find the project's settings and the language of the file.
|
||||
let path = d.notebook.clone()?;
|
||||
Some(NotebookCellText {
|
||||
path,
|
||||
language: d.language.clone(),
|
||||
text: d.text.as_str().to_owned(),
|
||||
version: d.version.max(0) as u32,
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens the notebooks of `server`'s language on its instance that just became ready.
|
||||
pub(crate) fn reopen_notebooks(&self, server: &Arc<Server>, run: &Running) {
|
||||
let mut pull = Vec::new();
|
||||
@@ -384,4 +408,27 @@ mod tests {
|
||||
assert!(is_cell_uri(&uri) && parse_uri(&uri).is_some());
|
||||
assert!(!is_cell_uri("file:///a.ipynb") && !is_cell_uri("vscode-notebook-cellx:/a"));
|
||||
}
|
||||
|
||||
/// A cell lives in `docs` only, never in `documents`; formatting asks for its buffer here.
|
||||
#[test]
|
||||
fn cell_text_answers_for_a_cell_document_and_nothing_else() {
|
||||
let manager = LspManager::new(
|
||||
PathBuf::from("/work"),
|
||||
std::sync::Arc::new(crate::LanguageRegistry::load(None).unwrap()),
|
||||
std::sync::Arc::new(|_: ide_core::IdeEvent| {}),
|
||||
);
|
||||
let path = PathBuf::from("/work/a.ipynb");
|
||||
let cells = [NotebookCell { id: "cell-a".into(), source: "x=1".into() }];
|
||||
manager.sync_notebook(&path, &LanguageId::new("python"), &cells);
|
||||
|
||||
let doc = manager.notebook_cells(&path)[0].doc;
|
||||
let text = manager.cell_text(doc).expect("a cell document answers");
|
||||
assert_eq!(text.text, "x=1");
|
||||
// The notebook file, so a formatter finds the project's settings for it.
|
||||
assert_eq!(text.path, path);
|
||||
assert_eq!(text.language.as_str(), "python");
|
||||
|
||||
// A document the notebook service does not know stays unknown.
|
||||
assert!(manager.cell_text(DocId(9999)).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Switch Header/Source for C, C++ and Objective-C through clangd's
|
||||
//! `textDocument/switchSourceHeader` extension. The editor falls back to a file with the
|
||||
//! same name when clangd does not serve the document or finds nothing.
|
||||
|
||||
use crate::{DEFAULT_TIMEOUT, LspManager, uri};
|
||||
use ide_core::{CancellationToken, DocId, IdeResult};
|
||||
use serde_json::Value;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const SERVER: &str = "clangd";
|
||||
const METHOD: &str = "textDocument/switchSourceHeader";
|
||||
|
||||
impl LspManager {
|
||||
/// clangd's header for the document's source file, or source for its header; `None`
|
||||
/// when clangd finds none or does not serve the document.
|
||||
pub async fn switch_source_header(&self, doc: DocId, cancel: CancellationToken) -> IdeResult<Option<PathBuf>> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let clangd: Vec<_> = snap.servers.iter().filter(|s| s.name == SERVER).cloned().collect();
|
||||
let Some(t) = self.ready_targets(&clangd, |_| true).await.into_iter().next() else { return Ok(None) };
|
||||
let found: Value = self.call(&t, METHOD, snap.ident(), Some(&cancel), DEFAULT_TIMEOUT).await?;
|
||||
Ok(found.as_str().and_then(uri::uri_to_path))
|
||||
}
|
||||
}
|
||||
@@ -87,10 +87,56 @@ pub(crate) fn file_references(result: &Value) -> Vec<ide_core::Location> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `typescript.tsserverRequest` arguments asking where the selection of vtsls' Move to File
|
||||
/// command (`_typescript.moveToFileRefactoring` with `[action, uri, range]`, run with the target
|
||||
/// file appended) can go.
|
||||
pub(crate) fn move_to_file_suggestions_request(file: &std::path::Path, arguments: &[Value]) -> Option<Value> {
|
||||
let range: lsp_types::Range = serde_json::from_value(arguments.get(2)?.clone()).ok()?;
|
||||
// tsserver: 1-based lines and UTF-16 offsets; vtsls speaks UTF-16.
|
||||
Some(json!({
|
||||
"command": COMMAND,
|
||||
"arguments": ["getMoveToRefactoringFileSuggestions", {
|
||||
"file": file,
|
||||
"startLine": range.start.line + 1,
|
||||
"startOffset": range.start.character + 1,
|
||||
"endLine": range.end.line + 1,
|
||||
"endOffset": range.end.character + 1,
|
||||
}],
|
||||
}))
|
||||
}
|
||||
|
||||
/// The files tsserver suggests in its `getMoveToRefactoringFileSuggestions` answer.
|
||||
pub(crate) fn move_to_file_suggestions(result: &Value) -> Vec<PathBuf> {
|
||||
let body = result.get("body").unwrap_or(result);
|
||||
serde_json::from_value(body.get("files").cloned().unwrap_or_default()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn asks_tsserver_where_the_move_to_file_selection_can_go() {
|
||||
let action = json!({ "name": "Move to file", "kind": "refactor.move.file" });
|
||||
let range = json!({ "start": { "line": 6, "character": 16 }, "end": { "line": 8, "character": 1 } });
|
||||
let request = move_to_file_suggestions_request(
|
||||
std::path::Path::new("/p/src/util.ts"),
|
||||
&[action.clone(), json!("file:///p/src/util.ts"), range],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
request["arguments"],
|
||||
json!(["getMoveToRefactoringFileSuggestions", {
|
||||
"file": "/p/src/util.ts", "startLine": 7, "startOffset": 17, "endLine": 9, "endOffset": 2,
|
||||
}])
|
||||
);
|
||||
assert!(move_to_file_suggestions_request(std::path::Path::new("/p/a.ts"), &[action]).is_none());
|
||||
let answer =
|
||||
json!({ "success": true, "body": { "newFileName": "/p/src/greet.ts", "files": ["/p/src/app.ts"] } });
|
||||
assert_eq!(move_to_file_suggestions(&answer), vec![PathBuf::from("/p/src/app.ts")]);
|
||||
assert!(move_to_file_suggestions(&json!({ "success": false })).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_tsserver_file_references() {
|
||||
let result = json!({ "success": true, "body": { "symbolName": "\"./Hello.vue\"", "refs": [
|
||||
|
||||
@@ -109,6 +109,14 @@ pub struct Signature {
|
||||
pub parameters: Vec<(u32, u32)>,
|
||||
}
|
||||
|
||||
/// A file vtsls opens for a document: its project's configuration or the TS Server log.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TypeScriptFile {
|
||||
ProjectConfig,
|
||||
ServerLog,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GotoKind {
|
||||
|
||||
@@ -8800,3 +8800,75 @@ async fn hierarchy_refactorings_use_phoxites_requests_when_the_server_advertises
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Protocol);
|
||||
assert_eq!(e.message, "any-name: index out of bounds");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn switch_source_header_asks_clangd_and_only_clangd() {
|
||||
let h = harness_for("objective-c", "m", &[("clangd", incremental_caps())], &[]);
|
||||
let (doc, path) = h.open("Foo.m", "#import \"Foo.h\"\n");
|
||||
h.wait_status("clangd", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("clangd");
|
||||
let header = h.root.join("Foo.h");
|
||||
s.respond("textDocument/switchSourceHeader", json!(uri_of(&header)));
|
||||
assert_eq!(h.mgr.switch_source_header(doc, CancellationToken::new()).await.unwrap(), Some(header));
|
||||
assert_eq!(s.requested("textDocument/switchSourceHeader"), vec![json!({ "uri": uri_of(&path) })]);
|
||||
// clangd found nothing: the editor falls back to a file of the same name.
|
||||
s.respond("textDocument/switchSourceHeader", Value::Null);
|
||||
assert_eq!(h.mgr.switch_source_header(doc, CancellationToken::new()).await.unwrap(), None);
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// Another server is never sent clangd's extension.
|
||||
let h = harness_for("objective-c", "m", &[("mock", incremental_caps())], &[]);
|
||||
let (doc, _) = h.open("Foo.m", "");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
assert_eq!(h.mgr.switch_source_header(doc, CancellationToken::new()).await.unwrap(), None);
|
||||
assert!(h.launcher.state("mock").requested("textDocument/switchSourceHeader").is_empty());
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// C-family files go to sourcekit-lsp in an Xcode project with a BSP config (`buildServer.json`),
|
||||
/// which hands them to clangd with the build's flags; elsewhere, and when sourcekit-lsp is missing,
|
||||
/// to plain clangd. Uses the shipped language definitions.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn c_family_files_use_sourcekit_lsp_only_with_an_xcode_bsp_config() {
|
||||
let registry = LanguageRegistry::load(None).unwrap();
|
||||
for (language, ext) in [("c", "h"), ("cpp", "cpp"), ("objective-c", "m"), ("objective-cpp", "mm")] {
|
||||
let shipped = registry.get(&LanguageId::new(language)).unwrap().language_servers;
|
||||
let names: Vec<_> = shipped.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(names, ["sourcekit-lsp", "clangd"], "{language}");
|
||||
let servers = [("sourcekit-lsp", incremental_caps()), ("clangd", incremental_caps())];
|
||||
let as_shipped = |cfg: &mut LanguageServerConfig| {
|
||||
let real = shipped.iter().find(|c| c.name == cfg.name).unwrap();
|
||||
cfg.root_markers = real.root_markers.clone();
|
||||
cfg.require_root_marker = real.require_root_marker;
|
||||
cfg.replaces = real.replaces.clone();
|
||||
};
|
||||
let file = format!("Foo.{ext}");
|
||||
|
||||
// A plain folder, or one with only compile_commands.json: clangd alone.
|
||||
let h = harness_configured(language, ext, &servers, as_shipped);
|
||||
std::fs::write(h.root.join("compile_commands.json"), "[]").unwrap();
|
||||
h.open(&file, "");
|
||||
h.wait_status("clangd", ServerStatus::Ready).await;
|
||||
assert!(h.statuses("sourcekit-lsp").is_empty(), "{language}");
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// An Xcode project with buildServer.json: sourcekit-lsp alone, rooted at the config.
|
||||
let h = harness_configured(language, ext, &servers, as_shipped);
|
||||
std::fs::write(h.root.join("buildServer.json"), "{}").unwrap();
|
||||
let (_, path) = h.open(&file, "");
|
||||
h.wait_status("sourcekit-lsp", ServerStatus::Ready).await;
|
||||
eventually(|| h.launcher.state("sourcekit-lsp").docs.lock().contains_key(&uri_of(&path))).await;
|
||||
assert!(h.statuses("clangd").is_empty(), "{language}");
|
||||
assert_eq!(h.mgr.servers().iter().map(|s| s.root.clone()).collect::<Vec<_>>(), std::slice::from_ref(&h.root));
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// sourcekit-lsp not installed: clangd still serves.
|
||||
let h = harness_configured(language, ext, &servers, as_shipped);
|
||||
h.launcher.state("sourcekit-lsp").missing.store(true, Ordering::SeqCst);
|
||||
std::fs::write(h.root.join("buildServer.json"), "{}").unwrap();
|
||||
h.open(&file, "");
|
||||
h.wait_status("sourcekit-lsp", ServerStatus::Missing).await;
|
||||
h.wait_status("clangd", ServerStatus::Ready).await;
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
}
|
||||
@@ -969,6 +969,135 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// vtsls' own commands (#6922): Go to Source Definition opens a library's JavaScript instead
|
||||
/// of its `.d.ts`, Go to Project Configuration and Open TS Server Log answer with
|
||||
/// `window/showDocument`, JSDoc `{@link}` in hovers is a `file://…#L1,1` link, and Move to File
|
||||
/// suggests the project's files and moves a function with its imports in one applied edit. Set
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/[email protected] typescript@6`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vtsls/language-server and typescript@6 (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn vtsls_commands_open_sources_configs_logs_and_move_to_file() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
for dir in ["src", "node_modules/greeting"] {
|
||||
std::fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
let files = [
|
||||
("package.json", "{\"name\":\"app\",\"private\":true}"),
|
||||
("tsconfig.json", "{\"files\":[],\"references\":[{\"path\":\"./src/tsconfig.app.json\"}]}"),
|
||||
(
|
||||
"src/tsconfig.app.json",
|
||||
"{\"compilerOptions\":{\"strict\":true,\"composite\":true,\"module\":\"ESNext\",\"moduleResolution\":\"Bundler\"},\"include\":[\"./**/*.ts\"]}",
|
||||
),
|
||||
(
|
||||
"node_modules/greeting/package.json",
|
||||
"{\"name\":\"greeting\",\"main\":\"index.js\",\"types\":\"index.d.ts\"}",
|
||||
),
|
||||
("node_modules/greeting/index.d.ts", "export declare function shout(s: string): string;\n"),
|
||||
("node_modules/greeting/index.js", "export function shout(s) {\n return s.toUpperCase();\n}\n"),
|
||||
(
|
||||
"src/main.ts",
|
||||
"import { shout } from \"greeting\";\nimport { greet, Greeter } from \"./util\";\n\n/** Uses {@link Greeter} to say hello. */\nexport function hello(name: string) {\n return shout(greet(name));\n}\n\nexport const g = new Greeter();\n",
|
||||
),
|
||||
(
|
||||
"src/util.ts",
|
||||
"export class Greeter {\n greet(name: string) {\n return `Hello, ${name}`;\n }\n}\n\nexport function greet(name: string) {\n return new Greeter().greet(name);\n}\n",
|
||||
),
|
||||
("src/strings.ts", "export const upper = (s: string) => s.toUpperCase();\n"),
|
||||
("src/app.ts", "import { greet } from \"./util\";\n\nconsole.log(greet(\"app\"));\n"),
|
||||
];
|
||||
for (path, text) in files {
|
||||
std::fs::write(root.join(path), text).unwrap();
|
||||
}
|
||||
// The IDE's settings hook: Move to File on, a TypeScript 6 lib, the log on.
|
||||
let init = serde_json::json!({
|
||||
"vtsls": { "enableMoveToFileCodeAction": true, "autoUseWorkspaceTsdk": true },
|
||||
"typescript": {
|
||||
"tsdk": tools.join("node_modules/typescript/lib").to_string_lossy(),
|
||||
"tsserver": { "log": "verbose" },
|
||||
},
|
||||
});
|
||||
let ts = lang("typescript", "ts", npm_server(&tools, "vtsls", "vtsls", Some(init)));
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![ts]));
|
||||
let applied: Arc<Mutex<Vec<ide_core::WorkspaceEdit>>> = Arc::default();
|
||||
mgr.set_apply_edit_hook(Box::new({
|
||||
let applied = applied.clone();
|
||||
move |edit| {
|
||||
applied.lock().push(edit);
|
||||
true
|
||||
}
|
||||
}));
|
||||
let open = |path: &str| {
|
||||
let doc = DocId::next();
|
||||
let file = root.join(path);
|
||||
mgr.did_open(doc, &file, &LanguageId::new("typescript"), 1, &std::fs::read_to_string(&file).unwrap());
|
||||
doc
|
||||
};
|
||||
let (main, util) = (open("src/main.ts"), open("src/util.ts"));
|
||||
|
||||
// `shout`: Go to Declaration is the `.d.ts`, Go to Source Definition the `.js`.
|
||||
let at = Pos::new(0, 10);
|
||||
// The syntax server answers with the import itself until the project is loaded.
|
||||
let dts = |d: &ide_core::Location| d.path.to_string_lossy().ends_with("greeting/index.d.ts");
|
||||
let declaration = retry("declaration", Duration::from_secs(90), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(main, at, GotoKind::Definition).await.ok().filter(|d| d.iter().any(dts)) }
|
||||
})
|
||||
.await;
|
||||
assert!(declaration.iter().all(dts), "{declaration:?}");
|
||||
let source = mgr.source_definition(main, at, Default::default()).await.unwrap();
|
||||
assert_eq!(source.len(), 1, "{source:?}");
|
||||
assert_eq!(*source[0].path, *root.join("node_modules/greeting/index.js"));
|
||||
assert_eq!(source[0].range.start, Pos::new(0, 16));
|
||||
|
||||
let shown = |events: &Events, suffix: &str| {
|
||||
events
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|e| matches!(e, IdeEvent::LspShowDocument { path: Some(path), .. } if path.to_string_lossy().ends_with(suffix)))
|
||||
};
|
||||
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ProjectConfig).await.unwrap();
|
||||
retry("tsconfig.app.json shown", Duration::from_secs(10), || {
|
||||
let found = shown(&events, "src/tsconfig.app.json").then_some(());
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
mgr.open_typescript_file(main, ide_lsp::types::TypeScriptFile::ServerLog).await.unwrap();
|
||||
retry("tsserver.log shown", Duration::from_secs(10), || {
|
||||
let found = shown(&events, "tsserver.log").then_some(());
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
|
||||
let hover = mgr.hover(main, Pos::new(4, 17), Default::default()).await.unwrap();
|
||||
let hover = format!("{hover:?}");
|
||||
assert!(hover.contains("src/util.ts#L1%2C1"), "{hover}");
|
||||
|
||||
// Move to File on `greet`: tsserver suggests the other files, the move updates the importers.
|
||||
let caret = Pos::new(6, 16);
|
||||
let actions = mgr.code_actions(util, Range::new(caret, caret), vec!["refactor.move".into()]).await.unwrap();
|
||||
let command = actions
|
||||
.iter()
|
||||
.find_map(|a| a.command.clone().filter(|c| c.command == "_typescript.moveToFileRefactoring"))
|
||||
.unwrap_or_else(|| panic!("no Move to File: {actions:?}"));
|
||||
let targets = mgr.move_to_file_targets(util, command.clone(), Default::default()).await.unwrap();
|
||||
let strings = root.join("src/strings.ts");
|
||||
assert!(targets.contains(&strings) && targets.contains(&root.join("src/app.ts")), "{targets:?}");
|
||||
let mut moving = command;
|
||||
moving.arguments.push(serde_json::json!(strings));
|
||||
mgr.execute_command(util, moving).await.unwrap();
|
||||
let edits = applied.lock().clone();
|
||||
assert_eq!(edits.len(), 1, "{edits:?}");
|
||||
let edit = format!("{:?}", edits[0]);
|
||||
for file in ["src/util.ts", "src/strings.ts", "src/app.ts", "src/main.ts"] {
|
||||
assert!(edit.contains(&*root.join(file).to_string_lossy()), "{file}: {edit}");
|
||||
}
|
||||
assert!(edit.contains("export function greet(name: string)"), "{edit}");
|
||||
assert!(edit.contains("import { greet } from \\\"./strings\\\""), "{edit}");
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// CSS Modules Kit (`@css-modules-kit/ts-plugin`) on vtsls, which serves the `.module.css`
|
||||
/// files too (`languages: ["css"]`): definition and completion from TSX, references and rename
|
||||
/// from the stylesheet (#6071), with the settings hook's own plugin configuration. Exactly the
|
||||
@@ -1082,6 +1211,83 @@ async fn css_modules_kit_navigates_between_tsx_and_module_css() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `@styled/typescript-styled-plugin` on vtsls: CSS diagnostics, completion and hover inside
|
||||
/// styled-components and emotion templates (#6900), with the settings hook's own plugin
|
||||
/// configuration. A tsconfig that declares the plugin too still gets one copy: each
|
||||
/// diagnostic shows once. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with
|
||||
/// `npm i @vtsls/language-server typescript@6 @styled/[email protected]`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vtsls/language-server and @styled/typescript-styled-plugin (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn styled_plugin_checks_and_completes_css_in_templates() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
// (library, its import and tag, the tsconfig declares the plugin)
|
||||
let cases = [
|
||||
("styled-components", "import styled from 'styled-components';", "styled.div", false),
|
||||
("@emotion/styled", "import styled from '@emotion/styled';", "styled.div", true),
|
||||
("@emotion/react", "import { css } from '@emotion/react';", "css", false),
|
||||
];
|
||||
for (library, import, tag, declared) in cases {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::write(root.join("package.json"), format!(r#"{{"name":"app","dependencies":{{"{library}":"*"}}}}"#))
|
||||
.unwrap();
|
||||
let plugins = if declared { r#", "plugins": [{ "name": "@styled/typescript-styled-plugin" }]"# } else { "" };
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
format!(r#"{{ "compilerOptions": {{ "strict": true, "module": "ESNext", "moduleResolution": "Bundler"{plugins} }}, "include": ["src"] }}"#),
|
||||
)
|
||||
.unwrap();
|
||||
// The library itself isn't installed: the plugin goes by the tag name.
|
||||
let types = "declare module 'styled-components' { const styled: any; export default styled; }\n\
|
||||
declare module '@emotion/styled' { const styled: any; export default styled; }\n\
|
||||
declare module '@emotion/react' { export const css: any; }\n";
|
||||
std::fs::write(root.join("src/libs.d.ts"), types).unwrap();
|
||||
let path = root.join("src/box.ts");
|
||||
let text = format!("{import}\nexport const box = {tag}`\n color: blue;\n colr: red;\n justify-con\n`;\n");
|
||||
std::fs::write(&path, &text).unwrap();
|
||||
let mut vtsls = npm_server(&tools, "vtsls", "vtsls", None);
|
||||
vtsls.tsserver_project = true;
|
||||
assert!(ide_sdk::apply::configure_styled(&mut vtsls, &root, Some(&tools)));
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
assert!(!ide_sdk::apply::configure_tsconfig_plugins(&mut vtsls, &root, data.path()));
|
||||
let registry = LanguageRegistry::from_configs(vec![lang("typescript", "ts", vtsls)]);
|
||||
let (mgr, events) = manager(&root, registry);
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &LanguageId::new("typescript"), 1, &text);
|
||||
let case = format!("{library}, declared: {declared}");
|
||||
|
||||
let unknown = retry("unknown property diagnostic", Duration::from_secs(90), || {
|
||||
let found = events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path: p, items, .. } if p == &path => Some(
|
||||
items.iter().filter(|d| d.message.contains("Unknown property: 'colr'")).map(|d| d.range).collect(),
|
||||
),
|
||||
_ => None,
|
||||
});
|
||||
async move { found.filter(|v: &Vec<_>| !v.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(unknown.len(), 1, "{case}: one copy of the plugin, {unknown:?}");
|
||||
assert_eq!(unknown[0].start.line, 3, "{case}");
|
||||
let list = retry("CSS property completion", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move {
|
||||
let list = mgr.completion(doc, Pos::new(4, 13), None, Default::default()).await.ok()?;
|
||||
list.items.iter().any(|i| i.label == "justify-content").then_some(list)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert!(list.items.iter().any(|i| i.label == "justify-items"), "{case}");
|
||||
let hover = retry("CSS property hover", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.hover(doc, Pos::new(2, 4), Default::default()).await.ok().flatten() }
|
||||
})
|
||||
.await;
|
||||
assert!(hover.contents.value.to_lowercase().contains("color"), "{case}: {}", hover.contents.value);
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
const MDX_BUTTON: &str =
|
||||
"export function Button(props: { label: string }) {\n return <button>{props.label}</button>;\n}\n";
|
||||
const MDX_DOC: &str = "import { Button } from \"./Button\"\n\nexport const count = 2\n\n# Hello\n\n<Button label=\"hi\" />\n\n<Button label={count} />\n\n{count.toFixed()}\n";
|
||||
|
||||
@@ -67,9 +67,10 @@ pub trait ToolRegistry: Send + Sync + 'static {
|
||||
/// Roots of the projects open in a window of the IDE that the server serves.
|
||||
fn projects(&self) -> Vec<PathBuf>;
|
||||
/// The root of the project the IDE serves `path` from without a window (a background
|
||||
/// project), asked when no project of [`Self::projects`] contains `path`. Opens nothing:
|
||||
/// the first call for that root does.
|
||||
fn resolve(&self, _path: &Path) -> Option<PathBuf> {
|
||||
/// project). `within` is the root of the innermost project of [`Self::projects`] that
|
||||
/// contains `path`, when one does: then only a root strictly inside it answers, and the
|
||||
/// open project keeps the path otherwise. Opens nothing: the first call for that root does.
|
||||
fn resolve(&self, _path: &Path, _within: Option<&Path>) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
/// The tools callable for `project` (one of [`Self::projects`] or a root
|
||||
|
||||
@@ -223,9 +223,7 @@ impl Session<'_> {
|
||||
roots.sort();
|
||||
roots.dedup();
|
||||
if let Some(requested) = requested.filter(|p| !p.trim().is_empty()) {
|
||||
let path = Path::new(requested);
|
||||
// An open project wins; the registry is asked only for a folder outside all of them.
|
||||
return resolve(&roots, path).or_else(|| self.registry.resolve(path)).ok_or_else(|| {
|
||||
return self.serving_root(&roots, Path::new(requested)).ok_or_else(|| {
|
||||
RpcError::new(
|
||||
NOT_OPEN,
|
||||
format!(
|
||||
@@ -247,10 +245,30 @@ impl Session<'_> {
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
/// The innermost project containing `path`, whether a window has it open (one of `roots`)
|
||||
/// or the registry serves it in the background, so the answer doesn't depend on which
|
||||
/// windows are open. Inside an open project the registry is asked only for a path below
|
||||
/// its root, about the folders inside that root: a folder of a window's project that no
|
||||
/// nested project holds loads nothing.
|
||||
fn serving_root(&self, roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
|
||||
let Some(open) = resolve(roots, path) else { return self.registry.resolve(path, None) };
|
||||
let nested = if open.below { self.registry.resolve(path, Some(&open.root)) } else { None };
|
||||
Some(nested.unwrap_or(open.root))
|
||||
}
|
||||
}
|
||||
|
||||
/// The innermost open project containing a path.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct OpenRoot {
|
||||
/// As the registry lists it.
|
||||
root: PathBuf,
|
||||
/// Whether the path lies below the root rather than at it.
|
||||
below: bool,
|
||||
}
|
||||
|
||||
/// The project among `roots` containing `path` (the innermost one).
|
||||
fn resolve(roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
|
||||
fn resolve(roots: &[PathBuf], path: &Path) -> Option<OpenRoot> {
|
||||
if !path.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
@@ -274,7 +292,7 @@ fn resolve(roots: &[PathBuf], path: &Path) -> Option<PathBuf> {
|
||||
path.starts_with(&canonical).then(|| (canonical.components().count(), root))
|
||||
})
|
||||
.max_by_key(|(depth, _)| *depth)
|
||||
.map(|(_, root)| root.clone())
|
||||
.map(|(depth, root)| OpenRoot { root: root.clone(), below: path.components().count() > depth })
|
||||
}
|
||||
|
||||
fn tool_json(tool: &Tool) -> Value {
|
||||
@@ -299,11 +317,15 @@ mod tests {
|
||||
let inner = outer.join("inner");
|
||||
std::fs::create_dir_all(inner.join("src")).unwrap();
|
||||
let roots = [outer.clone(), inner.clone()];
|
||||
assert_eq!(resolve(&roots, &inner.join("src")), Some(inner.clone()));
|
||||
assert_eq!(resolve(&roots, &outer.join("other")), Some(outer.clone()));
|
||||
assert_eq!(resolve(&roots[1..], &outer), None);
|
||||
assert_eq!(resolve(&roots, Path::new("relative/path")), None);
|
||||
let root = |roots: &[PathBuf], path: &Path| resolve(roots, path).map(|open| open.root);
|
||||
assert_eq!(root(&roots, &inner.join("src")), Some(inner.clone()));
|
||||
assert_eq!(root(&roots, &outer.join("other")), Some(outer.clone()));
|
||||
assert_eq!(root(&roots[1..], &outer), None);
|
||||
assert_eq!(root(&roots, Path::new("relative/path")), None);
|
||||
// Siblings sharing a prefix are not inside.
|
||||
assert_eq!(resolve(&roots[1..], &outer.join("inner-two")), None);
|
||||
assert_eq!(root(&roots[1..], &outer.join("inner-two")), None);
|
||||
// Only a path below the root is below it.
|
||||
assert_eq!(resolve(&roots, &inner), Some(OpenRoot { root: inner.clone(), below: false }));
|
||||
assert_eq!(resolve(&roots, &inner.join("src")), Some(OpenRoot { root: inner.clone(), below: true }));
|
||||
}
|
||||
}
|
||||
@@ -225,18 +225,22 @@ async fn folders_that_are_not_open_are_named_in_the_error() {
|
||||
assert!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"].is_array());
|
||||
}
|
||||
|
||||
/// One project open in a window and, optionally, one folder served without a window.
|
||||
/// One project open in a window and the folders served without a window.
|
||||
struct WithBackground {
|
||||
open: PathBuf,
|
||||
background: Option<PathBuf>,
|
||||
background: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl ToolRegistry for WithBackground {
|
||||
fn projects(&self) -> Vec<PathBuf> {
|
||||
vec![self.open.clone()]
|
||||
}
|
||||
fn resolve(&self, path: &Path) -> Option<PathBuf> {
|
||||
self.background.clone().filter(|root| path.starts_with(root))
|
||||
/// The innermost served folder containing `path`, strictly inside `within`, as the
|
||||
/// background policy answers.
|
||||
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||||
let inside = |root: &&PathBuf| within.is_none_or(|open| root.starts_with(open) && *root != open);
|
||||
let served = self.background.iter().filter(|root| path.starts_with(root)).filter(inside);
|
||||
served.max_by_key(|root| root.components().count()).cloned()
|
||||
}
|
||||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
|
||||
Ok(vec![Tool {
|
||||
@@ -253,13 +257,16 @@ impl ToolRegistry for WithBackground {
|
||||
}
|
||||
}
|
||||
|
||||
/// The server over [`WithBackground`]; the folder `inventory` next to the open project.
|
||||
fn setup_with_background(served: bool) -> (Setup, PathBuf) {
|
||||
/// The server over [`WithBackground`] serving the `served` folders, relative to the folder
|
||||
/// that holds the open project; the folder `inventory` next to the open project.
|
||||
fn setup_with_background(served: &[&str]) -> (Setup, PathBuf) {
|
||||
let mut s = setup();
|
||||
s.server.take().unwrap().stop();
|
||||
let inventory = s.project.parent().unwrap().join("inventory");
|
||||
let base = s.project.parent().unwrap().to_path_buf();
|
||||
let inventory = base.join("inventory");
|
||||
std::fs::create_dir_all(inventory.join("src")).unwrap();
|
||||
let registry = WithBackground { open: s.project.clone(), background: served.then(|| inventory.clone()) };
|
||||
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
|
||||
let registry = WithBackground { open: s.project.clone(), background };
|
||||
s.server = Some(
|
||||
McpServer::start_with(Arc::new(registry), None, &tokio::runtime::Handle::current(), ServerOptions::default())
|
||||
.unwrap(),
|
||||
@@ -277,7 +284,7 @@ async fn rpc_for(s: &Setup, folder: &Path, method: &str, params: Value) -> Value
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||||
let (s, inventory) = setup_with_background(true);
|
||||
let (s, inventory) = setup_with_background(&["inventory"]);
|
||||
let inside = inventory.join("src");
|
||||
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
@@ -296,9 +303,37 @@ async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||||
assert_eq!(open["result"]["structuredContent"]["project"], json!(s.project), "{open}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_innermost_project_answers_whether_a_window_has_it_open_or_it_is_served_in_the_background() {
|
||||
// The layout of #7040: a window on `project` and `contracts` inside it served in the
|
||||
// background. The policy serves the window's root and the folder around it as well, as
|
||||
// trusted projects and listed folders do.
|
||||
let (s, _) = setup_with_background(&["", "project", "project/contracts"]);
|
||||
let contracts = s.project.join("contracts");
|
||||
std::fs::create_dir_all(contracts.join("src")).unwrap();
|
||||
let base = s.project.parent().unwrap().to_path_buf();
|
||||
for (folder, served) in [
|
||||
(contracts.join("src"), &contracts),
|
||||
(contracts.clone(), &contracts),
|
||||
// Folders of the window's project that no nested project holds stay with the window.
|
||||
(s.project.join("src"), &s.project),
|
||||
(s.project.clone(), &s.project),
|
||||
(base.join("elsewhere"), &base),
|
||||
] {
|
||||
let at = folder.display();
|
||||
let call = rpc(&s, "tools/call", json!({ "name": "where", "arguments": { "projectPath": folder } })).await;
|
||||
assert_eq!(call["result"]["structuredContent"]["project"], json!(served), "{at}: {call}");
|
||||
let list = rpc_for(&s, &folder, "tools/list", json!({})).await;
|
||||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", served.display()), "{at}: {list}");
|
||||
let init = rpc_for(&s, &folder, "initialize", json!({})).await;
|
||||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.contains(&format!("serves at {}:", served.display())), "{at}: {instructions}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
|
||||
let (s, inventory) = setup_with_background(false);
|
||||
let (s, inventory) = setup_with_background(&[]);
|
||||
for (method, params) in [("tools/list", json!({})), ("tools/call", json!({ "name": "where" }))] {
|
||||
let reply = rpc_for(&s, &inventory, method, params).await;
|
||||
assert_eq!(reply["error"]["code"], -32001, "{method}: {reply}");
|
||||
|
||||
@@ -613,11 +613,14 @@ impl PluginEngine {
|
||||
pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result<Component, String> {
|
||||
let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?;
|
||||
let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes)));
|
||||
if file.is_file() {
|
||||
// Read into memory rather than `deserialize_file`: that maps the file and makes its pages
|
||||
// executable, which the hardened runtime of the signed macOS app refuses ("failed to make
|
||||
// memory executable"), so the cache never hit and every activation compiled again.
|
||||
if let Ok(precompiled) = std::fs::read(&file) {
|
||||
// SAFETY: the cache directory belongs to the IDE (inside its plugins
|
||||
// directory) and is written only by `store_precompiled` below from
|
||||
// components this engine compiled; a corrupt file fails validation.
|
||||
match unsafe { Component::deserialize_file(&self.engine, &file) } {
|
||||
match unsafe { Component::deserialize(&self.engine, &precompiled) } {
|
||||
Ok(component) => return Ok(component),
|
||||
Err(e) => {
|
||||
tracing::info!("discarding precompiled {}: {e}", file.display());
|
||||
@@ -3035,6 +3038,26 @@ impl Runtime {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The second compile of the same component loads the cached one instead of compiling and
|
||||
/// writing it again (a failed load deletes and rewrites the file).
|
||||
#[test]
|
||||
fn a_precompiled_component_is_loaded_from_the_cache() {
|
||||
let engine = PluginEngine::new().unwrap();
|
||||
let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm");
|
||||
let cache = tempfile::tempdir().unwrap();
|
||||
engine.compile_cached(&wasm, cache.path()).unwrap();
|
||||
let cached = || {
|
||||
let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect();
|
||||
assert_eq!(entries.len(), 1, "{entries:?}");
|
||||
let file = entries[0].clone();
|
||||
(std::fs::metadata(&file).unwrap().modified().unwrap(), file)
|
||||
};
|
||||
let before = cached();
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
engine.compile_cached(&wasm, cache.path()).unwrap();
|
||||
assert_eq!(cached(), before, "loaded, not compiled and stored again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() {
|
||||
let fields = [
|
||||
|
||||
@@ -33,12 +33,13 @@ pub struct ContainerRun<'a> {
|
||||
pub name: &'a str,
|
||||
/// `--user uid:gid`; `None` keeps the image's user.
|
||||
pub user: Option<(u32, u32)>,
|
||||
/// Runs the Python program under debugpy, for the debugger to attach.
|
||||
/// Runs the program for the debugger to attach: Python under debugpy, Node.js (a `js-debug`
|
||||
/// configuration) with its inspector waiting.
|
||||
pub debug: Option<ContainerDebug<'a>>,
|
||||
}
|
||||
|
||||
/// A debug run: the program starts under [`DEBUG_BOOTSTRAP`], which waits for the
|
||||
/// debugger on `port` (published on this machine's loopback interface only).
|
||||
/// A debug run: the program starts under [`DEBUG_BOOTSTRAP`] (Node.js: with `--inspect-brk`),
|
||||
/// which waits for the debugger on `port` (published on this machine's loopback interface only).
|
||||
pub struct ContainerDebug<'a> {
|
||||
pub port: u16,
|
||||
/// Folder on this machine holding [`DEBUG_BOOTSTRAP`] as [`DEBUG_BOOTSTRAP_NAME`].
|
||||
@@ -57,6 +58,14 @@ const DEBUG_DIR: &str = "/opt/openidea/debug";
|
||||
const DEBUGPY_DIR: &str = "/opt/openidea/debugpy-lib";
|
||||
/// Start of the line the bootstrap prints when the debugger can attach.
|
||||
pub const DEBUG_READY: &str = "debugpy is waiting for the debugger on port ";
|
||||
/// Start of the line printed before a Node.js program starts for debugging on a run target,
|
||||
/// followed by the project folder there. Node prints `Debugger listening on ws://…` itself.
|
||||
pub const NODE_DEBUG_FOLDER: &str = "Starting Node.js for the debugger, project folder ";
|
||||
|
||||
/// Whether a debug run of `config` starts Node.js with its inspector rather than debugpy.
|
||||
pub fn node_debug(config: &RunConfig) -> bool {
|
||||
config.debug_adapter.as_deref() == Some("js-debug")
|
||||
}
|
||||
|
||||
/// The container folder of the project when a Docker target sets none.
|
||||
pub fn default_container_root(root: &Path) -> String {
|
||||
@@ -243,9 +252,12 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
if let Some((uid, gid)) = run.user {
|
||||
args.extend(["--user".into(), format!("{uid}:{gid}")]);
|
||||
}
|
||||
let node = node_debug(config);
|
||||
if let Some(debug) = &run.debug {
|
||||
let port = debug.port;
|
||||
args.extend(["--publish".into(), format!("127.0.0.1:{port}:{port}")]);
|
||||
}
|
||||
if let Some(debug) = run.debug.as_ref().filter(|_| !node) {
|
||||
args.extend(["--volume".into(), format!("{}:{DEBUG_DIR}:ro", debug.bootstrap_dir.to_string_lossy())]);
|
||||
if let Some(lib) = debug.debugpy {
|
||||
args.extend(["--volume".into(), format!("{}:{DEBUGPY_DIR}:ro", lib.to_string_lossy())]);
|
||||
@@ -262,11 +274,15 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
match (command.shell_line, &run.debug) {
|
||||
(Some(_), Some(_)) => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' is a shell command line: only a Python script, module or console script can be debugged in a container. Set Command to the Python executable and put the script or -m module in Arguments",
|
||||
"'{}' is a shell command line: only a Python or Node.js program can be debugged in a container. Set Command to the Python or Node.js executable and put the script in Arguments",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
|
||||
// Inside the container the inspector listens on every interface, for the published port.
|
||||
(None, Some(debug)) if node => {
|
||||
args.extend(node_debug_command(&command.program, &command.args, "0.0.0.0", debug.port)?)
|
||||
}
|
||||
(None, Some(debug)) => {
|
||||
let bootstrap = format!("{DEBUG_DIR}/{DEBUG_BOOTSTRAP_NAME}");
|
||||
args.extend(debug_command(
|
||||
@@ -347,6 +363,43 @@ fn is_python(program: &str) -> bool {
|
||||
name == "python" || name == "python2" || name.starts_with("python3")
|
||||
}
|
||||
|
||||
/// Why tsx can't be debugged on a run target yet: js-debug's attach never lets the program start
|
||||
/// past tsx's loader worker.
|
||||
const TSX_UNSUPPORTED: &str = "tsx can't be debugged on a run target yet: the program does not start once the debugger attaches. For TypeScript, set the Node interpreter to node and add --experimental-strip-types to the Node options";
|
||||
|
||||
/// `program args` (a Node.js command on a run target) with the inspector waiting for the debugger
|
||||
/// on `host:port`: `--inspect-brk` goes right after `node`, so the configuration's Node options keep
|
||||
/// applying.
|
||||
pub(crate) fn node_debug_command(program: &str, args: &[String], host: &str, port: u16) -> IdeResult<Vec<String>> {
|
||||
let name = |s: &str| s.rsplit(['/', '\\']).next().unwrap_or(s).trim_end_matches(".exe").to_owned();
|
||||
// `node --import tsx` registers the same loader worker (`--loader tsx` fails on its own).
|
||||
let tsx_import = |value: &str| value == "tsx" || value.starts_with("tsx/") || value.contains("/tsx/");
|
||||
let mut imports_tsx = false;
|
||||
let mut i = 0;
|
||||
while let Some(a) = args.get(i).filter(|a| a.starts_with('-')) {
|
||||
if a == "--import" {
|
||||
imports_tsx |= args.get(i + 1).is_some_and(|v| tsx_import(v));
|
||||
i += 1;
|
||||
}
|
||||
imports_tsx |= a.strip_prefix("--import=").is_some_and(tsx_import);
|
||||
i += 1;
|
||||
}
|
||||
match name(program).as_str() {
|
||||
"node" if imports_tsx => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
|
||||
"node" => {}
|
||||
"tsx" => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
|
||||
"npx" if args.first().is_some_and(|a| a == "tsx") => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
|
||||
_ => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"`{program}` can't be debugged on a run target: set the Node interpreter to node"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut line = vec![program.to_owned(), format!("--inspect-brk={host}:{port}")];
|
||||
line.extend(args.iter().cloned());
|
||||
Ok(line)
|
||||
}
|
||||
|
||||
/// The command line that runs `program args` under [`DEBUG_BOOTSTRAP`] (at `bootstrap` in the
|
||||
/// container or on the SSH host): `python [options] <bootstrap> <port> <folder> (script | -m module | -c code) args`.
|
||||
/// A console script (`pytest`) runs as a module of the interpreter next to it, or of the
|
||||
@@ -741,6 +794,52 @@ mod tests {
|
||||
assert!(args.contains("openidea/debug:ro python:3.12") && !args.contains("debugpy-lib"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn debug_starts_node_with_the_inspector_on_the_published_port() {
|
||||
let target = RunTarget { kind: RunTargetKind::Docker, image: "node:22".into(), ..Default::default() };
|
||||
let line = |command: &str, args: &[&str]| {
|
||||
let c = RunConfig { debug_adapter: Some("js-debug".into()), ..config(command, args) };
|
||||
let args = debugged(&target, &c).unwrap().join(" ");
|
||||
assert!(args.contains("--publish 127.0.0.1:41234:41234 node:22"), "{args}");
|
||||
assert!(!args.contains("openidea/debug"), "no bootstrap for Node.js: {args}");
|
||||
args.split_once("node:22 ").unwrap().1.to_owned()
|
||||
};
|
||||
let inspect = "--inspect-brk=0.0.0.0:41234";
|
||||
assert_eq!(
|
||||
line("/usr/local/bin/node", &["--env-file=.env", "/work/proj/main.js", "a"]),
|
||||
format!("node {inspect} --env-file=.env /workspaces/proj/main.js a"),
|
||||
"the configuration's Node options stay"
|
||||
);
|
||||
assert_eq!(
|
||||
line("node", &["--import", "./setup.mjs", "main.js", "--import", "tsx"]),
|
||||
format!("node {inspect} --import ./setup.mjs main.js --import tsx"),
|
||||
"other imports, and the program's own arguments, don't count"
|
||||
);
|
||||
assert_eq!(
|
||||
line("node", &["--experimental-strip-types", "main.ts"]),
|
||||
format!("node {inspect} --experimental-strip-types main.ts")
|
||||
);
|
||||
// tsx hangs once js-debug attaches: refused, pointing to type stripping.
|
||||
for (command, args, error) in [
|
||||
("/work/proj/node_modules/.bin/tsx", &["main.ts"][..], "--experimental-strip-types"),
|
||||
("npx", &["tsx", "main.ts"][..], "tsx can't be debugged"),
|
||||
("node", &["--import", "tsx", "main.ts"][..], "tsx can't be debugged"),
|
||||
("node", &["--import=tsx/esm", "main.ts"][..], "tsx can't be debugged"),
|
||||
(
|
||||
"node",
|
||||
&["--env-file=.env", "--import", "/opt/lib/node_modules/tsx/dist/loader.mjs", "main.ts"][..],
|
||||
"tsx",
|
||||
),
|
||||
("npm", &["run", "dev"][..], "set the Node interpreter to node"),
|
||||
("node main.js", &[][..], "shell command line"),
|
||||
] {
|
||||
let c = RunConfig { debug_adapter: Some("js-debug".into()), ..config(command, args) };
|
||||
let err = debugged(&target, &c).unwrap_err();
|
||||
assert!(err.message.contains(error), "{command}: {}", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_files_printed_in_the_container_through_the_longest_mount() {
|
||||
let root = Path::new("project");
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, Tran
|
||||
use crate::mapping::{Excludes, Mappings, ResolvedMapping, posix};
|
||||
use crate::target::{
|
||||
DEBUG_PARAM, PROBE_NO_FOLDER, RemoteDebug, RemoteRuns, RemoteStart, SyncFn, debug_interpreter, debugpy_probe,
|
||||
remote_command, rewrite_external_classpath, ssh_debug_command,
|
||||
remote_command, rewrite_external_classpath, ssh_debug_command, ssh_node_debug_command,
|
||||
};
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentServer, DeploymentType, RunTarget};
|
||||
use ide_core::settings::Settings;
|
||||
@@ -605,14 +605,21 @@ async fn prepare_debug(
|
||||
remote_root: &str,
|
||||
debugpy_lib: Option<&Path>,
|
||||
) -> IdeResult<(RemoteDebug, Option<SyncFn>)> {
|
||||
if config.debug_adapter.as_deref() != Some("debugpy") {
|
||||
let node = crate::docker::node_debug(config);
|
||||
if config.debug_adapter.as_deref() != Some("debugpy") && !node {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' can't be debugged on an SSH run target: only Python run configurations can",
|
||||
"'{}' can't be debugged on an SSH run target: only Python and Node.js run configurations can",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
let dir = join(&fs.home().await?, DEBUG_FOLDER);
|
||||
let port = std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port();
|
||||
if node {
|
||||
let command = ssh_node_debug_command(&remote_command(config, target, root, remote_root), port)?;
|
||||
let tunnel = forward(session, port).await?;
|
||||
let note = Some(format!("{}{remote_root}", crate::docker::NODE_DEBUG_FOLDER));
|
||||
return Ok((RemoteDebug { command, tunnel, note }, None));
|
||||
}
|
||||
let dir = join(&fs.home().await?, DEBUG_FOLDER);
|
||||
// Unique among this machine's debug runs; other machines' runs use other temporary names too.
|
||||
let temp = |path: &str| format!("{path}.{}-{port}.tmp", std::process::id());
|
||||
// Named after its content and never rewritten: a concurrent run may be reading it.
|
||||
@@ -671,13 +678,19 @@ async fn prepare_debug(
|
||||
}));
|
||||
}
|
||||
}
|
||||
let tunnel = forward(session, port).await?;
|
||||
Ok((RemoteDebug { command, tunnel, note: None }, upload))
|
||||
}
|
||||
|
||||
/// Forwards local `port` to the same port on the host's loopback interface.
|
||||
async fn forward(session: &Arc<ide_ssh::Session>, port: u16) -> IdeResult<ide_ssh::Tunnel> {
|
||||
let tunnel = ide_ssh::Tunnel::listen_on(session.clone(), Some(port), "127.0.0.1", port).await?;
|
||||
if tunnel.port() != port {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"local port {port} for the debugger was taken meanwhile; try again"
|
||||
)));
|
||||
}
|
||||
Ok((RemoteDebug { command, tunnel }, upload))
|
||||
Ok(tunnel)
|
||||
}
|
||||
|
||||
/// Uploads outside-root classpath entries to their mirrored remote copies,
|
||||
|
||||
@@ -153,6 +153,18 @@ pub fn ssh_debug_command(
|
||||
})
|
||||
}
|
||||
|
||||
/// `command` (an SSH target's Node.js command) with the inspector waiting on the host's loopback
|
||||
/// `port`, which the IDE reaches through an SSH forward.
|
||||
pub fn ssh_node_debug_command(command: &RemoteCommand, port: u16) -> IdeResult<RemoteCommand> {
|
||||
if command.shell_line.is_some() {
|
||||
return Err(IdeError::invalid(
|
||||
"a shell command line can't be debugged on a run target: set the Node interpreter to node and the JavaScript file to the script",
|
||||
));
|
||||
}
|
||||
let line = crate::docker::node_debug_command(&command.program, &command.args, "127.0.0.1", port)?;
|
||||
Ok(RemoteCommand { program: line[0].clone(), args: line[1..].to_vec(), shell_line: None, ..command.clone() })
|
||||
}
|
||||
|
||||
/// The interpreter of an [`ssh_debug_command`] (with its options, or behind `uv run`).
|
||||
pub fn debug_interpreter(debug: &RemoteCommand, bootstrap: &str) -> RemoteCommand {
|
||||
let end = debug.args.iter().position(|a| a == bootstrap).unwrap_or(debug.args.len());
|
||||
@@ -358,6 +370,8 @@ pub struct RemoteStart {
|
||||
pub struct RemoteDebug {
|
||||
pub command: RemoteCommand,
|
||||
pub tunnel: ide_ssh::Tunnel,
|
||||
/// Printed right before the program starts (`docker::NODE_DEBUG_FOLDER`).
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
impl RemoteRuns {
|
||||
@@ -485,6 +499,9 @@ async fn run_remote(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
on_output(OutputChunk::System { text: format!("{}\n", command.display()) });
|
||||
if let Some(note) = start.debug.as_ref().and_then(|d| d.note.as_ref()) {
|
||||
on_output(OutputChunk::System { text: format!("{note}\n") });
|
||||
}
|
||||
let out = on_output.clone();
|
||||
let process = start
|
||||
.session
|
||||
@@ -556,6 +573,26 @@ mod tests {
|
||||
assert_eq!(c.program, "make");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn debugs_node_on_an_ssh_host_through_its_loopback_port() {
|
||||
let target = RunTarget { node: "/opt/node/bin/node".into(), ..Default::default() };
|
||||
let plain = remote_command(
|
||||
&config("/usr/local/bin/node", &["--enable-source-maps", "/work/proj/src/main.js"], None),
|
||||
&target,
|
||||
Path::new("/work/proj"),
|
||||
"/home/me/proj",
|
||||
);
|
||||
let debug = ssh_node_debug_command(&plain, 50123).unwrap();
|
||||
assert_eq!(debug.program, "/opt/node/bin/node");
|
||||
assert_eq!(debug.args, ["--inspect-brk=127.0.0.1:50123", "--enable-source-maps", "/home/me/proj/src/main.js"]);
|
||||
assert_eq!((debug.cwd.as_str(), &debug.env), (plain.cwd.as_str(), &plain.env));
|
||||
let tsx = RemoteCommand { program: "tsx".into(), ..plain.clone() };
|
||||
assert!(ssh_node_debug_command(&tsx, 50123).unwrap_err().message.contains("--experimental-strip-types"));
|
||||
let shell = RemoteCommand { shell_line: Some("node main.js".into()), ..plain };
|
||||
assert!(ssh_node_debug_command(&shell, 50123).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn debugs_python_on_an_ssh_host_through_its_loopback_port() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Swift packages (`Package.swift`): one `swift run <product>` per executable product, built
|
||||
//! first by `swift build --product <product>` and debuggable with lldb-dap on the built
|
||||
//! `.build/debug/<product>`. Read from the manifest's source: `swift package describe` would
|
||||
//! product (found by `swift build --show-bin-path` when debugging). Read from the manifest's source: `swift package describe` would
|
||||
//! compile and run the manifest, and detection never runs the project's build code.
|
||||
|
||||
use super::zig::{call_body, code_only, string_at};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Xcode schemes: one configuration per scheme that builds its app and runs it on the iOS
|
||||
//! Simulator (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
|
||||
//! so its schemes and theirs are built through it.
|
||||
//! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
|
||||
//! so its schemes and theirs are built through it, as is the workspace of a CocoaPods project.
|
||||
|
||||
use super::{ConfigExt, config};
|
||||
use crate::RunConfig;
|
||||
@@ -8,10 +8,12 @@ use crate::xcode::{XcodeScheme, schemes};
|
||||
use std::path::Path;
|
||||
|
||||
/// A folder holding an Xcode project or workspace, other than the `ios/` / `macos/` host app
|
||||
/// of a Flutter or React Native project, which that project's own tooling runs.
|
||||
/// of a Flutter or React Native project, which that project's own tooling runs, and a CocoaPods
|
||||
/// `Pods/` folder.
|
||||
pub(super) fn is_project(dir: &Path) -> bool {
|
||||
let hosted = dir.parent().is_some_and(|p| p.join("pubspec.yaml").is_file() || p.join("package.json").is_file());
|
||||
!hosted
|
||||
&& !crate::xcode::is_pods_dir(dir)
|
||||
&& std::fs::read_dir(dir).is_ok_and(|entries| {
|
||||
entries.flatten().any(|e| e.path().extension().is_some_and(|x| x == "xcodeproj" || x == "xcworkspace"))
|
||||
})
|
||||
@@ -19,9 +21,13 @@ pub(super) fn is_project(dir: &Path) -> bool {
|
||||
|
||||
pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let found = schemes(dir);
|
||||
let workspace = found.iter().map(|s| &s.container).find(|c| c.extension().is_some_and(|x| x == "xcworkspace"));
|
||||
let workspace = found
|
||||
.iter()
|
||||
.map(|s| s.container.clone())
|
||||
.find(|c| c.extension().is_some_and(|x| x == "xcworkspace"))
|
||||
.or_else(|| crate::xcode::pods_workspace(dir));
|
||||
for scheme in &found {
|
||||
let container = workspace.unwrap_or(&scheme.container);
|
||||
let container = workspace.as_ref().unwrap_or(&scheme.container);
|
||||
let container = container.strip_prefix(dir).unwrap_or(container).to_string_lossy().into_owned();
|
||||
out.push(scheme_config(scheme, &container));
|
||||
}
|
||||
@@ -77,4 +83,49 @@ mod tests {
|
||||
assert_eq!(app.env["API_HOST"], "localhost:8080");
|
||||
assert!(!app.extras.params.contains_key(crate::xcode::SIMULATOR_PARAM));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cocoapods_project_builds_and_tests_through_its_workspace() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let scheme = std::fs::read_to_string(
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme"),
|
||||
)
|
||||
.unwrap();
|
||||
for dir in ["App.xcodeproj", "Pods/Pods.xcodeproj"] {
|
||||
let schemes = root.join(dir).join("xcshareddata/xcschemes");
|
||||
std::fs::create_dir_all(&schemes).unwrap();
|
||||
std::fs::write(schemes.join("App.xcscheme"), &scheme).unwrap();
|
||||
}
|
||||
// `pod install`'s workspace has no schemes of its own.
|
||||
std::fs::create_dir(root.join("App.xcworkspace")).unwrap();
|
||||
|
||||
let args = |out: &[RunConfig]| out.iter().map(|c| c.args.join(" ")).collect::<Vec<_>>();
|
||||
let mut out = Vec::new();
|
||||
detect(root, &mut out);
|
||||
assert_eq!(args(&out), ["-project App.xcodeproj -scheme App -configuration Staging"]);
|
||||
// Without a Podfile, a `Pods/` folder is just another project.
|
||||
assert!(is_project(&root.join("Pods")));
|
||||
|
||||
std::fs::write(root.join("Podfile"), "").unwrap();
|
||||
assert!(is_project(root) && !is_project(&root.join("Pods")));
|
||||
let mut out = Vec::new();
|
||||
detect(root, &mut out);
|
||||
assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
|
||||
let mut tests = Vec::new();
|
||||
super::super::xcode_test::detect(root, &mut tests);
|
||||
assert_eq!(args(&tests), ["test -workspace App.xcworkspace -scheme App"]);
|
||||
|
||||
// A leftover workspace that sorts first: the one named after the project still wins.
|
||||
std::fs::create_dir(root.join("Aardvark.xcworkspace")).unwrap();
|
||||
let mut out = Vec::new();
|
||||
detect(root, &mut out);
|
||||
assert_eq!(args(&out), ["-workspace App.xcworkspace -scheme App -configuration Staging"]);
|
||||
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("App.xcworkspace")));
|
||||
// Without a workspace named after a project, the first by name.
|
||||
std::fs::remove_dir(root.join("App.xcworkspace")).unwrap();
|
||||
std::fs::create_dir(root.join("Old.xcworkspace")).unwrap();
|
||||
assert_eq!(crate::xcode::pods_workspace(root), Some(root.join("Aardvark.xcworkspace")));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests.
|
||||
//! Xcode test configurations: `xcodebuild test` for each scheme whose `TestAction` has tests,
|
||||
//! through the CocoaPods workspace when the project has one.
|
||||
//! The simulator destination and the result bundle are added at launch (`xcode::prepare_test`).
|
||||
|
||||
use super::{ConfigExt, config};
|
||||
@@ -6,11 +7,15 @@ use crate::RunConfig;
|
||||
use std::path::Path;
|
||||
|
||||
pub(super) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
// With a Podfile every scheme is built through the Pods workspace, assuming one app project
|
||||
// per folder: the workspace `pod install` writes links that project's targets.
|
||||
let pods = crate::xcode::pods_workspace(root);
|
||||
for scheme in crate::xcode::schemes(root) {
|
||||
if !scheme.has_tests {
|
||||
continue;
|
||||
}
|
||||
let Some(container) = scheme.container.file_name().and_then(|n| n.to_str()) else { continue };
|
||||
let path = pods.as_ref().unwrap_or(&scheme.container);
|
||||
let Some(container) = path.file_name().and_then(|n| n.to_str()) else { continue };
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
out.push(
|
||||
config(
|
||||
|
||||
@@ -23,6 +23,7 @@ pub mod tomcat;
|
||||
mod utf8;
|
||||
pub mod wrap;
|
||||
pub mod xcode;
|
||||
pub mod xcode_clean;
|
||||
|
||||
pub use detect::cmake::{build_configs as cmake_build_configs, prepare as prepare_cmake};
|
||||
pub use process::{DetachedProcessKills, ProcessManager, StartOptions};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! iOS Simulators, through `xcrun simctl` (macOS only): the devices an Xcode project can run on.
|
||||
//! iOS Simulators, through `xcrun simctl`, and connected iPhones and iPads, through
|
||||
//! `xcrun devicectl` (macOS only): the devices an Xcode project can run on.
|
||||
//!
|
||||
//! Flutter projects get theirs from `flutter daemon` (`ide-flutter`), so only native Xcode
|
||||
//! projects use this.
|
||||
@@ -11,7 +12,8 @@ use specta::Type;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
/// One simulator `simctl list devices available` reports.
|
||||
/// One simulator `simctl list devices available` reports, or one physical device
|
||||
/// `devicectl list devices` knows.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IosSimulator {
|
||||
@@ -19,10 +21,18 @@ pub struct IosSimulator {
|
||||
pub name: String,
|
||||
/// The runtime, as Xcode shows it: `iOS 27.0`.
|
||||
pub runtime: String,
|
||||
/// `Booted`, `Shutdown`, `Booting`, `Shutting Down`.
|
||||
/// `Booted`, `Shutdown`, `Booting`, `Shutting Down`; for a physical device [`AVAILABLE`],
|
||||
/// [`UNAVAILABLE`] (not connected) or [`DEVELOPER_MODE_OFF`].
|
||||
pub state: String,
|
||||
/// An iPhone or iPad rather than a simulator.
|
||||
pub physical: bool,
|
||||
}
|
||||
|
||||
/// The states of a physical device.
|
||||
pub const AVAILABLE: &str = "Available";
|
||||
pub const UNAVAILABLE: &str = "Unavailable";
|
||||
pub const DEVELOPER_MODE_OFF: &str = "Developer Mode Off";
|
||||
|
||||
/// An Xcode project or workspace directly in `root`, outside a Flutter project (whose
|
||||
/// `ios/Runner.xcodeproj` sits one level down and whose devices come from Flutter).
|
||||
pub fn is_xcode_project(root: &Path) -> bool {
|
||||
@@ -54,7 +64,8 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
|
||||
for d in list.as_array().into_iter().flatten() {
|
||||
let text = |key| d.get(key).and_then(Value::as_str).map(str::to_owned);
|
||||
let (Some(udid), Some(name), Some(state)) = (text("udid"), text("name"), text("state")) else { continue };
|
||||
devices.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state }));
|
||||
devices
|
||||
.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state, physical: false }));
|
||||
}
|
||||
}
|
||||
devices.sort_by(|(va, a), (vb, b)| {
|
||||
@@ -67,8 +78,73 @@ pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
|
||||
Ok(devices.into_iter().map(|(_, d)| d).collect())
|
||||
}
|
||||
|
||||
fn run(program: &str, args: &[&str]) -> IdeResult<String> {
|
||||
/// The physical iOS and iPadOS devices in `devicectl list devices --json-output` output, by name.
|
||||
/// Reads the fields Xcode 15 and later write, falling back to the `properties` that replace them.
|
||||
pub fn parse_devices(json: &str) -> IdeResult<Vec<IosSimulator>> {
|
||||
let value: Value = serde_json::from_str(json).map_err(|e| IdeError::internal(format!("devicectl list: {e}")))?;
|
||||
let mut devices = Vec::new();
|
||||
for d in value.pointer("/result/devices").and_then(Value::as_array).into_iter().flatten() {
|
||||
let text = |old: &str, new: &str| {
|
||||
d.pointer(old).or_else(|| d.pointer(new)).and_then(Value::as_str).unwrap_or_default().to_owned()
|
||||
};
|
||||
let reality = text("/hardwareProperties/reality", "/properties/hardware/reality");
|
||||
let platform = text("/hardwareProperties/platform", "/properties/hardware/platform");
|
||||
let udid = text("/hardwareProperties/udid", "/properties/hardware/udid");
|
||||
if reality != "physical" || !matches!(&*platform, "iOS" | "iPadOS") || udid.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let version = d
|
||||
.pointer("/deviceProperties/osVersionNumber")
|
||||
.or_else(|| d.pointer("/properties/software/osVersionNumber/stringValue"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
// `tunnelState` (`connected`, `disconnected`: reachable, connects on use) or `state`.
|
||||
let connection = text("/connectionProperties/tunnelState", "/properties/connection/state");
|
||||
let developer_mode = d
|
||||
.pointer("/deviceProperties/developerModeStatus")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.or_else(|| d.pointer("/properties/state/developerModeStatus")?.as_object()?.keys().next().cloned());
|
||||
let state = if connection == "unavailable" || connection.is_empty() {
|
||||
UNAVAILABLE
|
||||
} else if developer_mode.as_deref() == Some("disabled") {
|
||||
DEVELOPER_MODE_OFF
|
||||
} else {
|
||||
AVAILABLE
|
||||
};
|
||||
devices.push(IosSimulator {
|
||||
udid,
|
||||
name: text("/deviceProperties/name", "/properties/state/name"),
|
||||
runtime: format!("{platform} {version}").trim().to_owned(),
|
||||
state: state.to_owned(),
|
||||
physical: true,
|
||||
});
|
||||
}
|
||||
devices.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.udid.cmp(&b.udid)));
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
/// The physical devices paired with this Mac, as [`parse_devices`] reads them; none when
|
||||
/// `devicectl` (Xcode 15 and later) is missing or fails. `dir` picks the project's Xcode.
|
||||
pub fn devices(dir: &Path) -> Vec<IosSimulator> {
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos();
|
||||
let file = std::env::temp_dir().join(format!("openidea-devicectl-{}-{stamp}.json", std::process::id()));
|
||||
let path = file.to_string_lossy().into_owned();
|
||||
let listed = run_in(Some(dir), "xcrun", &["devicectl", "list", "devices", "--quiet", "--json-output", &path]);
|
||||
let json = std::fs::read_to_string(&file);
|
||||
let _ = std::fs::remove_file(&file);
|
||||
match (listed, json) {
|
||||
(Ok(_), Ok(json)) => parse_devices(&json).unwrap_or_default(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `dir`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
|
||||
fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(program);
|
||||
if let Some(dir) = dir {
|
||||
cmd.current_dir(dir);
|
||||
}
|
||||
prepare(&mut cmd).args(args);
|
||||
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("could not run {program}: {e}")))?;
|
||||
if out.status.success() {
|
||||
@@ -78,23 +154,26 @@ fn run(program: &str, args: &[&str]) -> IdeResult<String> {
|
||||
Err(IdeError::unavailable(format!("{program} {} failed: {}", args.join(" "), stderr.trim())))
|
||||
}
|
||||
|
||||
/// The available iOS simulators, sorted as [`parse_list`] does.
|
||||
pub fn list() -> IdeResult<Vec<IosSimulator>> {
|
||||
parse_list(&run("xcrun", &["simctl", "list", "devices", "available", "--json"])?)
|
||||
/// The available iOS simulators of the Xcode the project at `root` uses, sorted as
|
||||
/// [`parse_list`] does, then the physical devices.
|
||||
pub fn list(root: &Path) -> IdeResult<Vec<IosSimulator>> {
|
||||
let mut list = parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)?;
|
||||
list.extend(devices(root));
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
/// Boots a simulator; returns once `simctl` has it booted.
|
||||
pub fn boot(udid: &str) -> IdeResult<()> {
|
||||
run("xcrun", &["simctl", "boot", udid]).map(drop)
|
||||
run_in(None, "xcrun", &["simctl", "boot", udid]).map(drop)
|
||||
}
|
||||
|
||||
pub fn shutdown(udid: &str) -> IdeResult<()> {
|
||||
run("xcrun", &["simctl", "shutdown", udid]).map(drop)
|
||||
run_in(None, "xcrun", &["simctl", "shutdown", udid]).map(drop)
|
||||
}
|
||||
|
||||
/// Brings Simulator.app to the front, which shows the booted simulators.
|
||||
pub fn open_app() -> IdeResult<()> {
|
||||
run("open", &["-a", "Simulator"]).map(drop)
|
||||
run_in(None, "open", &["-a", "Simulator"]).map(drop)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -137,6 +216,42 @@ mod tests {
|
||||
assert_eq!(parse_list("{}").unwrap(), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_physical_devices_by_name_from_old_and_new_fields() {
|
||||
// Trimmed `devicectl list devices --json-output` (Xcode 27): one device with the
|
||||
// deprecated fields too, one with `properties` only, a simulator and a Mac.
|
||||
let json = r#"{"info": {"outcome": "success"}, "result": {"devices": [
|
||||
{"hardwareProperties": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"},
|
||||
"deviceProperties": {"name": "Work iPhone", "osVersionNumber": "27.3", "developerModeStatus": "enabled"},
|
||||
"connectionProperties": {"tunnelState": "disconnected"},
|
||||
"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"},
|
||||
"connection": {"state": "disconnected"}}},
|
||||
{"properties": {"hardware": {"reality": "physical", "platform": "iPadOS", "udid": "00008103-BBB"},
|
||||
"software": {"osVersionNumber": {"stringValue": "26.1"}},
|
||||
"state": {"name": "Test iPad", "developerModeStatus": {"disabled": {"mode": 0}}},
|
||||
"connection": {"state": "connected"}}},
|
||||
{"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008150-CCC"},
|
||||
"state": {"name": "Away iPhone", "developerModeStatus": {"enabled": {"mode": 1}}},
|
||||
"connection": {"state": "unavailable"}}},
|
||||
{"hardwareProperties": {"reality": "simulated", "platform": "iOS", "udid": "SIM"},
|
||||
"connectionProperties": {"tunnelState": "disconnected"}},
|
||||
{"hardwareProperties": {"reality": "physical", "platform": "macOS", "udid": "MAC"},
|
||||
"connectionProperties": {"tunnelState": "connected"}}
|
||||
]}}"#;
|
||||
let devices = parse_devices(json).unwrap();
|
||||
let rows: Vec<_> = devices.iter().map(|d| (&*d.name, &*d.udid, &*d.runtime, &*d.state, d.physical)).collect();
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
("Away iPhone", "00008150-CCC", "iOS", UNAVAILABLE, true),
|
||||
("Test iPad", "00008103-BBB", "iPadOS 26.1", DEVELOPER_MODE_OFF, true),
|
||||
("Work iPhone", "00008110-AAA", "iOS 27.3", AVAILABLE, true),
|
||||
]
|
||||
);
|
||||
assert!(parse_devices("not json").is_err());
|
||||
assert_eq!(parse_devices(r#"{"info": {"outcome": "failed"}}"#).unwrap(), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_xcode_projects_at_the_root_only() {
|
||||
let dir = std::env::temp_dir().join(format!("ide-run-simulator-{}", std::process::id()));
|
||||
|
||||
@@ -1027,13 +1027,13 @@ pub fn artifact_is_current(root: &Path, base: &Path, config: &RunConfig, modules
|
||||
let id_matches = selected.is_none_or(|id| recorded_id.as_deref().map(str::trim) == Some(id.as_str()));
|
||||
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
|
||||
let war = match recorded.filter(|_| id_matches) {
|
||||
Some(war) if war.is_file() && is_war(&war) => war,
|
||||
Some(war) if (war.is_file() && is_war(&war)) || war.is_dir() => war,
|
||||
_ => match find_built_war(root, Some(&module)) {
|
||||
Some(war) => war,
|
||||
None => return false,
|
||||
},
|
||||
};
|
||||
let Ok(war_time) = fs::metadata(&war).and_then(|m| m.modified()) else { return false };
|
||||
let Some(war_time) = newest_mtime_under(&war) else { return false };
|
||||
let mut newest = newest_mtime_under(&module.join("src"));
|
||||
// Web content packaged from outside `src` (a custom `warSourceDirectory`, `webResources`
|
||||
// directories, a custom Gradle web app dir) also lands in the WAR — the running-session
|
||||
@@ -1077,12 +1077,10 @@ pub fn deployment(root: &Path, base: &Path, config: &RunConfig, resources_only:
|
||||
let recorded = fs::read_to_string(base.join("artifact-path.txt")).ok().map(|s| PathBuf::from(s.trim()));
|
||||
let module = artifact_module_dir(root, config);
|
||||
let war = match recorded.filter(|_| id_matches) {
|
||||
Some(war) => {
|
||||
if war.is_file() && is_war(&war) {
|
||||
war
|
||||
} else {
|
||||
return Err(invalid(format!("The built WAR artifact does not exist: {}", war.display())));
|
||||
}
|
||||
Some(path) if path.is_file() && is_war(&path) => path,
|
||||
Some(path) if path.is_dir() => return Ok(path),
|
||||
Some(path) => {
|
||||
return Err(invalid(format!("The built WAR artifact does not exist: {}", path.display())));
|
||||
}
|
||||
None => find_built_war(root, Some(module.as_path())).ok_or_else(|| {
|
||||
invalid("No built WAR artifact found - build the project first, or add 'Build' to Before launch")
|
||||
@@ -2417,4 +2415,45 @@ mod tests {
|
||||
let error = prepare(root, &cache, &mut c).unwrap_err().to_string();
|
||||
assert!(error.contains("Two deployments use the application context /"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deploys_recorded_exploded_artifact_directory_directly() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let home = root.join("Tomcat Home");
|
||||
fs::create_dir_all(home.join("bin")).unwrap();
|
||||
fs::create_dir_all(home.join("conf")).unwrap();
|
||||
fs::write(home.join("bin/catalina.sh"), "").unwrap();
|
||||
fs::write(home.join("bin/catalina.bat"), "").unwrap();
|
||||
archive(
|
||||
&home.join("lib/catalina.jar"),
|
||||
&[("org/apache/catalina/util/ServerInfo.properties", "server.info=Apache Tomcat/10.1")],
|
||||
);
|
||||
let server = "<Server port='8005'><Service><Connector port='8080'/><Engine name='Catalina'><Host name='localhost'/></Engine></Service></Server>";
|
||||
fs::write(home.join("conf/server.xml"), server).unwrap();
|
||||
let exploded = root.join("out/artifacts/EJSH_war_exploded");
|
||||
fs::create_dir_all(exploded.join("WEB-INF")).unwrap();
|
||||
fs::write(exploded.join("WEB-INF/web.xml"), "<web-app/>").unwrap();
|
||||
|
||||
let mut c = config();
|
||||
for (k, v) in [
|
||||
("tomcatHome", "Tomcat Home"),
|
||||
("deployment", "artifact"),
|
||||
("artifact", "project:EJSH:war exploded"),
|
||||
("artifactName", "EJSH"),
|
||||
] {
|
||||
c.extras.params.insert(k.into(), v.into());
|
||||
}
|
||||
let cache = root.join("cache");
|
||||
let base = base_dir(&cache, &c.id);
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
fs::write(base.join("artifact-id.txt"), "project:EJSH:war exploded").unwrap();
|
||||
fs::write(base.join("artifact-path.txt"), exploded.to_string_lossy().as_bytes()).unwrap();
|
||||
|
||||
prepare(root, &cache, &mut c).unwrap();
|
||||
let runtime = PathBuf::from(&c.env["CATALINA_BASE"]);
|
||||
let ctx = fs::read_to_string(runtime.join("conf/Catalina/localhost/EJSH.xml")).unwrap();
|
||||
assert!(ctx.contains(&format!("docBase=\"{}\"", escape(&exploded.to_string_lossy()))), "{ctx}");
|
||||
assert!(artifact_is_current(root, &runtime, &c, &[]));
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@
|
||||
//! projects without any, but it takes a second or two, too slow for detection.
|
||||
//!
|
||||
//! A scheme's run configuration builds it for the iOS Simulator and launches the app there with
|
||||
//! `simctl`; [`prepare`] turns the configuration into that process when it starts.
|
||||
//! `simctl`, for a connected iPhone or iPad and launches it there with `devicectl`, or, for a
|
||||
//! macOS app, builds it for the Mac and runs its executable;
|
||||
//! [`prepare`] turns the configuration into that process when it starts.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use quick_xml::{Reader, XmlVersion, events::Event};
|
||||
@@ -45,6 +47,29 @@ pub fn schemes(root: &Path) -> Vec<XcodeScheme> {
|
||||
containers.iter().flat_map(|c| container_schemes(c)).collect()
|
||||
}
|
||||
|
||||
/// The `.xcworkspace` `pod install` wrote next to the app's project, when `root` has a `Podfile`:
|
||||
/// the one named after an `.xcodeproj` in `root`, else the first by name (a leftover workspace
|
||||
/// may sit beside it). The project alone doesn't link the pods, so its schemes are built through
|
||||
/// this workspace, which usually has no schemes of its own. The frontend picks the same one
|
||||
/// (`podsWorkspace` in `src/features/run/cocoapodsActions.ts`).
|
||||
pub fn pods_workspace(root: &Path) -> Option<PathBuf> {
|
||||
if !root.join("Podfile").is_file() {
|
||||
return None;
|
||||
}
|
||||
let mut dirs: Vec<PathBuf> = fs::read_dir(root).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
|
||||
dirs.sort();
|
||||
let has_ext = |p: &Path, ext: &str| p.extension().is_some_and(|e| e == ext);
|
||||
let projects: Vec<_> = dirs.iter().filter(|p| has_ext(p, "xcodeproj")).filter_map(|p| p.file_stem()).collect();
|
||||
let workspaces: Vec<&PathBuf> = dirs.iter().filter(|p| has_ext(p, "xcworkspace")).collect();
|
||||
let named = workspaces.iter().find(|w| w.file_stem().is_some_and(|s| projects.contains(&s)));
|
||||
named.or(workspaces.first()).map(|w| (*w).clone())
|
||||
}
|
||||
|
||||
/// The `Pods/` folder of a CocoaPods project: its `Pods.xcodeproj` is generated, not the app.
|
||||
pub fn is_pods_dir(dir: &Path) -> bool {
|
||||
dir.file_name().is_some_and(|n| n == "Pods") && dir.parent().is_some_and(|p| p.join("Podfile").is_file())
|
||||
}
|
||||
|
||||
fn container_schemes(container: &Path) -> Vec<XcodeScheme> {
|
||||
let mut out: Vec<XcodeScheme> = Vec::new();
|
||||
let mut add = |dir: PathBuf, shared: bool| {
|
||||
@@ -154,16 +179,21 @@ fn resolve(reference: &str, container: &Path) -> PathBuf {
|
||||
|
||||
/// Completes an `xcodebuild test` launch: a simulator destination unless the configuration names
|
||||
/// one, and a fresh `-resultBundlePath` under `bundles` (xcodebuild refuses an existing one). The
|
||||
/// bundles of this configuration's earlier runs are removed.
|
||||
pub fn prepare_test(config: &mut crate::RunConfig, bundles: &Path) -> std::io::Result<()> {
|
||||
/// bundles of this configuration's earlier runs are removed. Run with Coverage names the bundle
|
||||
/// itself in [`RESULT_BUNDLE_PARAM`].
|
||||
pub fn prepare_test(config: &mut crate::RunConfig, dir: &Path, bundles: &Path) -> std::io::Result<()> {
|
||||
if !config.args.iter().any(|a| a == "-destination")
|
||||
&& let Some(udid) = default_simulator()
|
||||
&& let Some(udid) = default_simulator(dir)
|
||||
{
|
||||
config.args.extend(["-destination".to_owned(), format!("id={udid}")]);
|
||||
}
|
||||
if let Some(at) = config.args.iter().position(|a| a == "-resultBundlePath") {
|
||||
config.args.drain(at..(at + 2).min(config.args.len()));
|
||||
}
|
||||
if let Some(bundle) = config.extras.params.get(RESULT_BUNDLE_PARAM).cloned() {
|
||||
config.args.extend(["-resultBundlePath".to_owned(), bundle]);
|
||||
return Ok(());
|
||||
}
|
||||
let prefix: String = config.id.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
|
||||
fs::create_dir_all(bundles)?;
|
||||
for entry in fs::read_dir(bundles)?.flatten() {
|
||||
@@ -177,10 +207,11 @@ pub fn prepare_test(config: &mut crate::RunConfig, bundles: &Path) -> std::io::R
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The booted iOS simulator, otherwise the first iPhone of the newest iOS runtime.
|
||||
pub fn default_simulator() -> Option<String> {
|
||||
/// The booted iOS simulator, otherwise the first iPhone of the newest iOS runtime. `dir` (inside
|
||||
/// the project) picks the project's Xcode.
|
||||
pub fn default_simulator(dir: &Path) -> Option<String> {
|
||||
let mut cmd = std::process::Command::new("xcrun");
|
||||
cmd.args(["simctl", "list", "devices", "available", "-j"]);
|
||||
cmd.args(["simctl", "list", "devices", "available", "-j"]).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd).output().ok()?;
|
||||
pick_simulator(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
@@ -208,15 +239,26 @@ fn pick_simulator(json: &str) -> Option<String> {
|
||||
|
||||
/// The run configuration parameter that holds the simulator's UDID. Empty means
|
||||
/// [`default_simulator`]: the one place a device selector can feed its choice into.
|
||||
/// [`MAC`] runs an app that supports both on the Mac instead.
|
||||
pub const SIMULATOR_PARAM: &str = "simulator";
|
||||
/// The result bundle an `xcodebuild test` launch writes, when the caller reads it afterwards.
|
||||
pub const RESULT_BUNDLE_PARAM: &str = "resultBundle";
|
||||
|
||||
/// Set (to anything but empty) by Debug: the app is launched suspended
|
||||
/// (`simctl launch --wait-for-debugger`) until the debugger attaches to the pid simctl prints.
|
||||
pub const WAIT_FOR_DEBUGGER_PARAM: &str = "waitForDebugger";
|
||||
|
||||
/// The [`SIMULATOR_PARAM`] value that runs a multiplatform app on the Mac.
|
||||
pub const MAC: &str = "macos";
|
||||
|
||||
/// The `xcodebuild` arguments that pick what is built, and where, for a `kind = "xcode"`
|
||||
/// configuration: its `container`, `scheme` and `configuration` params and the simulator.
|
||||
pub fn build_args(params: &BTreeMap<String, String>, udid: &str, derived_data: &Path) -> Result<Vec<String>, String> {
|
||||
/// configuration: its `container`, `scheme` and `configuration` params and the `-destination`
|
||||
/// (`id=<udid>`, `platform=macOS`; None leaves it to the scheme).
|
||||
pub fn build_args(
|
||||
params: &BTreeMap<String, String>,
|
||||
destination: Option<&str>,
|
||||
derived_data: &Path,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let param = |key: &str| params.get(key).map(|v| v.trim()).filter(|v| !v.is_empty());
|
||||
let container = param("container").ok_or("No Xcode project or workspace is set")?;
|
||||
let scheme = param("scheme").ok_or("No scheme is set")?;
|
||||
@@ -225,36 +267,71 @@ pub fn build_args(params: &BTreeMap<String, String>, udid: &str, derived_data: &
|
||||
if let Some(configuration) = param("configuration") {
|
||||
args.extend(["-configuration".to_owned(), configuration.to_owned()]);
|
||||
}
|
||||
args.extend([
|
||||
"-destination".to_owned(),
|
||||
format!("id={udid}"),
|
||||
"-derivedDataPath".to_owned(),
|
||||
derived_data.to_string_lossy().into_owned(),
|
||||
]);
|
||||
if let Some(destination) = destination {
|
||||
args.extend(["-destination".to_owned(), destination.to_owned()]);
|
||||
}
|
||||
args.extend(["-derivedDataPath".to_owned(), derived_data.to_string_lossy().into_owned()]);
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The built `.app` and its bundle id, from `xcodebuild -showBuildSettings -json`: the
|
||||
/// scheme's first application target.
|
||||
pub fn built_app(settings: &str) -> Result<(PathBuf, String), String> {
|
||||
/// The application targets' build settings in `xcodebuild -showBuildSettings -json` output.
|
||||
fn app_settings(settings: &str) -> Result<Vec<serde_json::Value>, String> {
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_str(settings).map_err(|e| format!("Unreadable build settings: {e}"))?;
|
||||
let targets = json.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
let apps = || {
|
||||
targets
|
||||
.iter()
|
||||
.map(|t| &t["buildSettings"])
|
||||
.filter(|b| b["PRODUCT_TYPE"] == "com.apple.product-type.application")
|
||||
};
|
||||
let Some(app) = apps().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else {
|
||||
return Err(match apps().next().and_then(|b| b["PLATFORM_NAME"].as_str()) {
|
||||
Some("macosx") => "Running macOS apps is not supported yet; only iOS apps run on the Simulator".to_owned(),
|
||||
Some(platform) => format!("The scheme builds an app for {platform}, not the iOS Simulator"),
|
||||
let targets = json.as_array().cloned().unwrap_or_default();
|
||||
Ok(targets
|
||||
.into_iter()
|
||||
.map(|mut t| t["buildSettings"].take())
|
||||
.filter(|b| b["PRODUCT_TYPE"] == "com.apple.product-type.application")
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Whether the scheme's first application runs on the Mac, from its `SUPPORTED_PLATFORMS` in
|
||||
/// build settings read without a destination: it supports macOS but not the iOS Simulator, or
|
||||
/// both and `simulator` is [`MAC`].
|
||||
pub fn runs_on_mac(settings: &str, simulator: &str) -> Result<bool, String> {
|
||||
let apps = app_settings(settings)?;
|
||||
let app = apps.first().ok_or("The scheme builds no application")?;
|
||||
let platforms: Vec<&str> = app["SUPPORTED_PLATFORMS"].as_str().unwrap_or_default().split_whitespace().collect();
|
||||
Ok(platforms.contains(&"macosx") && (simulator.trim() == MAC || !platforms.contains(&"iphonesimulator")))
|
||||
}
|
||||
|
||||
/// The executable inside the built macOS `.app`: `TARGET_BUILD_DIR/EXECUTABLE_PATH`.
|
||||
pub fn mac_executable(settings: &str) -> Result<PathBuf, String> {
|
||||
let apps = app_settings(settings)?;
|
||||
let app = apps.iter().find(|b| b["PLATFORM_NAME"] == "macosx").ok_or("The scheme builds no macOS application")?;
|
||||
let get =
|
||||
|key: &str| app[key].as_str().filter(|v| !v.is_empty()).ok_or(format!("The build settings have no {key}"));
|
||||
Ok(Path::new(get("TARGET_BUILD_DIR")?).join(get("EXECUTABLE_PATH")?))
|
||||
}
|
||||
|
||||
/// The built `.app` and its bundle id, from `xcodebuild -showBuildSettings -json`: the
|
||||
/// scheme's first application target for the iOS Simulator, or with `device` for an iPhone or
|
||||
/// iPad, which runs only an app signed with a development team.
|
||||
pub fn built_app(settings: &str, device: bool) -> Result<(PathBuf, String), String> {
|
||||
let apps = app_settings(settings)?;
|
||||
let (platform, target) =
|
||||
if device { ("iphoneos", "an iOS device") } else { ("iphonesimulator", "the iOS Simulator") };
|
||||
let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == platform) else {
|
||||
return Err(match apps.first().and_then(|b| b["PLATFORM_NAME"].as_str()) {
|
||||
Some(platform) => format!("The scheme builds an app for {platform}, not {target}"),
|
||||
None => "The scheme builds no application".to_owned(),
|
||||
});
|
||||
};
|
||||
let get =
|
||||
|key: &str| app[key].as_str().filter(|v| !v.is_empty()).ok_or(format!("The build settings have no {key}"));
|
||||
if device && app["CODE_SIGNING_ALLOWED"] == "NO" {
|
||||
return Err(format!(
|
||||
"{} is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps",
|
||||
get("WRAPPER_NAME")?
|
||||
));
|
||||
}
|
||||
if device && app["CODE_SIGN_STYLE"] == "Automatic" && get("DEVELOPMENT_TEAM").is_err() {
|
||||
return Err(format!(
|
||||
"Signing {} for a device needs a development team: choose one under Signing & Capabilities in Xcode",
|
||||
get("WRAPPER_NAME")?
|
||||
));
|
||||
}
|
||||
Ok((Path::new(get("TARGET_BUILD_DIR")?).join(get("WRAPPER_NAME")?), get("PRODUCT_BUNDLE_IDENTIFIER")?.to_owned()))
|
||||
}
|
||||
|
||||
@@ -311,36 +388,146 @@ fn announce_suspended(udid: &str, bundle_id: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The script a run on a physical device executes: build with the project's signing (letting
|
||||
/// Xcode register the device and fetch profiles, as its own Run does), install, then launch with
|
||||
/// the app's output on the console. The app's arguments follow the script as `$@`. A Stop's
|
||||
/// SIGINT becomes a SIGTERM to `devicectl` (a background job ignores SIGINT), which passes it on
|
||||
/// to the app. When `devicectl` itself fails to launch the app
|
||||
/// (its JSON outcome is not `success`) and no Stop was asked for, a hint about a locked device
|
||||
/// follows its error.
|
||||
pub fn device_launch_script(build_args: &[String], udid: &str, name: &str, app: &Path, bundle_id: &str) -> String {
|
||||
let build: Vec<String> = build_args.iter().map(|a| sh_quote(a)).collect();
|
||||
let (udid, app, bundle_id) = (sh_quote(udid), sh_quote(&app.to_string_lossy()), sh_quote(bundle_id));
|
||||
let hint = sh_quote(&format!("Could not launch the app on {name}. If it is locked, unlock it and run again."));
|
||||
format!(
|
||||
"set -e\n\
|
||||
xcodebuild {} -allowProvisioningUpdates build\n\
|
||||
xcrun devicectl device install app --device {udid} {app}\n\
|
||||
set +e\n\
|
||||
result=$(mktemp)\n\
|
||||
xcrun devicectl device process launch --console --terminate-existing --json-output \"$result\" --device {udid} {bundle_id} -- \"$@\" &\n\
|
||||
launch=$!\n\
|
||||
trap 'stopped=1; kill -TERM $launch 2>/dev/null' INT TERM\n\
|
||||
wait $launch; status=$?\n\
|
||||
while kill -0 $launch 2>/dev/null; do wait $launch; status=$?; done\n\
|
||||
if [ -z \"$stopped\" ] && ! grep -q '\"outcome\" *: *\"success\"' \"$result\" 2>/dev/null; then echo {hint} >&2; fi\n\
|
||||
rm -f \"$result\"\n\
|
||||
exit $status\n",
|
||||
build.join(" "),
|
||||
)
|
||||
}
|
||||
|
||||
/// Why a run cannot start on `device`, a physical one [`crate::simulator::devices`] listed.
|
||||
fn device_unready(device: &crate::simulator::IosSimulator) -> Option<String> {
|
||||
let name = &device.name;
|
||||
match device.state.as_str() {
|
||||
crate::simulator::UNAVAILABLE => Some(format!(
|
||||
"{name} is not connected. Connect it with a cable or to this Mac's network, unlock it, and run again."
|
||||
)),
|
||||
crate::simulator::DEVELOPER_MODE_OFF => Some(format!(
|
||||
"Developer Mode is off on {name}. Turn it on in Settings > Privacy & Security > Developer Mode, restart the device, and run again."
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The script a macOS run executes: build, then become the app's executable, so its output
|
||||
/// reaches the console and a Stop's SIGINT reaches the app. Its arguments follow as `$@`.
|
||||
pub fn mac_launch_script(build_args: &[String], executable: &Path) -> String {
|
||||
let build: Vec<String> = build_args.iter().map(|a| sh_quote(a)).collect();
|
||||
format!("set -e\nxcodebuild {} build\nexec {} \"$@\"\n", build.join(" "), sh_quote(&executable.to_string_lossy()))
|
||||
}
|
||||
|
||||
/// The `-destination` of a run of `params` on a Mac.
|
||||
pub const MAC_DESTINATION: &str = "platform=macOS";
|
||||
|
||||
/// Runs `program` in `dir` and returns its stdout; a failure carries its stderr.
|
||||
fn output(dir: &Path, program: &str, args: &[String]) -> IdeResult<String> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
cmd.args(args).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd)
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("Cannot run {program}: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("{program} {} failed:\n{}", args.join(" "), err.trim())));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// Where a run of `params` builds: [`MAC_DESTINATION`] when the scheme's app runs on the Mac
|
||||
/// ([`runs_on_mac`]), else `id=<udid>` of the configured simulator or the default one. A Clean
|
||||
/// Build Folder of the configuration uses the same destination.
|
||||
pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data: &Path) -> IdeResult<String> {
|
||||
let simulator = params.get(SIMULATOR_PARAM).map_or("", String::as_str);
|
||||
let args = [
|
||||
build_args(params, None, derived_data).map_err(IdeError::invalid)?,
|
||||
vec!["-showBuildSettings".into(), "-json".into()],
|
||||
]
|
||||
.concat();
|
||||
if runs_on_mac(&output(dir, "xcodebuild", &args)?, simulator).map_err(IdeError::invalid)? {
|
||||
return Ok(MAC_DESTINATION.to_owned());
|
||||
}
|
||||
let udid = match Some(simulator.trim()).filter(|s| !s.is_empty() && *s != MAC) {
|
||||
Some(udid) => udid.to_owned(),
|
||||
None => default_simulator(dir).ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
|
||||
};
|
||||
Ok(format!("id={udid}"))
|
||||
}
|
||||
|
||||
/// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches
|
||||
/// its scheme on the simulator. `dir` is the run's working directory; DerivedData goes under
|
||||
/// `cache_dir`. The configuration's environment reaches the app as `SIMCTL_CHILD_*`.
|
||||
/// its scheme on the simulator, or on the physical device whose UDID [`SIMULATOR_PARAM`] holds. `dir` is the run's working directory; DerivedData goes under
|
||||
/// `cache_dir`. The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`.
|
||||
/// A macOS app ([`runs_on_mac`]) is built for `platform=macOS` and run directly, with no simulator.
|
||||
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Err(IdeError::unavailable("Xcode schemes run on macOS only"));
|
||||
}
|
||||
let output = |program: &str, args: &[String]| -> IdeResult<String> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
cmd.args(args).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd)
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("Cannot run {program}: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("{program} {} failed:\n{}", args.join(" "), err.trim())));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
};
|
||||
let params = &config.extras.params;
|
||||
let udid = match params.get(SIMULATOR_PARAM).map(|s| s.trim()).filter(|s| !s.is_empty()) {
|
||||
Some(udid) => udid.to_owned(),
|
||||
None => default_simulator().ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
|
||||
};
|
||||
let derived_data = cache_dir.join("xcode/DerivedData");
|
||||
let args = build_args(params, &udid, &derived_data).map_err(IdeError::invalid)?;
|
||||
let settings = output("xcodebuild", &[args.as_slice(), &["-showBuildSettings".into(), "-json".into()]].concat())?;
|
||||
let (app, bundle_id) = built_app(&settings).map_err(IdeError::invalid)?;
|
||||
let derived_data = crate::xcode_clean::ide_derived_data(cache_dir);
|
||||
let show =
|
||||
|args: &[String]| output(dir, "xcodebuild", &[args, &["-showBuildSettings".into(), "-json".into()]].concat());
|
||||
let destination = destination(dir, params, &derived_data)?;
|
||||
if destination == MAC_DESTINATION {
|
||||
let args = build_args(params, Some(MAC_DESTINATION), &derived_data).map_err(IdeError::invalid)?;
|
||||
let executable = mac_executable(&show(&args)?).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
config.command = "/bin/sh".into();
|
||||
config.args = ["-c".to_owned(), mac_launch_script(&args, &executable), "xcode-run".to_owned()]
|
||||
.into_iter()
|
||||
.chain(app_args)
|
||||
.collect();
|
||||
// Foundation buffers a GUI app's stdout when it is not a terminal; Xcode sets this too.
|
||||
config.env.entry("NSUnbufferedIO".to_owned()).or_insert_with(|| "YES".to_owned());
|
||||
return Ok(());
|
||||
}
|
||||
let udid = destination.trim_start_matches("id=").to_owned();
|
||||
let device = crate::simulator::devices(dir).into_iter().find(|d| d.udid == udid);
|
||||
if let Some(reason) = device.as_ref().and_then(device_unready) {
|
||||
return Err(IdeError::unavailable(reason));
|
||||
}
|
||||
let args = build_args(params, Some(&destination), &derived_data).map_err(IdeError::invalid)?;
|
||||
let settings = show(&args)?;
|
||||
let (app, bundle_id) = built_app(&settings, device.is_some()).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
let wait = params.get(WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty());
|
||||
if let Some(device) = device {
|
||||
if wait {
|
||||
return Err(IdeError::unavailable("Debugging an app on a physical device is not supported yet"));
|
||||
}
|
||||
config.command = "/bin/sh".into();
|
||||
config.args = [
|
||||
"-c".to_owned(),
|
||||
device_launch_script(&args, &udid, &device.name, &app, &bundle_id),
|
||||
"xcode-run".to_owned(),
|
||||
]
|
||||
.into_iter()
|
||||
.chain(app_args)
|
||||
.collect();
|
||||
let env = std::mem::take(&mut config.env);
|
||||
config.env = env.into_iter().map(|(k, v)| (format!("DEVICECTL_CHILD_{k}"), v)).collect();
|
||||
return Ok(());
|
||||
}
|
||||
config.command = "/bin/sh".into();
|
||||
config.args = ["-c".to_owned(), launch_script(&args, &udid, &app, &bundle_id, wait), "xcode-run".to_owned()]
|
||||
.into_iter()
|
||||
@@ -455,12 +642,16 @@ mod tests {
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
prepare_test(&mut config, dir.path()).unwrap();
|
||||
prepare_test(&mut config, dir.path(), dir.path()).unwrap();
|
||||
assert_eq!(config.args[..3], ["test", "-destination", "id=X"]);
|
||||
assert_eq!(config.args[3], "-resultBundlePath");
|
||||
assert!(config.args[4].contains("xcode_test_A-") && config.args[4].ends_with(".xcresult"));
|
||||
assert_eq!(config.args.len(), 5);
|
||||
assert!(!old.exists() && other.exists());
|
||||
|
||||
config.extras.params.insert(RESULT_BUNDLE_PARAM.into(), "/cov/r.xcresult".into());
|
||||
prepare_test(&mut config, dir.path(), dir.path()).unwrap();
|
||||
assert_eq!(config.args[3..], ["-resultBundlePath", "/cov/r.xcresult"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -477,7 +668,7 @@ mod tests {
|
||||
.into();
|
||||
let dd = Path::new("/cache/DerivedData");
|
||||
assert_eq!(
|
||||
build_args(¶ms, "U1", dd).unwrap(),
|
||||
build_args(¶ms, Some("id=U1"), dd).unwrap(),
|
||||
[
|
||||
"-workspace",
|
||||
"App.xcworkspace",
|
||||
@@ -494,11 +685,11 @@ mod tests {
|
||||
params.insert("container".into(), "App.xcodeproj".into());
|
||||
params.remove("configuration");
|
||||
assert_eq!(
|
||||
build_args(¶ms, "U1", dd).unwrap()[..5],
|
||||
build_args(¶ms, Some("id=U1"), dd).unwrap()[..5],
|
||||
["-project", "App.xcodeproj", "-scheme", "App", "-destination"]
|
||||
);
|
||||
params.remove("scheme");
|
||||
assert_eq!(build_args(¶ms, "U1", dd).unwrap_err(), "No scheme is set");
|
||||
assert_eq!(build_args(¶ms, Some("id=U1"), dd).unwrap_err(), "No scheme is set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -514,11 +705,154 @@ mod tests {
|
||||
)
|
||||
};
|
||||
assert_eq!(
|
||||
built_app(&settings("iphonesimulator")).unwrap(),
|
||||
built_app(&settings("iphonesimulator"), false).unwrap(),
|
||||
(PathBuf::from("/dd/Build/Products/Debug-iphonesimulator/App.app"), "dev.example.App".to_owned())
|
||||
);
|
||||
assert!(built_app(&settings("macosx")).unwrap_err().contains("macOS apps is not supported"));
|
||||
assert_eq!(built_app("[]").unwrap_err(), "The scheme builds no application");
|
||||
assert_eq!(
|
||||
built_app(&settings("macosx"), false).unwrap_err(),
|
||||
"The scheme builds an app for macosx, not the iOS Simulator"
|
||||
);
|
||||
assert_eq!(built_app("[]", false).unwrap_err(), "The scheme builds no application");
|
||||
assert_eq!(
|
||||
built_app(&settings("iphonesimulator"), true).unwrap_err(),
|
||||
"The scheme builds an app for iphonesimulator, not an iOS device"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_app_must_be_signed_with_a_team() {
|
||||
let settings = |signing: &str| {
|
||||
format!(
|
||||
r#"[{{"target": "App", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.application",
|
||||
"PLATFORM_NAME": "iphoneos", "TARGET_BUILD_DIR": "/dd/Debug-iphoneos", "WRAPPER_NAME": "App.app",
|
||||
"PRODUCT_BUNDLE_IDENTIFIER": "dev.example.App", {signing}}}}}]"#
|
||||
)
|
||||
};
|
||||
let signed = settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": "ABCDE12345""#);
|
||||
assert_eq!(
|
||||
built_app(&signed, true).unwrap(),
|
||||
(PathBuf::from("/dd/Debug-iphoneos/App.app"), "dev.example.App".to_owned())
|
||||
);
|
||||
let manual = settings(r#""CODE_SIGN_STYLE": "Manual", "DEVELOPMENT_TEAM": """#);
|
||||
assert!(built_app(&manual, true).is_ok(), "manual signing names its profile; xcodebuild checks it");
|
||||
assert_eq!(
|
||||
built_app(&settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": """#), true).unwrap_err(),
|
||||
"Signing App.app for a device needs a development team: choose one under Signing & Capabilities in Xcode"
|
||||
);
|
||||
assert_eq!(
|
||||
built_app(&settings(r#""CODE_SIGNING_ALLOWED": "NO""#), true).unwrap_err(),
|
||||
"App.app is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unready_device_says_what_to_do() {
|
||||
let device = |state: &str| crate::simulator::IosSimulator {
|
||||
udid: "U".into(),
|
||||
name: "Test iPhone".into(),
|
||||
runtime: "iOS 27.3".into(),
|
||||
state: state.into(),
|
||||
physical: true,
|
||||
};
|
||||
assert_eq!(device_unready(&device(crate::simulator::AVAILABLE)), None);
|
||||
assert!(
|
||||
device_unready(&device(crate::simulator::UNAVAILABLE))
|
||||
.unwrap()
|
||||
.starts_with("Test iPhone is not connected.")
|
||||
);
|
||||
assert!(
|
||||
device_unready(&device(crate::simulator::DEVELOPER_MODE_OFF))
|
||||
.unwrap()
|
||||
.starts_with("Developer Mode is off on Test iPhone.")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mac_only_app_or_a_multiplatform_one_pinned_to_the_mac_runs_on_the_mac() {
|
||||
let settings = |platforms: &str| {
|
||||
format!(
|
||||
r#"[{{"target": "Kit", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.framework", "SUPPORTED_PLATFORMS": "macosx"}}}},
|
||||
{{"target": "App", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.application", "SUPPORTED_PLATFORMS": "{platforms}"}}}}]"#
|
||||
)
|
||||
};
|
||||
assert!(runs_on_mac(&settings("macosx"), "").unwrap());
|
||||
assert!(runs_on_mac(&settings("macosx"), "SOME-UDID").unwrap());
|
||||
assert!(!runs_on_mac(&settings("iphoneos iphonesimulator"), "").unwrap());
|
||||
assert!(!runs_on_mac(&settings("iphoneos iphonesimulator"), MAC).unwrap());
|
||||
assert!(!runs_on_mac(&settings("iphoneos iphonesimulator macosx"), "SOME-UDID").unwrap());
|
||||
assert!(runs_on_mac(&settings("iphoneos iphonesimulator macosx"), " macos ").unwrap());
|
||||
assert_eq!(runs_on_mac("[]", "").unwrap_err(), "The scheme builds no application");
|
||||
|
||||
let mac = r#"[{"target": "App", "buildSettings": {"PRODUCT_TYPE": "com.apple.product-type.application",
|
||||
"PLATFORM_NAME": "macosx", "TARGET_BUILD_DIR": "/dd/Build/Products/Debug", "EXECUTABLE_PATH": "My App.app/Contents/MacOS/My App"}}]"#;
|
||||
assert_eq!(
|
||||
mac_executable(mac).unwrap(),
|
||||
PathBuf::from("/dd/Build/Products/Debug/My App.app/Contents/MacOS/My App")
|
||||
);
|
||||
assert_eq!(mac_executable(&settings("macosx")).unwrap_err(), "The scheme builds no macOS application");
|
||||
let dd = Path::new("/dd");
|
||||
let params: BTreeMap<String, String> =
|
||||
[("container", "App.xcodeproj"), ("scheme", "App")].map(|(k, v)| (k.to_owned(), v.to_owned())).into();
|
||||
assert_eq!(
|
||||
build_args(¶ms, Some("platform=macOS"), dd).unwrap(),
|
||||
[
|
||||
"-project",
|
||||
"App.xcodeproj",
|
||||
"-scheme",
|
||||
"App",
|
||||
"-destination",
|
||||
"platform=macOS",
|
||||
"-derivedDataPath",
|
||||
"/dd"
|
||||
]
|
||||
);
|
||||
assert!(!build_args(¶ms, None, dd).unwrap().iter().any(|a| a == "-destination"));
|
||||
}
|
||||
|
||||
/// The script builds, then runs the executable in its place: the stub app logs its arguments
|
||||
/// and environment and exits on the SIGINT a Stop sends.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn mac_launch_script_builds_then_runs_the_executable_until_stopped() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let log = dir.path().join("log");
|
||||
let stub = |path: &Path, then: &str| {
|
||||
let body = format!(
|
||||
"#!/bin/sh\nprintf '%s' \"${{0##*/}}\" >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}"
|
||||
);
|
||||
fs::write(path, body).unwrap();
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
stub(&dir.path().join("xcodebuild"), "");
|
||||
let exe = dir.path().join("My App");
|
||||
stub(
|
||||
&exe,
|
||||
"echo \"GREETING=$GREETING\" >> \"$LOG\"\ntrap 'echo stopped >> \"$LOG\"; exit 0' INT\nwhile :; do sleep 0.05; done\n",
|
||||
);
|
||||
let build = ["-scheme".to_owned(), "It's".to_owned(), "-destination".to_owned(), "platform=macOS".to_owned()];
|
||||
let mut child = std::process::Command::new("/bin/sh")
|
||||
.args(["-c", &mac_launch_script(&build, &exe), "xcode-run", "--greeting", "hi there"])
|
||||
.env("PATH", format!("{}:/usr/bin:/bin", dir.path().display()))
|
||||
.env("LOG", &log)
|
||||
.env("GREETING", "hello")
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
while !fs::read_to_string(&log).unwrap_or_default().contains("GREETING") && std::time::Instant::now() < deadline
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
unsafe { libc::kill(child.id() as i32, libc::SIGINT) };
|
||||
assert!(child.wait().unwrap().success());
|
||||
assert_eq!(
|
||||
fs::read_to_string(&log).unwrap(),
|
||||
"xcodebuild [-scheme] [It's] [-destination] [platform=macOS] [build]\n\
|
||||
My App [--greeting] [hi there]\n\
|
||||
GREETING=hello\n\
|
||||
stopped\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// Runs the script against stub `xcodebuild`, `xcrun` and `open` that log their arguments; the
|
||||
@@ -570,6 +904,82 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The device script builds, installs and launches through devicectl, turns a Stop's SIGINT
|
||||
/// into a SIGTERM to it, and adds the locked-device hint only when devicectl itself failed to launch.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn device_launch_script_installs_launches_and_explains_a_failed_launch() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let log = dir.path().join("log");
|
||||
let stub = |tool: &str, then: &str| {
|
||||
let path = dir.path().join(tool);
|
||||
let body = format!(
|
||||
"#!/bin/sh\nprintf '{tool}' >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}"
|
||||
);
|
||||
fs::write(&path, body).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
stub("xcodebuild", "");
|
||||
// `launch` writes its JSON result to the path after `--json-output` ($8), then either
|
||||
// fails at once or runs until a SIGINT reaches it.
|
||||
stub(
|
||||
"xcrun",
|
||||
"[ \"$4\" = launch ] || exit 0\n\
|
||||
printf '{\"info\" : {\"outcome\" : \"%s\"}}' \"$OUTCOME\" > \"$8\"\n\
|
||||
[ \"$OUTCOME\" = success ] || { echo 'ERROR: the device was not unlocked' >&2; exit 1; }\n\
|
||||
trap 'echo terminated >> \"$LOG\"; exit 0' TERM\n\
|
||||
while :; do sleep 0.05; done\n",
|
||||
);
|
||||
let build = ["-project".to_owned(), "App.xcodeproj".to_owned()];
|
||||
let script =
|
||||
device_launch_script(&build, "00008110-AAA", "Test iPhone", Path::new("/dd/My App.app"), "dev.example.App");
|
||||
let run = |outcome: &str| {
|
||||
let _ = fs::remove_file(&log);
|
||||
std::process::Command::new("/bin/sh")
|
||||
.args(["-c", &script, "xcode-run", "--greeting", "hi there"])
|
||||
.env("PATH", format!("{}:/usr/bin:/bin", dir.path().display()))
|
||||
.env("LOG", &log)
|
||||
.env("OUTCOME", outcome)
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let failed = run("failed").wait_with_output().unwrap();
|
||||
assert_eq!(failed.status.code(), Some(1));
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&failed.stderr),
|
||||
"ERROR: the device was not unlocked\n\
|
||||
Could not launch the app on Test iPhone. If it is locked, unlock it and run again.\n"
|
||||
);
|
||||
|
||||
let child = run("success");
|
||||
let launched = || fs::read_to_string(&log).unwrap_or_default().contains("[launch]");
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
while !launched() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
unsafe { libc::kill(child.id() as i32, libc::SIGINT) };
|
||||
let stopped = child.wait_with_output().unwrap();
|
||||
assert!(stopped.status.success());
|
||||
assert_eq!(String::from_utf8_lossy(&stopped.stderr), "");
|
||||
let log = fs::read_to_string(&log).unwrap();
|
||||
let json = log.split("[--json-output] [").nth(1).unwrap().split(']').next().unwrap().to_owned();
|
||||
assert_eq!(
|
||||
log,
|
||||
format!(
|
||||
"xcodebuild [-project] [App.xcodeproj] [-allowProvisioningUpdates] [build]\n\
|
||||
xcrun [devicectl] [device] [install] [app] [--device] [00008110-AAA] [/dd/My App.app]\n\
|
||||
xcrun [devicectl] [device] [process] [launch] [--console] [--terminate-existing] [--json-output] [{json}] \
|
||||
[--device] [00008110-AAA] [dev.example.App] [--] [--greeting] [hi there]\n\
|
||||
terminated\n"
|
||||
)
|
||||
);
|
||||
assert!(!Path::new(&json).exists(), "the launch result file is removed");
|
||||
}
|
||||
|
||||
/// A debug launch passes `--wait-for-debugger` and prints the pid of the suspended app (not of
|
||||
/// a running copy, nor of a process outside its bundle) right away, while simctl keeps running.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Product › Clean Build Folder and deleting a project's DerivedData, for the `kind = "xcode"`
|
||||
//! configurations of `crate::detect::xcode`.
|
||||
use crate::xcode::{build_args, destination};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The configuration kind of a Clean Build Folder run; its params are an `xcode` configuration's.
|
||||
pub const KIND: &str = "xcode-clean";
|
||||
|
||||
/// Where the IDE's runs of a project build: `xcodebuild -derivedDataPath`, under the project's cache.
|
||||
pub fn ide_derived_data(cache_dir: &Path) -> PathBuf {
|
||||
cache_dir.join("xcode/DerivedData")
|
||||
}
|
||||
|
||||
/// Turns a [`KIND`] configuration into `xcodebuild clean` of the build its `xcode` configuration
|
||||
/// runs: the same container, scheme, configuration, destination (the simulator, or the Mac for a
|
||||
/// macOS app) and DerivedData. `dir` is the configuration's working directory.
|
||||
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
let params = &config.extras.params;
|
||||
let derived_data = ide_derived_data(cache_dir);
|
||||
let destination = destination(dir, params, &derived_data)?;
|
||||
config.args = clean_args(params, &destination, &derived_data).map_err(IdeError::invalid)?;
|
||||
config.command = "xcodebuild".into();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clean_args(
|
||||
params: &BTreeMap<String, String>,
|
||||
destination: &str,
|
||||
derived_data: &Path,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let mut args = build_args(params, Some(destination), derived_data)?;
|
||||
args.push("clean".into());
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// `xcodebuild -showBuildSettings -json` of the scheme as Xcode builds it: no destination and no
|
||||
/// `-derivedDataPath`, so the build folder is the one in Xcode's DerivedData location.
|
||||
fn settings_args(params: &BTreeMap<String, String>) -> Result<Vec<String>, String> {
|
||||
let param = |key: &str| params.get(key).map(|v| v.trim()).filter(|v| !v.is_empty());
|
||||
let container = param("container").ok_or("No Xcode project or workspace is set")?;
|
||||
let scheme = param("scheme").ok_or("No scheme is set")?;
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
let mut args = vec![flag.to_owned(), container.to_owned(), "-scheme".to_owned(), scheme.to_owned()];
|
||||
if let Some(configuration) = param("configuration") {
|
||||
args.extend(["-configuration".to_owned(), configuration.to_owned()]);
|
||||
}
|
||||
args.extend(["-showBuildSettings".to_owned(), "-json".to_owned()]);
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The project's `<Name>-<hash>` folder in Xcode's DerivedData: the ancestor of the build
|
||||
/// settings' `BUILD_DIR` (else `OBJROOT`) that sits directly in a `DerivedData` folder. `None`
|
||||
/// when the build folder is elsewhere (a custom DerivedData location or a legacy `build/`).
|
||||
pub fn derived_data_of(settings: &str) -> Option<PathBuf> {
|
||||
let json: serde_json::Value = serde_json::from_str(settings).ok()?;
|
||||
let build = json.as_array()?.iter().find_map(|t| {
|
||||
let s = &t["buildSettings"];
|
||||
s["BUILD_DIR"].as_str().or(s["OBJROOT"].as_str()).filter(|v| !v.is_empty())
|
||||
})?;
|
||||
Path::new(build)
|
||||
.ancestors()
|
||||
.find(|dir| dir.parent().and_then(Path::file_name).is_some_and(|name| name == "DerivedData"))
|
||||
.map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// The existing DerivedData folders of an `xcode` configuration's project: Xcode's
|
||||
/// `<Name>-<hash>` one (Xcode's own builds and the scheme's tests) and the IDE's runs' one.
|
||||
/// `dir` is the configuration's working directory.
|
||||
pub fn derived_data_dirs(dir: &Path, cache_dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<Vec<PathBuf>> {
|
||||
let args = settings_args(params).map_err(IdeError::invalid)?;
|
||||
let mut cmd = std::process::Command::new("xcodebuild");
|
||||
cmd.args(&args).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd)
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("Cannot run xcodebuild: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("xcodebuild {} failed:\n{}", args.join(" "), err.trim())));
|
||||
}
|
||||
let xcode = derived_data_of(&String::from_utf8_lossy(&out.stdout));
|
||||
Ok(xcode.into_iter().chain([ide_derived_data(cache_dir)]).filter(|d| d.is_dir()).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn params(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
|
||||
pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_cleans_the_build_a_run_makes() {
|
||||
let p = params(&[("container", "App.xcworkspace"), ("scheme", "App"), ("configuration", "Debug")]);
|
||||
assert_eq!(
|
||||
clean_args(&p, "id=UDID", Path::new("/cache/xcode/DerivedData")).unwrap(),
|
||||
[
|
||||
"-workspace",
|
||||
"App.xcworkspace",
|
||||
"-scheme",
|
||||
"App",
|
||||
"-configuration",
|
||||
"Debug",
|
||||
"-destination",
|
||||
"id=UDID",
|
||||
"-derivedDataPath",
|
||||
"/cache/xcode/DerivedData",
|
||||
"clean"
|
||||
]
|
||||
);
|
||||
assert_eq!(ide_derived_data(Path::new("/cache")), Path::new("/cache/xcode/DerivedData"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_settings_are_read_where_xcode_builds() {
|
||||
let p = params(&[("container", "App.xcodeproj"), ("scheme", "App")]);
|
||||
assert_eq!(
|
||||
settings_args(&p).unwrap(),
|
||||
["-project", "App.xcodeproj", "-scheme", "App", "-showBuildSettings", "-json"]
|
||||
);
|
||||
assert!(settings_args(¶ms(&[("container", "App.xcodeproj")])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_data_is_the_folder_in_derived_data_that_holds_the_build() {
|
||||
let settings = |key: &str, dir: &str| format!(r#"[{{"target":"App","buildSettings":{{"{key}":"{dir}"}}}}]"#);
|
||||
let dd = "/Users/me/Library/Developer/Xcode/DerivedData/App-abcdef";
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", &format!("{dd}/Build/Products"))), Some(dd.into()));
|
||||
assert_eq!(
|
||||
derived_data_of(&settings("OBJROOT", &format!("{dd}/Build/Intermediates.noindex"))),
|
||||
Some(dd.into())
|
||||
);
|
||||
// A custom location or a legacy build folder: nothing to delete.
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", "/Volumes/Builds/App-abcdef/Build/Products")), None);
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", "/src/App/build")), None);
|
||||
// The DerivedData folder itself is never the answer.
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", "/x/DerivedData")), None);
|
||||
assert_eq!(derived_data_of("not json"), None);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use crate::exec::{path_with, search_path, which};
|
||||
use crate::npm::{has_ts_api, native_typescript, own_typescript};
|
||||
use crate::{angular, astro, godot, pinned, vue};
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings};
|
||||
use ide_core::settings::{InspectionLevel, InspectionSettings, LanguageServerSettings, Settings, TsServerLog};
|
||||
use ide_core::version_managers::Tool;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_language::{LanguageConfig, LanguageServerConfig};
|
||||
@@ -1508,6 +1508,14 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
if name == "vtsls" && memory > 0 {
|
||||
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "maxTsServerMemory": memory } } }));
|
||||
}
|
||||
if name == "vtsls" {
|
||||
// Move to File asks the IDE for the target file (vtsls hides the action by default).
|
||||
merge_init_options(cfg, json!({ "vtsls": { "enableMoveToFileCodeAction": true } }));
|
||||
let log = s.languages.typescript.tsserver_log;
|
||||
if log != TsServerLog::Off {
|
||||
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "log": log } } }));
|
||||
}
|
||||
}
|
||||
if name == "vtsls"
|
||||
&& cfg.tsserver_project
|
||||
&& !server_root.ancestors().any(|d| d.join("tsconfig.json").is_file() || d.join("jsconfig.json").is_file())
|
||||
@@ -1654,6 +1662,20 @@ pub fn configure_css_modules(cfg: &mut LanguageServerConfig, server_root: &Path,
|
||||
true
|
||||
}
|
||||
|
||||
/// Registers `@styled/typescript-styled-plugin` (installed under `location`) as a vtsls global
|
||||
/// plugin when a package.json at, above or below `server_root` depends on styled-components or
|
||||
/// emotion (#6900). No-op elsewhere, and without the plugin (`None`).
|
||||
pub fn configure_styled(cfg: &mut LanguageServerConfig, server_root: &Path, location: Option<&Path>) -> bool {
|
||||
if cfg.name != "vtsls" || !cfg.tsserver_project {
|
||||
return false;
|
||||
}
|
||||
let Some(location) = location.filter(|_| crate::styled::used(server_root)) else {
|
||||
return false;
|
||||
};
|
||||
push_global_plugin(cfg, crate::styled::tsserver_plugin(location));
|
||||
true
|
||||
}
|
||||
|
||||
/// Adds `plugin` to vtsls' `globalPlugins`, replacing an entry of the same name.
|
||||
fn push_global_plugin(cfg: &mut LanguageServerConfig, plugin: Value) {
|
||||
insert_global_plugin(cfg, plugin, None);
|
||||
@@ -2764,6 +2786,22 @@ mod maven_linkage_tests {
|
||||
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vtsls_offers_move_to_file_and_logs_only_when_asked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
let options = |s: &Settings| {
|
||||
let mut cfg = custom_server("vtsls", &LanguageServerSettings::default());
|
||||
configure_server(&mut cfg, tmp.path(), tmp.path(), s);
|
||||
serde_json::to_value(cfg.initialization_options).unwrap()
|
||||
};
|
||||
let off = options(&s);
|
||||
assert_eq!(off.pointer("/vtsls/enableMoveToFileCodeAction"), Some(&json!(true)));
|
||||
assert!(off.pointer("/typescript/tsserver/log").is_none());
|
||||
s.languages.typescript.tsserver_log = TsServerLog::Verbose;
|
||||
assert_eq!(options(&s).pointer("/typescript/tsserver/log"), Some(&json!("verbose")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vtsls_probes_the_tsconfig_plugins_but_not_its_global_ones() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -15,21 +15,22 @@ pub(crate) fn enabled(server_root: &Path) -> bool {
|
||||
if ide_language::marked_root(None, server_root, &markers).is_some() {
|
||||
return true;
|
||||
}
|
||||
// ponytail: bounded walk, as for the path aliases; deeper workspace members go without.
|
||||
files_below(server_root, "tsconfig.json")
|
||||
.any(|p| p.parent().is_some_and(|dir| ide_language::marked_root(Some(dir), dir, &markers).is_some()))
|
||||
}
|
||||
|
||||
/// The files named `name` in `root` and the packages below it, outside `node_modules`.
|
||||
pub(crate) fn files_below(root: &Path, name: &'static str) -> impl Iterator<Item = std::path::PathBuf> {
|
||||
// A bounded walk, as for the path aliases; deeper workspace members are not seen.
|
||||
const MAX_DEPTH: usize = 4;
|
||||
const MAX_ENTRIES: usize = 50_000;
|
||||
let mut walker = ignore::WalkBuilder::new(server_root);
|
||||
let mut walker = ignore::WalkBuilder::new(root);
|
||||
walker
|
||||
.max_depth(Some(MAX_DEPTH))
|
||||
.require_git(ide_core::ignored::inside_git_repo(server_root))
|
||||
.require_git(ide_core::ignored::inside_git_repo(root))
|
||||
.follow_links(false)
|
||||
.filter_entry(|e| e.file_name() != "node_modules");
|
||||
walker
|
||||
.build()
|
||||
.take(MAX_ENTRIES)
|
||||
.flatten()
|
||||
.filter(|e| e.file_name() == "tsconfig.json")
|
||||
.any(|e| e.path().parent().is_some_and(|dir| ide_language::marked_root(Some(dir), dir, &markers).is_some()))
|
||||
walker.build().take(MAX_ENTRIES).flatten().filter(move |e| e.file_name() == name).map(|e| e.into_path())
|
||||
}
|
||||
|
||||
/// vtsls `globalPlugins` entry of the plugin installed under `location` (the folder holding its
|
||||
|
||||
@@ -33,6 +33,7 @@ pub fn detect(kind: SdkKind, root: Option<&Path>) -> Vec<Sdk> {
|
||||
SdkKind::Zig => zig(),
|
||||
SdkKind::Dotnet => dotnet(),
|
||||
SdkKind::Flutter => crate::flutter::detect(),
|
||||
SdkKind::Xcode => xcode(),
|
||||
};
|
||||
if let Some(root) = root {
|
||||
pinned_first(&mut out, kind, root);
|
||||
@@ -54,7 +55,8 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
|
||||
| SdkKind::Rust
|
||||
| SdkKind::TypeScript
|
||||
| SdkKind::Dotnet
|
||||
| SdkKind::Flutter => None,
|
||||
| SdkKind::Flutter
|
||||
| SdkKind::Xcode => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1219,6 +1221,56 @@ fn zig() -> Vec<Sdk> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Xcodes in `/Applications` and `~/Applications` (any name: `Xcode-beta.app`, `Xcode_16.4.app`),
|
||||
/// for `languages.swift.xcode`; `path` is the `.app`.
|
||||
fn xcode() -> Vec<Sdk> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Vec::new();
|
||||
}
|
||||
let dirs = [Some(PathBuf::from("/Applications")), home_dir().map(|h| h.join("Applications"))];
|
||||
let mut apps: Vec<PathBuf> = dirs
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flat_map(|d| subdirs(&d))
|
||||
.filter(|app| app.extension() == Some(OsStr::new("app")))
|
||||
.filter(|app| app.join("Contents/Developer/usr/bin/xcodebuild").is_file())
|
||||
.collect();
|
||||
apps.sort();
|
||||
apps.into_iter()
|
||||
.map(|app| {
|
||||
let version = std::fs::read_to_string(app.join("Contents/version.plist"))
|
||||
.ok()
|
||||
.and_then(|plist| plist_string(&plist, "CFBundleShortVersionString"));
|
||||
let stem = app.file_stem().unwrap_or_default().to_string_lossy().into_owned();
|
||||
Sdk {
|
||||
name: match &version {
|
||||
Some(v) => format!("{stem} {v}"),
|
||||
None => stem,
|
||||
},
|
||||
path: app.clone().into(),
|
||||
version,
|
||||
source: "system".to_owned(),
|
||||
home: Some(app.join("Contents/Developer").into()),
|
||||
extra: None,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `<string>` after `<key>key</key>` of an XML property list.
|
||||
fn plist_string(plist: &str, key: &str) -> Option<String> {
|
||||
let rest = &plist[plist.find(&format!("<key>{key}</key>"))?..];
|
||||
let value = &rest[rest.find("<string>")? + "<string>".len()..];
|
||||
Some(value[..value.find("</string>")?].trim().to_owned()).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_xcodes_version_plist() {
|
||||
let plist = "<dict>\n\t<key>BuildVersion</key>\n\t<string>7</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>26.1</string>\n</dict>";
|
||||
assert_eq!(plist_string(plist, "CFBundleShortVersionString").as_deref(), Some("26.1"));
|
||||
assert_eq!(plist_string(plist, "CFBundleVersion"), None);
|
||||
}
|
||||
|
||||
/// The SDKs `dotnet --list-sdks` reports, newest first: only the `dotnet` that runs
|
||||
/// `dotnet new` can use them.
|
||||
fn dotnet() -> Vec<Sdk> {
|
||||
|
||||
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"java-usages",
|
||||
"1.19.0",
|
||||
"1.20.1",
|
||||
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ pub mod php;
|
||||
pub mod pinned;
|
||||
pub mod python;
|
||||
pub mod ruby;
|
||||
mod styled;
|
||||
mod tsconfig_plugins;
|
||||
mod vue;
|
||||
mod zig;
|
||||
@@ -65,6 +66,8 @@ pub enum SdkKind {
|
||||
Dotnet,
|
||||
/// Flutter SDK roots.
|
||||
Flutter,
|
||||
/// `Xcode.app` bundles.
|
||||
Xcode,
|
||||
}
|
||||
|
||||
/// One installed interpreter / toolchain.
|
||||
|
||||
@@ -506,7 +506,8 @@ fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationT
|
||||
let java = [".classpath", ".project"].iter().any(|f| root.join(f).is_file())
|
||||
|| idea_java_project(root)
|
||||
|| !s.languages.java.jdk.trim().is_empty()
|
||||
|| !s.project_structure.source_roots.is_empty();
|
||||
|| !s.project_structure.source_roots.is_empty()
|
||||
|| !s.project_structure.libraries.is_empty();
|
||||
if !java {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -521,11 +522,45 @@ fn jdk_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationT
|
||||
})
|
||||
}
|
||||
|
||||
/// The class roots of Project Structure library entry `entry`: `dir/*.jar` and `dir/**/*.jar` list the
|
||||
/// folder's jars, a folder holding jars (e.g. `WEB-INF/lib`) lists them all, anything else is itself.
|
||||
pub fn library_class_paths(root: &Path, entry: &str) -> Vec<PathBuf> {
|
||||
if let Some((base, recursive)) = ide_core::settings::split_jar_glob(entry) {
|
||||
return crate::apply::setting_path(root, base)
|
||||
.map(|dir| ide_core::settings::jar_files(&dir, recursive))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
let Some(path) = crate::apply::setting_path(root, entry.trim()) else { return Vec::new() };
|
||||
if path.is_dir() {
|
||||
let jars = ide_core::settings::jar_files(&path, true);
|
||||
if !jars.is_empty() {
|
||||
return jars;
|
||||
}
|
||||
}
|
||||
vec![path]
|
||||
}
|
||||
|
||||
fn project_structure_groups(root: &Path, s: &Settings) -> Vec<LibraryGroup> {
|
||||
let mut out = Vec::new();
|
||||
let push_archive = |roots: &mut Vec<LibraryRoot>, path: &Path| {
|
||||
let label =
|
||||
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
|
||||
roots.push(LibraryRoot { name: label, path: ide_vfs::archive_root(path).into() });
|
||||
};
|
||||
for lib in &s.project_structure.libraries {
|
||||
let mut roots = Vec::new();
|
||||
for entry in lib.classes.iter().chain(&lib.sources) {
|
||||
for path in lib.classes.iter().flat_map(|entry| library_class_paths(root, entry)) {
|
||||
if path.is_file() {
|
||||
push_archive(&mut roots, &path);
|
||||
} else if path.is_dir() {
|
||||
let label = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| path.display().to_string());
|
||||
roots.push(LibraryRoot { name: label, path: path.into() });
|
||||
}
|
||||
}
|
||||
for entry in &lib.sources {
|
||||
let Some(path) = crate::apply::setting_path(root, entry) else { continue };
|
||||
let label = path
|
||||
.file_name()
|
||||
|
||||
@@ -64,16 +64,25 @@ pub enum ComposerInstall {
|
||||
Outdated,
|
||||
}
|
||||
|
||||
/// The Composer project `file` belongs to (the nearest `composer.json` at or below `root`), and
|
||||
/// whether its dependencies need `composer install`.
|
||||
/// Whether the nearest enclosing Composer project needs `composer install`. A manifest inside
|
||||
/// that project's vendor directory belongs to an installed package.
|
||||
pub fn composer_install(file: &Path, root: &Path) -> Option<(PathBuf, ComposerInstall)> {
|
||||
let dir = file.ancestors().filter(|d| d.starts_with(root)).find(|d| d.join("composer.json").is_file())?;
|
||||
let composer: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("composer.json")).ok()?).ok()?;
|
||||
let vendor = dir.join(composer.pointer("/config/vendor-dir").and_then(Value::as_str).unwrap_or("vendor"));
|
||||
let read = |path: PathBuf| std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
|
||||
let ancestors: Vec<_> = file.ancestors().take_while(|dir| dir.starts_with(root)).collect();
|
||||
let mut project = None;
|
||||
for dir in ancestors.into_iter().rev() {
|
||||
let Some(composer) = read(dir.join("composer.json")) else { continue };
|
||||
let vendor = dir.join(composer.pointer("/config/vendor-dir").and_then(Value::as_str).unwrap_or("vendor"));
|
||||
let in_vendor = file.starts_with(&vendor);
|
||||
project = Some((dir, vendor));
|
||||
if in_vendor {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (dir, vendor) = project?;
|
||||
if !vendor.join("autoload.php").is_file() {
|
||||
return Some((dir.to_path_buf(), ComposerInstall::Missing));
|
||||
}
|
||||
let read = |path: PathBuf| std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok());
|
||||
let lock = read(dir.join("composer.lock"))?;
|
||||
let installed = read(vendor.join("composer/installed.json")).unwrap_or(Value::Null);
|
||||
// Composer 2 writes `{"packages": [...], "dev": bool}`, Composer 1 the list itself.
|
||||
@@ -352,6 +361,32 @@ mod tests {
|
||||
assert_eq!(composer_install(&root.join("other.php"), root), None, "outside the Composer project");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_install_checks_the_owning_project_for_vendor_files() {
|
||||
for (vendor, manifest) in [("vendor", "{}"), ("deps", r#"{"config":{"vendor-dir":"deps"}}"#)] {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let vendor = root.join(vendor);
|
||||
let package = vendor.join("symfony/console");
|
||||
let nested = root.join("apps/console");
|
||||
for dir in [&package, &nested, &vendor.join("composer")] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("composer.json"), manifest).unwrap();
|
||||
std::fs::write(package.join("composer.json"), "{}").unwrap();
|
||||
std::fs::write(nested.join("composer.json"), "{}").unwrap();
|
||||
let file = package.join("Application.php");
|
||||
assert_eq!(composer_install(&file, root), Some((root.to_path_buf(), ComposerInstall::Missing)));
|
||||
|
||||
std::fs::write(vendor.join("autoload.php"), "<?php").unwrap();
|
||||
let packages = r#"{"packages":[{"name":"symfony/console","version":"v7.4.0"}]}"#;
|
||||
std::fs::write(root.join("composer.lock"), packages).unwrap();
|
||||
std::fs::write(vendor.join("composer/installed.json"), packages).unwrap();
|
||||
assert_eq!(composer_install(&file, root), None);
|
||||
assert_eq!(composer_install(&nested.join("Command.php"), root), Some((nested, ComposerInstall::Missing)));
|
||||
}
|
||||
}
|
||||
|
||||
fn level(composer: Option<&str>, explicit: &str) -> Option<String> {
|
||||
levels(composer, explicit).0.map(|l| l.version)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//! `@styled/typescript-styled-plugin`: the tsserver plugin vtsls loads for CSS completion, hover
|
||||
//! and diagnostics inside styled-components and emotion template literals (#6900). It matches
|
||||
//! templates by tag name (`styled`, `css`, `createGlobalStyle`, `keyframes`, `injectGlobal`).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The package (and tsserver plugin name) the IDE installs as the `typescript-styled-plugin` tool.
|
||||
pub(crate) const PLUGIN: &str = "@styled/typescript-styled-plugin";
|
||||
/// The CSS-in-JS libraries whose templates the plugin understands.
|
||||
const LIBRARIES: &[&str] = &["styled-components", "@emotion/styled", "@emotion/react", "@emotion/css"];
|
||||
|
||||
fn depends(manifest: &Path) -> bool {
|
||||
std::fs::read_to_string(manifest)
|
||||
.is_ok_and(|text| crate::libraries::package_dependencies(&text).iter().any(|d| LIBRARIES.contains(&d.as_str())))
|
||||
}
|
||||
|
||||
/// A package.json at `server_root`, above it, or in a package below it depends on one of them.
|
||||
pub(crate) fn used(server_root: &Path) -> bool {
|
||||
server_root.ancestors().any(|dir| depends(&dir.join("package.json")))
|
||||
|| crate::css_modules::files_below(server_root, "package.json").any(|p| depends(&p))
|
||||
}
|
||||
|
||||
/// vtsls `globalPlugins` entry of the plugin installed under `location` (the folder holding its
|
||||
/// `node_modules`).
|
||||
pub(crate) fn tsserver_plugin(location: &Path) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"name": PLUGIN,
|
||||
"location": location.to_string_lossy(),
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_package_depending_on_styled_components_or_emotion_turns_it_on() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = &dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("apps/web/node_modules/dep")).unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "react": "^19.0.0" } }"#).unwrap();
|
||||
let styled = r#"{ "dependencies": { "styled-components": "^6.1.0" } }"#;
|
||||
std::fs::write(root.join("apps/web/node_modules/dep/package.json"), styled).unwrap();
|
||||
assert!(!used(root), "dependencies don't count");
|
||||
std::fs::write(root.join("apps/web/package.json"), styled).unwrap();
|
||||
assert!(used(root), "a package below the server root");
|
||||
assert!(used(&root.join("apps/web/src")), "the package.json above");
|
||||
std::fs::write(root.join("apps/web/package.json"), r#"{ "devDependencies": { "@emotion/react": "^11" } }"#)
|
||||
.unwrap();
|
||||
assert!(used(root), "emotion");
|
||||
std::fs::write(root.join("apps/web/package.json"), r#"{ "dependencies": { "@emotion/cache": "^11" } }"#)
|
||||
.unwrap();
|
||||
assert!(!used(root));
|
||||
}
|
||||
}
|
||||
@@ -3655,6 +3655,22 @@ fn project_structure_module_jdk_language_level_and_external_libraries() {
|
||||
});
|
||||
let groups = crate::libraries::project_libraries(root, &settings, &[]);
|
||||
assert!(groups.iter().any(|g| g.name == "servlet-api" && g.kind == "library" && g.roots.len() == 1));
|
||||
|
||||
let web_lib = root.join("WebRoot/WEB-INF/lib");
|
||||
std::fs::create_dir_all(&web_lib).unwrap();
|
||||
std::fs::write(web_lib.join("a.jar"), b"").unwrap();
|
||||
std::fs::write(web_lib.join("b.jar"), b"").unwrap();
|
||||
settings.project_structure.libraries.push(ide_core::settings::ProjectLibrary {
|
||||
name: "web-lib".into(),
|
||||
classes: vec!["WebRoot/WEB-INF/lib".into()],
|
||||
sources: vec![],
|
||||
javadocs: vec![],
|
||||
scope: ide_core::settings::DependencyScope::Runtime,
|
||||
});
|
||||
let groups = crate::libraries::project_libraries(root, &settings, &[]);
|
||||
let web = groups.iter().find(|g| g.name == "web-lib" && g.kind == "library").unwrap();
|
||||
let names: Vec<&str> = web.roots.iter().map(|r| r.name.as_str()).collect();
|
||||
assert_eq!(names, vec!["a.jar", "b.jar"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -4037,3 +4053,55 @@ fn css_modules_kit_stays_the_ides_copy_when_the_project_declares_or_installs_it(
|
||||
assert!(location.join("node_modules/project-plugin").exists());
|
||||
assert!(!location.join("node_modules/@css-modules-kit").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vtsls_gets_the_styled_plugin_where_a_package_uses_styled_components_or_emotion() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, tools) = (tmp.path().join("app"), tmp.path().join("tools"));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "react": "^19.0.0" } }"#).unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
cfg.tsserver_project = true;
|
||||
assert!(!crate::apply::configure_styled(&mut cfg, &root, Some(&tools)), "no CSS-in-JS library");
|
||||
assert!(cfg.initialization_options.is_none());
|
||||
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "@emotion/styled": "^11.14.0" } }"#).unwrap();
|
||||
assert!(!crate::apply::configure_styled(&mut cfg, &root, None), "plugin not installed");
|
||||
let mut native = server("vtsls");
|
||||
assert!(!crate::apply::configure_styled(&mut native, &root, Some(&tools)), "TypeScript 7 hosts no plugins");
|
||||
for _ in 0..2 {
|
||||
assert!(crate::apply::configure_styled(&mut cfg, &root, Some(&tools)));
|
||||
}
|
||||
let init = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
init.pointer("/vtsls/tsserver/globalPlugins").unwrap(),
|
||||
&serde_json::json!([{
|
||||
"name": "@styled/typescript-styled-plugin",
|
||||
"location": tools.to_string_lossy(),
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
}]),
|
||||
"once"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_styled_plugin_stays_one_ides_copy_when_the_tsconfig_declares_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, tools, data) = (tmp.path().join("app"), tmp.path().join("tools"), tmp.path().join("data"));
|
||||
std::fs::create_dir_all(root.join("node_modules/@styled/typescript-styled-plugin")).unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "styled-components": "^6.1.0" } }"#).unwrap();
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
r#"{ "compilerOptions": { "plugins": [{ "name": "@styled/typescript-styled-plugin" }] } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
cfg.tsserver_project = true;
|
||||
// In the host's order: the global plugins, then the tsconfig's.
|
||||
assert!(crate::apply::configure_styled(&mut cfg, &root, Some(&tools)));
|
||||
assert!(!crate::apply::configure_tsconfig_plugins(&mut cfg, &root, &data), "no probe location for it");
|
||||
let init = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
|
||||
let plugins = init.pointer("/vtsls/tsserver/globalPlugins").unwrap().as_array().unwrap();
|
||||
assert_eq!(plugins.len(), 1);
|
||||
assert_eq!(plugins[0]["location"], tools.to_string_lossy().as_ref());
|
||||
assert!(init.pointer("/typescript/tsserver/pluginPaths").is_none());
|
||||
}
|
||||
Loaded 100 of 480 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача