дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 14:22:34 +02:00
Порівняти коміти
29
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
c00016db8a | ||
|
|
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 |
No files matched your search
@@ -0,0 +1,104 @@
|
||||
name: Nightly
|
||||
|
||||
# Builds main every night, when it has moved since the last nightly, into a prerelease
|
||||
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
|
||||
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
|
||||
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
|
||||
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 18 * * *" # 02:00 Beijing
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: "Build even when main has not changed since the last nightly"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nightly
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
if: github.repository == 'l0ng-ai/openidea'
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
tag: ${{ steps.tag.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with: { ref: main, fetch-depth: 0 }
|
||||
- id: changed
|
||||
env:
|
||||
FORCE: ${{ inputs.force == true }}
|
||||
run: |
|
||||
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
|
||||
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
|
||||
echo "::notice::main has not changed since $last"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Version commit and tag
|
||||
id: tag
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
env:
|
||||
BUILD: ${{ github.run_number }}
|
||||
run: |
|
||||
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add -A
|
||||
git commit -q -m "chore: v$version"
|
||||
git tag "v$version"
|
||||
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
|
||||
git push origin "refs/tags/v$version"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
release:
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.tag != ''
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/release.yml
|
||||
with:
|
||||
tag: ${{ needs.prepare.outputs.tag }}
|
||||
nightly: true
|
||||
secrets: inherit
|
||||
|
||||
# Points the nightly channel at the new nightly and drops the old ones.
|
||||
channel:
|
||||
needs: [prepare, release]
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
TAG: ${{ needs.prepare.outputs.tag }}
|
||||
steps:
|
||||
- name: Nightly manifest
|
||||
run: |
|
||||
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
|
||||
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
|
||||
exit 0
|
||||
fi
|
||||
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
|
||||
if gh release view nightly >/dev/null 2>&1; then
|
||||
gh release edit nightly --notes "$notes"
|
||||
else
|
||||
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
|
||||
fi
|
||||
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
|
||||
- name: Drop old nightlies
|
||||
run: |
|
||||
gh release list --limit 200 --json tagName,createdAt \
|
||||
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
|
||||
while read -r old; do
|
||||
gh release delete "$old" --cleanup-tag --yes
|
||||
done
|
||||
@@ -7,17 +7,23 @@ on:
|
||||
tag:
|
||||
description: "Tag to release (e.g. v0.1.0); must already exist"
|
||||
required: true
|
||||
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
|
||||
# official plugins, the CNB mirror or the Homebrew cask.
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
nightly: { type: boolean, default: false }
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.event.inputs.tag || github.ref_name }}
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
TAG: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
TAG: ${{ inputs.tag || github.ref_name }}
|
||||
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
|
||||
|
||||
# The jobs that read a signing key or token, here and in the workflows called below, run in
|
||||
@@ -52,6 +58,8 @@ jobs:
|
||||
fi
|
||||
- id: release
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
env:
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
with:
|
||||
script: |
|
||||
const tag = process.env.TAG;
|
||||
@@ -63,8 +71,13 @@ jobs:
|
||||
core.setOutput("id", existing.id);
|
||||
return;
|
||||
}
|
||||
// Prereleases are skipped: the notes span stable release to stable release.
|
||||
const previous = releases.find((r) => !r.draft && !r.prerelease);
|
||||
// Prereleases are skipped: the notes span stable release to stable release. A
|
||||
// nightly's span from the newest published release, nightly or stable (not the
|
||||
// rolling `nightly` release, which only holds the channel's manifest).
|
||||
const nightly = process.env.NIGHTLY === "true";
|
||||
const previous = releases.find(
|
||||
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
|
||||
);
|
||||
const { data: notes } = await github.rest.repos.generateReleaseNotes({
|
||||
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
|
||||
});
|
||||
@@ -80,7 +93,7 @@ jobs:
|
||||
needs: create-release
|
||||
uses: ./.github/workflows/release-build.yml
|
||||
with:
|
||||
tag: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
tag: ${{ inputs.tag || github.ref_name }}
|
||||
release_id: ${{ needs.create-release.outputs.release_id }}
|
||||
secrets: inherit
|
||||
|
||||
@@ -102,10 +115,14 @@ jobs:
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
steps:
|
||||
- id: key
|
||||
run: |
|
||||
if [ -z "$SIGNING_KEY" ]; then
|
||||
if [ "$NIGHTLY" = true ]; then
|
||||
echo "a nightly does not publish the official plugins"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$SIGNING_KEY" ]; then
|
||||
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
@@ -178,13 +195,15 @@ jobs:
|
||||
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
|
||||
cnb-mirror:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
Створено
+50
-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",
|
||||
@@ -4702,7 +4702,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4732,7 +4732,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4751,7 +4751,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4776,7 +4776,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4798,7 +4798,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4812,7 +4812,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4832,7 +4832,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4858,7 +4858,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4874,7 +4874,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 +4900,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4921,7 +4921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4934,7 +4934,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4959,7 +4959,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4972,7 +4972,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4987,7 +4987,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -5001,7 +5001,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -5014,7 +5014,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -5041,7 +5041,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5063,7 +5063,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5090,7 +5090,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5106,7 +5106,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6754,7 +6754,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.55"
|
||||
version = "0.1.56"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+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"
|
||||
|
||||
@@ -614,6 +614,15 @@ 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.
|
||||
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).is_absolute() && !Path::new(path).exists()
|
||||
}
|
||||
|
||||
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
|
||||
pub(crate) fn frame_from(f: &Value) -> StackFrame {
|
||||
let source = f.get("source");
|
||||
@@ -626,7 +635,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,
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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);
|
||||
@@ -825,6 +811,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 +1298,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()];
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2429,6 +2445,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::*;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -3027,6 +3027,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.
|
||||
|
||||
@@ -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"))));
|
||||
|
||||
@@ -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;
|
||||
@@ -771,6 +773,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)> {
|
||||
|
||||
@@ -327,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(),
|
||||
@@ -1793,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
|
||||
@@ -4677,6 +4720,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::*;
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -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"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -311,6 +311,22 @@ fn network_args(r: &Repo) -> Vec<String> {
|
||||
NETWORK_STAT_CONFIG.iter().flat_map(|(key, value)| ["-c".to_owned(), format!("{key}={value}")]).collect()
|
||||
}
|
||||
|
||||
/// Runs `git status`; when rename detection needs a blob that cannot be fetched (Restricted Mode
|
||||
/// sets `GIT_NO_LAZY_FETCH`, or the promisor remote is unreachable), retries once without it.
|
||||
/// The message is stable because `cli::command` pins `LC_ALL=C`.
|
||||
fn run_status(r: &Repo, mut args: Vec<&str>) -> IdeResult<crate::cli::Output> {
|
||||
let out = crate::cli::run_raw_env(r.root(), &args, None, &read_only())?;
|
||||
if out.code == Some(0) {
|
||||
return Ok(out);
|
||||
}
|
||||
if String::from_utf8_lossy(&out.stderr).contains("promisor remote") {
|
||||
let at = args.iter().position(|a| *a == "status").map_or(args.len(), |i| i + 1);
|
||||
args.insert(at, "--no-renames");
|
||||
return crate::cli::run_env(r.root(), &args, None, &read_only());
|
||||
}
|
||||
Err(crate::cli::failure(&args, &out.stderr, &out.stdout, out.code))
|
||||
}
|
||||
|
||||
/// `git status --porcelain=v2`: what git lists, unreadable directories skipped.
|
||||
/// In Restricted Mode git compares content without the repository's clean/process
|
||||
/// filters and doesn't ask submodules for their own status (which runs their config).
|
||||
@@ -323,7 +339,7 @@ fn cli_status(r: &Repo, ignored: &IgnoredNames) -> IdeResult<Entries> {
|
||||
if !crate::execution_allowed() {
|
||||
args.push("--ignore-submodules=dirty");
|
||||
}
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
let out = run_status(r, args)?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
@@ -340,7 +356,7 @@ fn cli_status_paths(r: &Repo, ignored: &IgnoredNames, paths: &[String]) -> IdeRe
|
||||
}
|
||||
args.push("--");
|
||||
args.extend(paths.iter().map(String::as_str));
|
||||
let out = crate::cli::run_env(r.root(), &args, None, &read_only())?;
|
||||
let out = run_status(r, args)?;
|
||||
Ok(parse_porcelain_v2(&String::from_utf8_lossy(&out.stdout), ignored))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Partial clones (`--filter=blob:none`) with a sparse checkout: blobs outside the
|
||||
//! checkout are never fetched, and gitoxide's status cannot read them.
|
||||
|
||||
use ide_vcs::{ChangeKind, LogQuery, Repos};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
let out = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "init.defaultBranch=main", "-c", "core.autocrlf=false", "-c", "protocol.file.allow=always"])
|
||||
.args(args)
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.output()
|
||||
.expect("git runs");
|
||||
assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
}
|
||||
|
||||
fn git_available() -> bool {
|
||||
Command::new("git").arg("--version").output().is_ok_and(|o| o.status.success())
|
||||
}
|
||||
|
||||
fn file_url(path: &Path) -> String {
|
||||
let path = path.to_string_lossy().replace('\\', "/");
|
||||
format!("file:///{}", path.trim_start_matches('/'))
|
||||
}
|
||||
|
||||
/// A blobless, cone-mode sparse clone of a small source repository; `docs/` and `app/` blobs stay remote.
|
||||
fn blobless_clone(base: &Path) -> std::path::PathBuf {
|
||||
let source = base.join("source");
|
||||
std::fs::create_dir_all(source.join("docs")).unwrap();
|
||||
std::fs::create_dir_all(source.join("app")).unwrap();
|
||||
git(&source, &["init", "-q"]);
|
||||
git(&source, &["config", "user.name", "Test User"]);
|
||||
git(&source, &["config", "user.email", "[email protected]"]);
|
||||
git(&source, &["config", "commit.gpgsign", "false"]);
|
||||
std::fs::write(source.join("README.md"), "hello\n").unwrap();
|
||||
let guide: String = (1..=200).map(|i| format!("line {i}\n")).collect();
|
||||
std::fs::write(source.join("docs/guide.txt"), &guide).unwrap();
|
||||
std::fs::write(source.join("app/main.rs"), "fn main() {}\n").unwrap();
|
||||
git(&source, &["add", "-A"]);
|
||||
git(&source, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let bare = base.join("bare.git");
|
||||
git(base, &["clone", "-q", "--bare", "source", "bare.git"]);
|
||||
git(&bare, &["config", "uploadpack.allowFilter", "true"]);
|
||||
git(&bare, &["config", "uploadpack.allowAnySHA1InWant", "true"]);
|
||||
|
||||
let work = base.join("work");
|
||||
git(base, &["clone", "-q", "--filter=blob:none", "--sparse", &file_url(&bare), "work"]);
|
||||
git(&work, &["config", "user.name", "Test User"]);
|
||||
git(&work, &["config", "user.email", "[email protected]"]);
|
||||
// A global `status.renames=false` would make the baseline pass without the fix.
|
||||
git(&work, &["config", "status.renames", "true"]);
|
||||
assert!(!work.join("app/main.rs").exists(), "app/ is outside the sparse checkout");
|
||||
work
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blobless_sparse_clone_keeps_its_repository_and_status() {
|
||||
if !git_available() {
|
||||
eprintln!("git is not available; skipping");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let work = blobless_clone(&base);
|
||||
let bare = base.join("bare.git");
|
||||
|
||||
std::fs::write(work.join("README.md"), "hello\nchanged\n").unwrap();
|
||||
std::fs::write(work.join("new.txt"), "new\n").unwrap();
|
||||
// A staged deletion of a never-fetched blob plus a near-identical addition: rename
|
||||
// detection would have to fetch the missing blob (`git rm --sparse` needs git 2.35+).
|
||||
git(&work, &["rm", "-q", "--sparse", "docs/guide.txt"]);
|
||||
let renamed: String = (1..=199).map(|i| format!("line {i}\n")).collect();
|
||||
std::fs::write(work.join("guide2.txt"), renamed).unwrap();
|
||||
git(&work, &["add", "guide2.txt"]);
|
||||
|
||||
// The promisor remote is gone: status must not need it.
|
||||
std::fs::rename(&bare, base.join("gone.git")).unwrap();
|
||||
|
||||
let repos = Repos::discover(&work, &|_| false).unwrap();
|
||||
let repo = repos.primary().expect("the partial clone is a repository");
|
||||
assert_eq!(repo.root(), work);
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(repo.log(&LogQuery::default()).unwrap().len(), 1);
|
||||
|
||||
let status = repos.status().expect("status of a partial clone");
|
||||
let find = |rel: &str| status.iter().find(|f| f.rel_path == rel);
|
||||
let readme = find("README.md").expect("README.md listed");
|
||||
assert_eq!((readme.staged, readme.unstaged), (None, Some(ChangeKind::Modified)));
|
||||
let new = find("new.txt").expect("new.txt listed");
|
||||
assert_eq!(new.unstaged, Some(ChangeKind::Untracked));
|
||||
// Rename detection needs the never-fetched blob, so the retry without it lists an addition.
|
||||
let moved = find("guide2.txt").expect("guide2.txt listed");
|
||||
assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None));
|
||||
let removed = find("docs/guide.txt").expect("docs/guide.txt listed");
|
||||
assert_eq!(removed.staged, Some(ChangeKind::Deleted));
|
||||
// Skip-worktree entries outside the checkout are not missing files.
|
||||
assert!(find("app/main.rs").is_none(), "{status:?}");
|
||||
assert_eq!(status.len(), 4, "{status:?}");
|
||||
|
||||
// The watcher's scoped refresh (a trusted project's `git status` with a pathspec) retries the
|
||||
// same way.
|
||||
repo.set_execution_allowed(true);
|
||||
let scoped = repo.status_paths(&[work.join("guide2.txt"), work.join("docs/guide.txt")]).expect("scoped status");
|
||||
let find = |rel: &str| scoped.iter().find(|f| f.rel_path == rel);
|
||||
let moved = find("guide2.txt").expect("guide2.txt listed");
|
||||
assert_eq!((moved.staged, moved.renamed_from.as_deref()), (Some(ChangeKind::Added), None));
|
||||
assert_eq!(find("docs/guide.txt").expect("docs/guide.txt listed").staged, Some(ChangeKind::Deleted));
|
||||
assert_eq!(scoped.len(), 2, "{scoped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blobless_clone_still_detects_a_rename_between_local_blobs() {
|
||||
if !git_available() {
|
||||
eprintln!("git is not available; skipping");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let work = blobless_clone(&base);
|
||||
// README.md is inside the cone, so both sides of the rename are local blobs.
|
||||
git(&work, &["mv", "README.md", "README2.md"]);
|
||||
|
||||
let repos = Repos::discover(&work, &|_| false).unwrap();
|
||||
let repo = repos.primary().expect("the partial clone is a repository");
|
||||
let status = repos.status().expect("status of a partial clone");
|
||||
let moved = status.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed");
|
||||
assert_eq!(
|
||||
(moved.staged, moved.renamed_from.as_deref()),
|
||||
(Some(ChangeKind::Renamed), Some("README.md")),
|
||||
"{status:?}"
|
||||
);
|
||||
|
||||
repo.set_execution_allowed(true);
|
||||
let scoped = repo.status_paths(&[work.join("README2.md"), work.join("README.md")]).expect("scoped status");
|
||||
let moved = scoped.iter().find(|f| f.rel_path == "README2.md").expect("README2.md listed");
|
||||
assert_eq!(
|
||||
(moved.staged, moved.renamed_from.as_deref()),
|
||||
(Some(ChangeKind::Renamed), Some("README.md")),
|
||||
"{scoped:?}"
|
||||
);
|
||||
}
|
||||
@@ -99,7 +99,9 @@ impl FileMoves {
|
||||
|
||||
/// Applies `edit` (paths as before the move, as `workspace/willRenameFiles`
|
||||
/// returns them), then performs `moves`. Edited files are snapshotted in
|
||||
/// Local History first. On failure everything done so far is rolled back.
|
||||
/// Local History first. `apply_edit` must be transactional: on error it leaves none of
|
||||
/// its own changes behind, so a rejected edit keeps external changes. A failed
|
||||
/// file move rolls back the applied edits.
|
||||
/// Returns the id for [`undo`](Self::undo).
|
||||
pub fn perform(
|
||||
&self,
|
||||
@@ -134,11 +136,8 @@ impl FileMoves {
|
||||
}
|
||||
before.push(text);
|
||||
}
|
||||
if !paths.is_empty()
|
||||
&& let Err(e) = apply_edit(edit)
|
||||
{
|
||||
restore(documents, &paths, &before);
|
||||
return Err(e);
|
||||
if !paths.is_empty() {
|
||||
apply_edit(edit)?;
|
||||
}
|
||||
if let Err(e) = crate::file_ops::move_files(moves) {
|
||||
restore(documents, &paths, &before);
|
||||
@@ -305,6 +304,37 @@ mod tests {
|
||||
assert_eq!(fs::read_to_string(root.join("Use.java")).unwrap(), "Bar f; // edited\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_reference_edits_preserve_changes_after_the_snapshot() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
fs::write(root.join("source.ts"), "source\n").unwrap();
|
||||
fs::write(root.join("main.ts"), "old\n").unwrap();
|
||||
let docs = documents();
|
||||
let mut edit = WorkspaceEdit {
|
||||
files: vec![FileEdit::Edit {
|
||||
path: root.join("main.ts").into(),
|
||||
version: None,
|
||||
edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "updated".into() }],
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
docs.prepare_workspace_edit(&mut edit).unwrap();
|
||||
let apply_edit = |edit: &WorkspaceEdit| {
|
||||
// An external writer lands after perform captured its rollback text.
|
||||
fs::write(root.join("main.ts"), "external edit after snapshot\n").unwrap();
|
||||
docs.apply_file_move_edits(edit)
|
||||
};
|
||||
let moves = FileMoves::new();
|
||||
let mv = vec![FileMove { from: root.join("source.ts").into(), to: root.join("renamed.ts").into() }];
|
||||
let error = moves.perform(&docs, None, &mv, &edit, "Move", &apply_edit).unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::OutOfSync);
|
||||
assert_eq!(fs::read_to_string(root.join("main.ts")).unwrap(), "external edit after snapshot\n");
|
||||
assert_eq!(fs::read_to_string(root.join("source.ts")).unwrap(), "source\n");
|
||||
assert!(!root.join("renamed.ts").exists());
|
||||
assert_eq!(moves.last(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moved_paths() {
|
||||
let mv = vec![FileMove { from: "/p/a".into(), to: "/p/b/a".into() }];
|
||||
|
||||
@@ -242,3 +242,51 @@ for (const theme of ["dark", "light"] as const) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("a long agent form scrolls above the composer instead of being cut off", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1000, height: 520 });
|
||||
const fields = Array.from({ length: 5 }, (_, q) => ({
|
||||
name: `q${q + 1}`,
|
||||
title: `Question ${q + 1}`,
|
||||
kind: "choice" as const,
|
||||
required: true,
|
||||
options: Array.from({ length: 4 }, (_, o) => ({ value: `a${o + 1}`, label: `Answer ${q + 1}.${o + 1}` })),
|
||||
}));
|
||||
await page.evaluate(
|
||||
async ({ task, fields }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const store: typeof AgentStore = await import(storePath);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[{ type: "permission", id: 1, title: "Plan the change", options: [], chosen: null, form: { fields } }],
|
||||
],
|
||||
]),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, fields },
|
||||
);
|
||||
const card = page.getByRole("form", { name: "Plan the change" });
|
||||
await expect(card).toBeVisible();
|
||||
const composer = page.getByRole("textbox", { name: "Message", exact: true });
|
||||
await expect(composer).toBeInViewport();
|
||||
for (let q = 1; q <= 5; q++) {
|
||||
const last = card.getByRole("radio", { name: `Answer ${q}.4` });
|
||||
await last.scrollIntoViewIfNeeded();
|
||||
const box = (await last.boundingBox())!;
|
||||
const hit = await page.evaluate(
|
||||
({ x, y }) => document.elementFromPoint(x, y)?.closest("label")?.textContent ?? null,
|
||||
{ x: box.x + box.width / 2, y: box.y + box.height / 2 },
|
||||
);
|
||||
expect(hit).toContain(`Answer ${q}.4`);
|
||||
await last.check();
|
||||
}
|
||||
const submit = card.getByRole("button", { name: "Submit", exact: true });
|
||||
await submit.scrollIntoViewIfNeeded();
|
||||
await expect(submit).toBeInViewport({ ratio: 1 });
|
||||
await expect(submit).toBeEnabled();
|
||||
});
|
||||
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
|
||||
Bundle-ManifestVersion: 2
|
||||
Bundle-Name: OpenIDEA Java usages
|
||||
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
|
||||
Bundle-Version: 1.19.0
|
||||
Bundle-Version: 1.20.1
|
||||
Bundle-RequiredExecutionEnvironment: JavaSE-21
|
||||
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
|
||||
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
|
||||
|
||||
@@ -6,6 +6,10 @@ The app-owned OSGi command `openidea.java.usages` returns `{location, kind, acce
|
||||
`kind` retains field/getter/setter/unknown identity for compatibility. Optional
|
||||
`access` is read/write/readWrite/unknown. Missing access metadata is unknown;
|
||||
old servers and ordinary LSP locations remain visible under either filter.
|
||||
`openidea.java.methodReferenceDefinition(uri, line, column)` resolves the method name
|
||||
of a `Type::method` or `expr::method` reference through its AST binding and returns the
|
||||
declaring method's location. This keeps inherited methods on their parent declaration
|
||||
where JDT's selection-based definition may return the functional interface method.
|
||||
An absent or failing extension command uses standard LSP references, without access
|
||||
classification or toolbar controls. This includes errors during scope widening.
|
||||
The Rust bridge logs the failure once per project session. Cancelled requests and
|
||||
@@ -88,7 +92,7 @@ is not a claim of full IntelliJ feature parity.
|
||||
## Rebuild and delivery
|
||||
|
||||
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
|
||||
`java-usages-1.18.0.jar`, and added alongside existing initialization bundles.
|
||||
`java-usages-1.20.1.jar`, and added alongside existing initialization bundles.
|
||||
Users need no compiler, Maven or Python. Manifest/install version must change
|
||||
when replacing the bundle because OSGi caches bundles.
|
||||
|
||||
@@ -142,6 +146,10 @@ protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is
|
||||
Version 1.17.0 adds `openidea.java.exceptionType`, the exception class at a caret for the exception
|
||||
breakpoint intention; its reproducible SHA-256 is
|
||||
`d1c596b37dcb6bd402ad48b214fd2a7651dbd4472eeea49e2ce992ea2f1363e9`.
|
||||
Version 1.20.1 adds `openidea.java.methodReferenceDefinition`, which resolves inherited Java method
|
||||
references from their AST binding instead of JDT's selection result. Lombok-generated accessors
|
||||
without a source range fall back to their field or declaring type; its reproducible SHA-256 is
|
||||
`a111a9359b8f13dcd06e14e72fa287943cfe953325bff6f940912cae199caec7`.
|
||||
|
||||
```sh
|
||||
export PATH=/path/to/jdk25/bin:$PATH
|
||||
@@ -173,6 +181,7 @@ OPENIDEA_USAGES_INDEX_STRESS=1 python3 java/java-usages/tests/read-write.py /pat
|
||||
python3 java/java-usages/tests/hierarchy.py /path/to/jdtls
|
||||
python3 java/java-usages/tests/implementations.py /path/to/jdtls
|
||||
python3 java/java-usages/tests/exception-type.py /path/to/jdtls
|
||||
python3 java/java-usages/tests/method-reference.py /path/to/jdtls
|
||||
```
|
||||
|
||||
The harnesses select the JDT LS configuration for the current platform. The first
|
||||
|
||||
Бінарний файл не відображається.
@@ -27,6 +27,9 @@
|
||||
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
|
||||
<command id="openidea.java.implementationLocations"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.navigation.MethodReferenceDefinitionCommand">
|
||||
<command id="openidea.java.methodReferenceDefinition"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.hierarchy.HierarchyCommand">
|
||||
<command id="openidea.java.hierarchy.members"/>
|
||||
<command id="openidea.java.hierarchy.refactor"/>
|
||||
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package ai.openidea.navigation;
|
||||
|
||||
import ai.openidea.Documents;
|
||||
import java.util.List;
|
||||
import org.eclipse.core.runtime.IProgressMonitor;
|
||||
import org.eclipse.jdt.core.IField;
|
||||
import org.eclipse.jdt.core.IMember;
|
||||
import org.eclipse.jdt.core.IMethod;
|
||||
import org.eclipse.jdt.core.IType;
|
||||
import org.eclipse.jdt.core.ITypeRoot;
|
||||
import org.eclipse.jdt.core.dom.ASTNode;
|
||||
import org.eclipse.jdt.core.dom.CompilationUnit;
|
||||
import org.eclipse.jdt.core.dom.ExpressionMethodReference;
|
||||
import org.eclipse.jdt.core.dom.IMethodBinding;
|
||||
import org.eclipse.jdt.core.dom.ITypeBinding;
|
||||
import org.eclipse.jdt.core.dom.MethodReference;
|
||||
import org.eclipse.jdt.core.dom.NodeFinder;
|
||||
import org.eclipse.jdt.core.dom.SimpleName;
|
||||
import org.eclipse.jdt.core.dom.SuperMethodReference;
|
||||
import org.eclipse.jdt.core.dom.TypeMethodReference;
|
||||
import org.eclipse.jdt.core.manipulation.CoreASTProvider;
|
||||
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
|
||||
import org.eclipse.jdt.ls.core.internal.JDTUtils;
|
||||
import org.eclipse.jdt.ls.core.internal.handlers.JsonRpcHelpers;
|
||||
import org.eclipse.lsp4j.Location;
|
||||
|
||||
/**
|
||||
* Resolves a method reference (for example {@code Child::getGoodsSpace}) to the declaration
|
||||
* of the referenced method. JDT's selection-based definition request can return the
|
||||
* functional interface method ({@code Function.apply}) when the method is inherited;
|
||||
* bindings retain the actual method identity instead.
|
||||
*/
|
||||
public final class MethodReferenceDefinitionCommand implements IDelegateCommandHandler {
|
||||
@Override
|
||||
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
|
||||
Documents.awaitChanges(monitor);
|
||||
String uri = (String) arguments.get(0);
|
||||
int line = ((Number) arguments.get(1)).intValue();
|
||||
int column = ((Number) arguments.get(2)).intValue();
|
||||
ITypeRoot root = JDTUtils.resolveTypeRoot(uri);
|
||||
if (root == null || !root.exists()) return List.of();
|
||||
CompilationUnit ast = CoreASTProvider.getInstance().getAST(root, CoreASTProvider.WAIT_YES, monitor);
|
||||
if (ast == null) return List.of();
|
||||
int offset = JsonRpcHelpers.toOffset(root, line, column);
|
||||
if (offset < 0) return List.of();
|
||||
|
||||
MethodReference reference = enclosingReference(ast, offset);
|
||||
if (reference == null) return List.of();
|
||||
SimpleName name = methodName(reference);
|
||||
if (name == null) return List.of();
|
||||
int start = name.getStartPosition();
|
||||
if (offset < start || offset > start + name.getLength()) return List.of();
|
||||
|
||||
IMethodBinding binding = reference.resolveMethodBinding();
|
||||
if (binding == null) return List.of();
|
||||
IMethodBinding declaration = binding.getMethodDeclaration();
|
||||
if (declaration == null) return List.of();
|
||||
Location location = locationOf(declaration);
|
||||
return location == null ? List.of() : List.of(location);
|
||||
}
|
||||
|
||||
/**
|
||||
* The declaration's source location. Lombok-generated accessors have a binding and a Java
|
||||
* element but no source range; then the field the accessor reads (or the declaring type)
|
||||
* is the closest source declaration. Without this fallback the standard definition request
|
||||
* stays at the functional interface method.
|
||||
*/
|
||||
private static Location locationOf(IMethodBinding declaration) throws Exception {
|
||||
var element = declaration.getJavaElement();
|
||||
Location location = element == null ? null : JDTUtils.toLocation(element);
|
||||
if (location != null) return location;
|
||||
if (element instanceof IMember member && member.getClassFile() != null)
|
||||
return JDTUtils.toLocation(member.getClassFile());
|
||||
|
||||
ITypeBinding owner = declaration.getDeclaringClass();
|
||||
if (owner == null) return null;
|
||||
var ownerElement = owner.getJavaElement();
|
||||
if (!(ownerElement instanceof IType type) || !type.exists()) return null;
|
||||
|
||||
for (IMethod method : type.getMethods()) {
|
||||
if (!method.getElementName().equals(declaration.getName())) continue;
|
||||
if (method.getNumberOfParameters() != declaration.getParameterTypes().length) continue;
|
||||
location = JDTUtils.toLocation(method);
|
||||
if (location != null) return location;
|
||||
}
|
||||
|
||||
String fieldName = propertyName(declaration.getName());
|
||||
if (fieldName != null) {
|
||||
IField field = type.getField(fieldName);
|
||||
if (field.exists()) {
|
||||
location = JDTUtils.toLocation(field);
|
||||
if (location != null) return location;
|
||||
}
|
||||
}
|
||||
return JDTUtils.toLocation(type);
|
||||
}
|
||||
|
||||
/** The field name of a bean accessor (`getUpdateTime` / `setUpdateTime` / `isEnabled`). */
|
||||
private static String propertyName(String methodName) {
|
||||
String rest;
|
||||
if (methodName.startsWith("get") || methodName.startsWith("set")) {
|
||||
rest = methodName.substring(3);
|
||||
} else if (methodName.startsWith("is")) {
|
||||
rest = methodName.substring(2);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
if (rest.isEmpty()) return null;
|
||||
if (rest.length() > 1 && Character.isUpperCase(rest.charAt(0)) && Character.isUpperCase(rest.charAt(1))) {
|
||||
return rest;
|
||||
}
|
||||
return Character.toLowerCase(rest.charAt(0)) + rest.substring(1);
|
||||
}
|
||||
|
||||
private static MethodReference enclosingReference(CompilationUnit ast, int offset) {
|
||||
ASTNode leaf = new NodeFinder(ast, offset, 1).getCoveringNode();
|
||||
for (ASTNode node = leaf; node != null; node = node.getParent()) {
|
||||
if (node instanceof MethodReference reference) return reference;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static SimpleName methodName(MethodReference reference) {
|
||||
return switch (reference) {
|
||||
case TypeMethodReference type -> type.getName();
|
||||
case ExpressionMethodReference expression -> expression.getName();
|
||||
case SuperMethodReference superReference -> superReference.getName();
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Go to Definition on a method reference, against a real JDT LS. Arguments: jdtls home, optional bundle jar.
|
||||
|
||||
Each case puts the caret on a method reference's name and checks that
|
||||
`openidea.java.methodReferenceDefinition` answers the referenced method's declaration (an inherited
|
||||
method on its parent, not the functional interface method), and nothing elsewhere.
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import platform
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
home = pathlib.Path(sys.argv[1]).resolve()
|
||||
bundle = pathlib.Path(sys.argv[2]).resolve() if len(sys.argv) > 2 else pathlib.Path(__file__).resolve().parents[1] / 'openidea-java-usages.jar'
|
||||
work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-method-reference-'))
|
||||
config = work / 'config'
|
||||
config.mkdir()
|
||||
system, machine = platform.system(), platform.machine().lower()
|
||||
config_name = {'Windows': 'config_win', 'Darwin': 'config_mac'}.get(system, 'config_linux')
|
||||
config_names = ([config_name + '_arm'] if machine in ('arm64', 'aarch64') else []) + [config_name]
|
||||
config_source = next(home / name / 'config.ini' for name in config_names if (home / name / 'config.ini').is_file())
|
||||
(config / 'config.ini').write_bytes(config_source.read_bytes())
|
||||
project = work / 'project'
|
||||
(project / 'src/app').mkdir(parents=True)
|
||||
(project / '.project').write_text('<projectDescription><name>app</name><buildSpec><buildCommand><name>org.eclipse.jdt.core.javabuilder</name></buildCommand></buildSpec><natures><nature>org.eclipse.jdt.core.javanature</nature></natures></projectDescription>')
|
||||
(project / '.classpath').write_text('<classpath><classpathentry kind="src" path="src"/><classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/><classpathentry kind="output" path="bin"/></classpath>')
|
||||
sources = {
|
||||
'Parent.java': '''package app;
|
||||
|
||||
public class Parent {
|
||||
public String getGoodsSpace() {
|
||||
return "space";
|
||||
}
|
||||
|
||||
public static String describe(Object o) {
|
||||
return String.valueOf(o);
|
||||
}
|
||||
}
|
||||
''',
|
||||
'Child.java': '''package app;
|
||||
|
||||
public class Child extends Parent {
|
||||
public int own() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
''',
|
||||
'Main.java': '''package app;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
public class Main {
|
||||
void run(List<Child> children) {
|
||||
Function<Child, String> inherited = Child::getGoodsSpace;
|
||||
Function<Child, Integer> own = Child::own;
|
||||
Function<Object, String> statics = Child::describe;
|
||||
children.forEach(System.out::println);
|
||||
String plain = new Child().getGoodsSpace();
|
||||
}
|
||||
}
|
||||
''',
|
||||
}
|
||||
for name, text in sources.items():
|
||||
(project / 'src/app' / name).write_text(text)
|
||||
uri = lambda name: (project / 'src/app' / name).as_uri()
|
||||
|
||||
log = (work / 'stderr.log').open('w')
|
||||
proc = subprocess.Popen(['java', '-Declipse.application=org.eclipse.jdt.ls.core.id1', '-Dosgi.bundles.defaultStartLevel=4', '-Declipse.product=org.eclipse.jdt.ls.core.product', '-Xmx1G', '--add-modules=ALL-SYSTEM', '--add-opens', 'java.base/java.util=ALL-UNNAMED', '--add-opens', 'java.base/java.lang=ALL-UNNAMED', '-jar', str(next((home / 'plugins').glob('org.eclipse.equinox.launcher_*.jar'))), '-configuration', str(config), '-data', str(work / 'metadata')], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log)
|
||||
messages = queue.Queue()
|
||||
lock = threading.Lock()
|
||||
|
||||
|
||||
def send(message):
|
||||
data = json.dumps(message).encode()
|
||||
with lock:
|
||||
proc.stdin.write(f'Content-Length: {len(data)}\r\n\r\n'.encode() + data)
|
||||
proc.stdin.flush()
|
||||
|
||||
|
||||
def read():
|
||||
while True:
|
||||
headers = {}
|
||||
while True:
|
||||
line = proc.stdout.readline()
|
||||
if not line:
|
||||
return
|
||||
if line == b'\r\n':
|
||||
break
|
||||
k, v = line.decode().split(':', 1)
|
||||
headers[k.lower()] = v.strip()
|
||||
message = json.loads(proc.stdout.read(int(headers['content-length'])))
|
||||
if 'method' in message and 'id' in message:
|
||||
send({'jsonrpc': '2.0', 'id': message['id'], 'result': [] if message['method'] == 'workspace/configuration' else None})
|
||||
else:
|
||||
messages.put(message)
|
||||
|
||||
|
||||
threading.Thread(target=read, daemon=True).start()
|
||||
seq = 0
|
||||
|
||||
|
||||
def request(method, params):
|
||||
global seq
|
||||
seq += 1
|
||||
send({'jsonrpc': '2.0', 'id': seq, 'method': method, 'params': params})
|
||||
deadline = time.monotonic() + 180
|
||||
while time.monotonic() < deadline:
|
||||
msg = messages.get(timeout=max(1, deadline - time.monotonic()))
|
||||
if msg.get('id') == seq:
|
||||
if 'error' in msg:
|
||||
raise RuntimeError(msg['error'])
|
||||
return msg.get('result')
|
||||
raise TimeoutError(method)
|
||||
|
||||
|
||||
|
||||
|
||||
def where(loc):
|
||||
return (loc['uri'].rsplit('/', 1)[-1], loc['range']['start']['line'])
|
||||
|
||||
|
||||
def line_of(file, needle):
|
||||
return next(i for i, t in enumerate(sources[file].splitlines()) if needle in t)
|
||||
|
||||
|
||||
CASES = [
|
||||
('Child::getGoodsSpace', 'getGoodsSpace', 3, [('Parent.java', line_of('Parent.java', 'getGoodsSpace'))]),
|
||||
('Child::own', 'own', 1, [('Child.java', line_of('Child.java', 'own()'))]),
|
||||
('Child::describe', 'describe', 2, [('Parent.java', line_of('Parent.java', 'describe'))]),
|
||||
('Child::getGoodsSpace', 'Child', 2, []),
|
||||
('new Child().getGoodsSpace', 'getGoodsSpace', 2, []),
|
||||
]
|
||||
|
||||
try:
|
||||
init = request('initialize', {'processId': None, 'rootUri': project.as_uri(), 'workspaceFolders': [{'uri': project.as_uri(), 'name': 'app'}], 'capabilities': {}, 'initializationOptions': {'bundles': [str(bundle)], 'settings': {'java': {'import': {'gradle': {'enabled': False}, 'maven': {'enabled': False}}}}}})
|
||||
commands = init['capabilities']['executeCommandProvider']['commands']
|
||||
assert 'openidea.java.methodReferenceDefinition' in commands, commands
|
||||
send({'jsonrpc': '2.0', 'method': 'initialized', 'params': {}})
|
||||
for name, text in sources.items():
|
||||
send({'jsonrpc': '2.0', 'method': 'textDocument/didOpen', 'params': {'textDocument': {'uri': uri(name), 'languageId': 'java', 'version': 1, 'text': text}}})
|
||||
request('java/buildWorkspace', True)
|
||||
failed = []
|
||||
lines = sources['Main.java'].splitlines()
|
||||
for line_needle, needle, at, expected in CASES:
|
||||
line = next(i for i, t in enumerate(lines) if line_needle in t)
|
||||
column = lines[line].index(needle, lines[line].index(line_needle)) + at
|
||||
got = request('workspace/executeCommand', {'command': 'openidea.java.methodReferenceDefinition', 'arguments': [uri('Main.java'), line, column]})
|
||||
got = [where(l) for l in got or []]
|
||||
ok = got == expected
|
||||
if not ok:
|
||||
failed.append((line_needle, needle))
|
||||
print('OK' if ok else 'FAIL', repr(line_needle), 'at', repr(needle), got)
|
||||
# The functional interface's method is what the standard request answers for the inherited case.
|
||||
line = next(i for i, t in enumerate(lines) if 'Child::getGoodsSpace' in t)
|
||||
std = request('textDocument/definition', {'textDocument': {'uri': uri('Main.java')}, 'position': {'line': line, 'character': lines[line].index('getGoodsSpace') + 3}})
|
||||
print('standard definition:', std)
|
||||
assert not failed, failed
|
||||
print('method-reference: all cases passed')
|
||||
finally:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=20)
|
||||
print('Evidence:', work, file=sys.stderr)
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.55",
|
||||
"version": "0.1.56",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
+1
-1
@@ -105,7 +105,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea-plugin-openidea-ai-completion"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
dependencies = [
|
||||
"openidea-plugin",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "openidea-plugin-openidea-ai-completion"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
fbaa75cf43cf1188b6b5f7621a94739a0f91ba4c8bd13b94fe78a2e8aa17bcc9
|
||||
385b624ee9593d759a2ce22d4427edc0f06954d0e98f458a77d780e5a3dbe92a
|
||||
@@ -1,10 +1,10 @@
|
||||
id = "openidea.ai-completion"
|
||||
name = "AI Completion"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
description = "Inline code suggestions (ghost text) from a local model (Ollama) or OpenAI, as you type."
|
||||
authors = ["OpenIDEA contributors"]
|
||||
license = "Apache-2.0"
|
||||
change-notes = "0.1.0 — first release: local (Ollama) and OpenAI backends; the key stays in the system keychain."
|
||||
change-notes = "0.1.1 — say why no suggestions appear (network access, missing model, Ollama not running) and choose the model with AI Completion: Set Model. 0.1.0 — first release: local (Ollama) and OpenAI backends; the key stays in the system keychain."
|
||||
categories = ["ai"]
|
||||
engines.openidea = "^1.0"
|
||||
wasm = "dist/plugin.wasm"
|
||||
@@ -43,3 +43,8 @@ category = "AI Completion"
|
||||
id = "set-endpoint"
|
||||
title = "AI Completion: Set Endpoint URL"
|
||||
category = "AI Completion"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "set-model"
|
||||
title = "AI Completion: Set Model"
|
||||
category = "AI Completion"
|
||||
@@ -22,6 +22,8 @@ const SUFFIX_CHARS: usize = 1000;
|
||||
pub struct AiCompletion {
|
||||
/// Why the last request failed, so it is logged once rather than per keystroke.
|
||||
last_error: Option<String>,
|
||||
/// The last failure shown to the user, so a notice is not repeated.
|
||||
last_notice: Option<String>,
|
||||
}
|
||||
|
||||
struct Config {
|
||||
@@ -48,6 +50,34 @@ fn config() -> Config {
|
||||
Config { endpoint, model, openai, enabled: get("enabled").as_deref() != Some("false") }
|
||||
}
|
||||
|
||||
/// What to tell the user about a failed request: why, and what to do.
|
||||
pub fn advice(endpoint: &str, model: &str, openai: bool, failure: &Result<String, Error>) -> String {
|
||||
match failure {
|
||||
Err(Error::Denied(_)) => format!(
|
||||
"AI Completion may not connect to {endpoint}. Allow its network access in Settings › Plugins › AI Completion."
|
||||
),
|
||||
Ok(text) if !openai && text.starts_with("HTTP 404") => format!(
|
||||
"The model {model} is not available at {endpoint}. Run `ollama pull {model}`, or choose an installed model with AI Completion: Set Model."
|
||||
),
|
||||
Err(Error::Failed(e)) if e.contains("timed out") => format!(
|
||||
"{endpoint} took too long to answer; the model may still be loading, or be too large for this machine."
|
||||
),
|
||||
Err(Error::Failed(e)) if !openai => format!("Could not reach Ollama at {endpoint} ({e}). Is it running?"),
|
||||
Ok(text) => format!("{endpoint} answered {text}"),
|
||||
Err(e) => format!("Could not reach {endpoint}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The command's argument, or what the user types (pre-filled with `current`);
|
||||
/// `None` when dismissed.
|
||||
fn arg_or_input(arg: Option<&str>, prompt: &str, current: &str) -> Result<Option<String>, Error> {
|
||||
let value = match arg {
|
||||
Some(a) => Some(a.to_owned()),
|
||||
None => host::input(prompt, Some(current))?,
|
||||
};
|
||||
Ok(value.map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()))
|
||||
}
|
||||
|
||||
/// The last `max` characters of `s` (on a char boundary).
|
||||
fn tail(s: &str, max: usize) -> &str {
|
||||
match s.char_indices().rev().nth(max.saturating_sub(1)) {
|
||||
@@ -112,14 +142,21 @@ impl Providers for AiCompletion {
|
||||
// Superseded by the next keystroke: nothing to report.
|
||||
Err(Error::Cancelled) => None,
|
||||
other => {
|
||||
let msg = match other {
|
||||
Ok(r) => format!("HTTP {}: {}", r.status, head(&r.text(), 200)),
|
||||
let failure = other.map(|r| format!("HTTP {}: {}", r.status, head(&r.text(), 200)));
|
||||
let msg = match &failure {
|
||||
Ok(m) => m.clone(),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
if self.last_error.as_ref() != Some(&msg) {
|
||||
host::log(LogLevel::Warn, &format!("{}: {msg}", c.endpoint));
|
||||
self.last_error = Some(msg);
|
||||
}
|
||||
// Otherwise a failure only shows in the IDE log, where nobody looks.
|
||||
let notice = advice(&c.endpoint, &c.model, c.openai, &failure);
|
||||
if self.last_notice.as_ref() != Some(¬ice) {
|
||||
host::notify(NotificationLevel::Warning, "AI Completion", ¬ice);
|
||||
self.last_notice = Some(notice);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -144,11 +181,23 @@ impl Plugin for AiCompletion {
|
||||
}
|
||||
}
|
||||
"set-endpoint" => {
|
||||
let url = arg.map(str::trim).filter(|u| u.starts_with("http://") || u.starts_with("https://"));
|
||||
let url = url.ok_or("give the endpoint URL, e.g. http://localhost:11434")?;
|
||||
storage::set("endpoint", url)?;
|
||||
let Some(url) = arg_or_input(arg, "Endpoint URL (e.g. http://localhost:11434)", &config().endpoint)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !(url.starts_with("http://") || url.starts_with("https://")) {
|
||||
return Err("give the endpoint URL, e.g. http://localhost:11434".into());
|
||||
}
|
||||
storage::set("endpoint", &url)?;
|
||||
format!("Using {url}.")
|
||||
}
|
||||
"set-model" => {
|
||||
let Some(model) = arg_or_input(arg, "Model (as `ollama list` shows it)", &config().model)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
storage::set("model", &model)?;
|
||||
format!("Using the model {model}.")
|
||||
}
|
||||
"toggle" => {
|
||||
let enabled = !config().enabled;
|
||||
storage::set("enabled", if enabled { "true" } else { "false" })?;
|
||||
@@ -156,6 +205,8 @@ impl Plugin for AiCompletion {
|
||||
}
|
||||
_ => return Err(Error::NotFound(format!("command {id}"))),
|
||||
};
|
||||
// A new setting may fix (or change) the failure: tell again.
|
||||
self.last_notice = None;
|
||||
host::notify(NotificationLevel::Info, "AI Completion", &msg);
|
||||
Ok(Some(msg))
|
||||
}
|
||||
@@ -228,7 +279,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quiet_when_cancelled_denied_or_mid_word() {
|
||||
fn quiet_when_cancelled_or_mid_word() {
|
||||
let host = MockHost::install().with_capabilities(&["storage"]);
|
||||
let mut p = AiCompletion::default();
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none(), "net denied");
|
||||
@@ -243,4 +294,61 @@ mod tests {
|
||||
assert!(p.inline_completion(&doc("x"), Position::new(0, 1)).is_none());
|
||||
assert_eq!(host2.requests().len(), 1, "disabled: no request");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tells_the_user_why_once_and_what_to_do() {
|
||||
// Installed without the optional network permission (the default for it).
|
||||
let host = MockHost::install().with_capabilities(&["storage"]);
|
||||
let mut p = AiCompletion::default();
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
|
||||
assert!(p.inline_completion(&doc("let x = 1"), Position::new(0, 9)).is_none());
|
||||
let notes = host.notifications();
|
||||
assert_eq!(notes.len(), 1, "once, not per keystroke: {notes:?}");
|
||||
assert!(notes[0].body.contains("Settings › Plugins › AI Completion"), "{}", notes[0].body);
|
||||
|
||||
// A model that is not pulled: Ollama answers 404.
|
||||
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
|
||||
host.on_fetch(|_| {
|
||||
Ok(HttpResponse {
|
||||
status: 404,
|
||||
headers: vec![],
|
||||
body: br#"{"error":{"message":"model \"qwen2.5-coder:1.5b\" not found, try pulling it first"}}"#
|
||||
.to_vec(),
|
||||
})
|
||||
});
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
|
||||
let body = &host.notifications()[0].body;
|
||||
assert!(body.contains("ollama pull qwen2.5-coder:1.5b") && body.contains("Set Model"), "{body}");
|
||||
|
||||
// Ollama not running.
|
||||
host.on_fetch(|_| Err(Error::Failed("connection refused".into())));
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
|
||||
assert!(host.notifications()[1].body.contains("Is it running?"));
|
||||
host.on_fetch(|_| Err(Error::Failed("error sending request: operation timed out".into())));
|
||||
assert!(p.inline_completion(&doc("let x = "), Position::new(0, 8)).is_none());
|
||||
assert!(host.notifications()[2].body.contains("took too long"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_model_takes_an_argument_or_asks() {
|
||||
let host = MockHost::install().with_capabilities(&["storage", "net:localhost"]);
|
||||
host.on_fetch(|_| {
|
||||
Ok(HttpResponse { status: 200, headers: vec![], body: br#"{"choices":[{"text":"x"}]}"#.to_vec() })
|
||||
});
|
||||
let mut p = AiCompletion::default();
|
||||
p.run_command("set-model", &host.invocation(), Some(" qwen2.5-coder:7b ")).unwrap();
|
||||
assert_eq!(config().model, "qwen2.5-coder:7b");
|
||||
// From the command palette: no argument, so it asks.
|
||||
host.answer_next_prompt(Some(&["codellama:7b-code"]));
|
||||
p.run_command("set-model", &host.invocation(), None).unwrap();
|
||||
p.inline_completion(&doc("let x = "), Position::new(0, 8)).unwrap();
|
||||
let body: Value = serde_json::from_slice(host.requests()[0].body.as_ref().unwrap()).unwrap();
|
||||
assert_eq!(body["model"], "codellama:7b-code");
|
||||
// Dismissed: nothing changes.
|
||||
assert_eq!(p.run_command("set-model", &host.invocation(), None).unwrap(), None);
|
||||
assert_eq!(config().model, "codellama:7b-code");
|
||||
host.answer_next_prompt(Some(&["http://127.0.0.1:11434"]));
|
||||
p.run_command("set-endpoint", &host.invocation(), None).unwrap();
|
||||
assert_eq!(config().endpoint, "http://127.0.0.1:11434");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NIGHTLY_ENDPOINT, msiVersion, nightlyVersion, setNightlyConfig } from "./nightly-prepare.ts";
|
||||
|
||||
describe("nightlyVersion", () => {
|
||||
it("is the next patch's nightly once the current version is released", () => {
|
||||
expect(nightlyVersion("0.1.55", true, "20261130", new Set(["v0.1.55"]))).toBe("0.1.56-nightly.20261130");
|
||||
});
|
||||
|
||||
it("is the current version's nightly while that is not released", () => {
|
||||
expect(nightlyVersion("0.1.56", false, "20261130", new Set())).toBe("0.1.56-nightly.20261130");
|
||||
});
|
||||
|
||||
it("numbers further nightlies of the same day, which sort after the first", () => {
|
||||
const tags = new Set(["v0.1.56-nightly.20261130", "v0.1.56-nightly.20261130.2"]);
|
||||
expect(nightlyVersion("0.1.55", true, "20261130", tags)).toBe("0.1.56-nightly.20261130.3");
|
||||
});
|
||||
|
||||
it("refuses a malformed date or version", () => {
|
||||
expect(() => nightlyVersion("0.1.55", true, "2026-11-30", new Set())).toThrow();
|
||||
expect(() => nightlyVersion("0.1", true, "20261130", new Set())).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("msiVersion", () => {
|
||||
it("is the last release with the build number", () => {
|
||||
expect(msiVersion("0.1.55", true, 42)).toBe("0.1.55.42");
|
||||
expect(msiVersion("0.1.56", false, 42)).toBe("0.1.55.42");
|
||||
expect(msiVersion("0.2.0", false, 42)).toBe("0.2.0.42");
|
||||
});
|
||||
|
||||
it("refuses a build number MSI cannot hold", () => {
|
||||
expect(() => msiVersion("0.1.55", true, 65536)).toThrow();
|
||||
expect(() => msiVersion("0.1.55", true, Number.NaN)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("setNightlyConfig", () => {
|
||||
it("sets the version, the nightly manifest and the MSI version, keeping the rest", () => {
|
||||
const json = JSON.stringify(
|
||||
{
|
||||
version: "0.1.55",
|
||||
bundle: { targets: "all", macOS: { minimumSystemVersion: "11.0" } },
|
||||
plugins: { updater: { pubkey: "key", endpoints: ["https://example.com/latest.json"] } },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const config = JSON.parse(setNightlyConfig(json, "0.1.56-nightly.20261130", "0.1.55.42"));
|
||||
expect(config.version).toBe("0.1.56-nightly.20261130");
|
||||
expect(config.plugins.updater).toEqual({ pubkey: "key", endpoints: [NIGHTLY_ENDPOINT] });
|
||||
expect(config.bundle).toEqual({
|
||||
targets: "all",
|
||||
macOS: { minimumSystemVersion: "11.0" },
|
||||
windows: { wix: { version: "0.1.55.42" } },
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses a config without the updater", () => {
|
||||
expect(() =>
|
||||
setNightlyConfig(JSON.stringify({ version: "0.1.55" }), "0.1.56-nightly.20261130", "0.1.55.1"),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Prepares a nightly build commit (nightly.yml): `node scripts/nightly-prepare.ts --date 20261130
|
||||
* --build 42` sets the app version to the next patch's nightly, `0.1.56-nightly.20261130` (`.2`,
|
||||
* `.3`… when that tag already exists), in Cargo.toml, package.json and tauri.conf.json, points the
|
||||
* updater at the nightly channel's manifest, gives the MSI installer a numeric version, refreshes
|
||||
* Cargo.lock and the plugin API snapshot, and prints the version (also `version=` in
|
||||
* $GITHUB_OUTPUT). The next patch is the current version's when that is already released (its
|
||||
* `v` tag exists), else the current version itself.
|
||||
*/
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { appendFileSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
cargoVersion,
|
||||
edit,
|
||||
parseVersion,
|
||||
setCargoVersion,
|
||||
setJsonVersion,
|
||||
syncApiSnapshot,
|
||||
} from "./release-prepare.ts";
|
||||
|
||||
/** The nightly channel's updater manifest: the rolling `nightly` release (nightly.yml). */
|
||||
export const NIGHTLY_ENDPOINT = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json";
|
||||
|
||||
function bump(version: string): string {
|
||||
const [major, minor, patch] = version.split(".").map(Number);
|
||||
return `${major}.${minor}.${patch! + 1}`;
|
||||
}
|
||||
|
||||
/** The nightly's version: the first of `<next>-nightly.<date>`, `….2`, `….3` whose tag is not in `tags`. */
|
||||
export function nightlyVersion(current: string, released: boolean, date: string, tags: Set<string>): string {
|
||||
if (!/^\d{8}$/.test(date)) throw new Error(`expected a date like 20261130, got ${date}`);
|
||||
const base = `${released ? bump(parseVersion(current)) : parseVersion(current)}-nightly.${date}`;
|
||||
for (let n = 1; ; n++) {
|
||||
const version = n === 1 ? base : `${base}.${n}`;
|
||||
if (!tags.has(`v${version}`)) return version;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The MSI ProductVersion (`major.minor.patch.build`, numbers only): the last released version
|
||||
* with the build number, so a nightly sorts after that release and before the next.
|
||||
*/
|
||||
export function msiVersion(current: string, released: boolean, build: number): string {
|
||||
if (!Number.isInteger(build) || build < 0 || build > 65535) throw new Error(`build ${build} is not 0–65535`);
|
||||
const [major, minor, patch] = parseVersion(current).split(".").map(Number);
|
||||
const last = released || patch === 0 ? patch : patch! - 1;
|
||||
return `${major}.${minor}.${last}.${build}`;
|
||||
}
|
||||
|
||||
/** tauri.conf.json for a nightly: its version, the nightly updater manifest and the MSI version. */
|
||||
export function setNightlyConfig(json: string, version: string, msi: string): string {
|
||||
const config = JSON.parse(setJsonVersion(json, version)) as {
|
||||
plugins?: { updater?: { endpoints?: string[] } };
|
||||
bundle?: { windows?: { wix?: { version?: string } } };
|
||||
};
|
||||
if (!config.plugins?.updater) throw new Error("tauri.conf.json: no plugins.updater");
|
||||
config.plugins.updater.endpoints = [NIGHTLY_ENDPOINT];
|
||||
config.bundle ??= {};
|
||||
config.bundle.windows ??= {};
|
||||
config.bundle.windows.wix = { ...config.bundle.windows.wix, version: msi };
|
||||
return `${JSON.stringify(config, null, 2)}\n`;
|
||||
}
|
||||
|
||||
function arg(name: string): string {
|
||||
const index = process.argv.indexOf(`--${name}`);
|
||||
const value = index >= 0 ? process.argv[index + 1] : undefined;
|
||||
if (!value) throw new Error(`missing --${name}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function git(root: string, ...args: string[]): string {
|
||||
const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
|
||||
if (result.status !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr}`);
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const root = fileURLToPath(new URL("..", import.meta.url));
|
||||
const date = arg("date");
|
||||
const build = Number(arg("build"));
|
||||
const current = cargoVersion(readFileSync(join(root, "Cargo.toml"), "utf8"));
|
||||
const tags = new Set(git(root, "tag", "--list", "v*").split("\n").filter(Boolean));
|
||||
const released = tags.has(`v${current}`);
|
||||
const version = nightlyVersion(current, released, date, tags);
|
||||
const msi = msiVersion(current, released, build);
|
||||
|
||||
edit(join(root, "Cargo.toml"), (text) => setCargoVersion(text, version));
|
||||
edit(join(root, "package.json"), (text) => setJsonVersion(text, version));
|
||||
edit(join(root, "src-tauri/tauri.conf.json"), (text) => setNightlyConfig(text, version, msi));
|
||||
const cargo = spawnSync("cargo", ["update", "--workspace"], { cwd: root, stdio: "inherit" });
|
||||
if (cargo.status !== 0) throw new Error("cargo update --workspace failed");
|
||||
syncApiSnapshot(root);
|
||||
|
||||
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`);
|
||||
console.log(version);
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error(`nightly-prepare: ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Forking recorded native agent sessions into new tasks (API 1.18). Requires
|
||||
/// the `agents` capability. The session must belong to the invoking window's
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// The commit being prepared in the window the current command or event came
|
||||
/// from (the Commit tool window, or the Commit dialog while it is open): the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (API 1.16, world `plugin-completion-list`): completion that
|
||||
/// can say its list is incomplete. A plugin exporting it is called instead of
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Plugin-owned project data sources. Requires database.sources and project trust.
|
||||
/// Runs on the Database subsystem's host, including on remote project servers.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
|
||||
/// follows its file: the file's own project, or the nearest one when it is outside them all.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// What the pane beside the Services tree shows for a plugin's node.
|
||||
interface detail-types {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-diagnostics`): problems in the current,
|
||||
/// possibly unsaved document, for the languages declared with the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
|
||||
interface endpoints-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// What other plugins contributed to the extension points this plugin declares
|
||||
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-file-actions`): quick fixes and
|
||||
/// refactorings that create, rename or delete files, next to the text edits
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Files outside the open projects: the configuration of the program a
|
||||
/// plugin integrates with, a tool installed elsewhere, a licence file.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-hover-actions`): clickable actions rendered
|
||||
/// at the left edge of a line and revealed while the pointer is in the leftmost
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-hover`): Markdown added to the hover of
|
||||
/// documents of the languages declared with the `hover` provider kind,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Cross-file associations a plugin publishes for the files it declares under
|
||||
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Embedded languages. The host routes plugin providers and configured language
|
||||
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
|
||||
/// the languages declared with the `inlay-hints` provider kind, including
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
@@ -108,6 +108,32 @@ interface net {
|
||||
/// project binding, so resource methods cannot be redirected to another
|
||||
/// project.
|
||||
websocket-connect: func(project: borrow<project>, req: websocket-request) -> result<websocket, error>;
|
||||
|
||||
record body-chunk {
|
||||
bytes: list<u8>,
|
||||
/// The body has ended: this read and every later one return no more bytes.
|
||||
done: bool,
|
||||
}
|
||||
|
||||
/// A response whose body is read as it arrives: server-sent events, a
|
||||
/// model's streamed reply (API 1.19). At most eight may be open for a
|
||||
/// plugin. Dropping this resource closes the connection, as does stopping
|
||||
/// the plugin.
|
||||
resource response-stream {
|
||||
status: func() -> u16;
|
||||
headers: func() -> list<header>;
|
||||
/// The next bytes of the body, at most `max-bytes` (and 1 MiB). Waits
|
||||
/// up to `timeout-ms` for them within the call's budget and returns
|
||||
/// none, with `done` false, when nothing arrived in time; zero only
|
||||
/// takes what has already arrived.
|
||||
read: func(max-bytes: u32, timeout-ms: u32) -> result<body-chunk, error>;
|
||||
close: func();
|
||||
}
|
||||
|
||||
/// As `fetch`, with the same grants, secrets and redirects, but returns
|
||||
/// once the response headers arrive (API 1.19). `timeout-ms` bounds the
|
||||
/// wait for the headers; the body has no overall limit.
|
||||
fetch-stream: func(req: request) -> result<response-stream, error>;
|
||||
}
|
||||
|
||||
/// Secrets the user stored for the plugin (Settings › Plugins, kept in the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Additional language features, called only for declared API 1.4 provider kinds.
|
||||
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
|
||||
interface mcp {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// `fs` and `workspace`, and everything else goes through the imports below,
|
||||
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
|
||||
/// `error::denied`).
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Editor features a plugin provides for the languages it declares under
|
||||
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Project-scoped targets owned by the registering plugin (API 1.4).
|
||||
interface run-targets {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Launches this plugin's configurations in the invoking window's Run tool window.
|
||||
interface run {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// On-demand results for `[[contributes.searchCategories]]`. Optional, API 1.13.
|
||||
interface search-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
|
||||
/// documents of the languages declared with the `semantic-tokens` provider
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
|
||||
/// as in the editor and LSP.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
@@ -203,8 +203,20 @@ interface views {
|
||||
/// The plugin's own settings (`[contributes.settings]`), as the user set them
|
||||
/// (project over global) or the schema's default.
|
||||
interface settings {
|
||||
use types.{error};
|
||||
|
||||
/// The value of `key` as JSON (`true`, `3`, `"text"`), none if unknown.
|
||||
get: func(key: string) -> option<string>;
|
||||
/// Opens Settings at one of the plugin's own pages in the window the
|
||||
/// current command or event came from (API 1.19): `page` is the `id` of a
|
||||
/// `[[contributes.settings.pages]]` entry, none for the plugin's settings
|
||||
/// node itself. `invalid` outside a window's command or event, `not-found`
|
||||
/// for a page the plugin does not declare (or without `[contributes.settings]`).
|
||||
open: func(page: option<string>) -> result<_, error>;
|
||||
/// Opens Settings › Plugins at this plugin's permissions, where the user
|
||||
/// grants an optional capability it lacks (API 1.19). `invalid` outside a
|
||||
/// window's command or event.
|
||||
open-permissions: func() -> result<_, error>;
|
||||
}
|
||||
|
||||
/// Optional export (world `plugin-views`): content of declared views and
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]8.0;
|
||||
package openidea:[email protected]9.0;
|
||||
|
||||
interface workspace {
|
||||
use types.{error, location};
|
||||
@@ -137,6 +137,10 @@ interface editor {
|
||||
/// the plugin's install directory, selecting a range. Only from
|
||||
/// commands/events of a window. Paths follow views.open-location.
|
||||
open: func(path: string, selection: option<range>) -> result<_, error>;
|
||||
/// `open` in the built-in text editor even when a custom editor claims
|
||||
/// the file, as the IDE's own "Open as Text" does: the same document,
|
||||
/// undo history and Save (API 1.19).
|
||||
open-as-text: func(path: string, selection: option<range>) -> result<_, error>;
|
||||
|
||||
/// Current version and text of an open project document. Unlike
|
||||
/// `text-editor.document`, this is available to background events.
|
||||
|
||||
@@ -636,11 +636,18 @@ fn config_endpoints<R: tauri::Runtime>(app: &AppHandle<R>) -> Vec<String> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Nightly builds (`x.y.z-nightly.…`, nightly.yml) update from the nightly channel's manifest
|
||||
/// only: the CNB mirror carries stable releases.
|
||||
fn is_nightly(version: &str) -> bool {
|
||||
version.contains("-nightly.")
|
||||
}
|
||||
|
||||
/// The endpoints tried in order: `source` first, the other source when it fails or has
|
||||
/// no manifest. Bundles are signed, so either source's manifest and downloads verify.
|
||||
/// No official endpoint (a build without updates) means no mirror either.
|
||||
fn source_endpoints(official: Vec<String>, source: UpdateSource) -> Vec<String> {
|
||||
if official.is_empty() {
|
||||
/// No official endpoint (a build without updates) means no mirror either, and a nightly
|
||||
/// build of `version` has no mirror.
|
||||
fn source_endpoints(official: Vec<String>, source: UpdateSource, version: &str) -> Vec<String> {
|
||||
if official.is_empty() || is_nightly(version) {
|
||||
return official;
|
||||
}
|
||||
let mirror = vec![CNB_ENDPOINT.to_string()];
|
||||
@@ -669,7 +676,7 @@ pub(crate) fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option
|
||||
}
|
||||
let endpoints = match update_endpoint_env() {
|
||||
Some(url) => vec![url],
|
||||
None => source_endpoints(config_endpoints(app), source),
|
||||
None => source_endpoints(config_endpoints(app), source, env!("CARGO_PKG_VERSION")),
|
||||
};
|
||||
let endpoints = endpoints
|
||||
.iter()
|
||||
@@ -867,7 +874,7 @@ pub async fn app_release_notes(
|
||||
) -> IdeResult<Option<BTreeMap<String, String>>> {
|
||||
let endpoints = match update_endpoint_env() {
|
||||
Some(url) => vec![url],
|
||||
None => source_endpoints(config_endpoints(&app), source),
|
||||
None => source_endpoints(config_endpoints(&app), source, env!("CARGO_PKG_VERSION")),
|
||||
};
|
||||
let client = ide_http::client::shared()?;
|
||||
for endpoint in endpoints {
|
||||
@@ -1005,10 +1012,24 @@ mod tests {
|
||||
#[test]
|
||||
fn chosen_source_is_tried_first_and_the_other_after_it() {
|
||||
let github = "https://github.com/l0ng-ai/openidea/releases/latest/download/latest.json".to_string();
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Github), [github.clone(), CNB_ENDPOINT.into()]);
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb), [CNB_ENDPOINT.into(), github]);
|
||||
assert_eq!(
|
||||
source_endpoints(vec![github.clone()], UpdateSource::Github, "0.1.55"),
|
||||
[github.clone(), CNB_ENDPOINT.into()]
|
||||
);
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb, "0.1.55"), [CNB_ENDPOINT.into(), github]);
|
||||
// A build without an update endpoint stays without one.
|
||||
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
|
||||
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb, "0.1.55").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_builds_update_from_the_nightly_manifest_only() {
|
||||
let nightly = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json".to_string();
|
||||
for source in [UpdateSource::Github, UpdateSource::Cnb] {
|
||||
assert_eq!(
|
||||
source_endpoints(vec![nightly.clone()], source, "0.1.56-nightly.20261130"),
|
||||
std::slice::from_ref(&nightly)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.55",
|
||||
"version": "0.1.56",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -11748,6 +11748,12 @@ export type NavigationFiles = {
|
||||
paths: IpcPath[],
|
||||
indexing: boolean,
|
||||
extensions: string[],
|
||||
/**
|
||||
* In-scope files matching `extensions`; `paths` holds the first
|
||||
* `MAX_NAVIGATION_FILES` of them.
|
||||
*/
|
||||
total: number,
|
||||
truncated: boolean,
|
||||
};
|
||||
|
||||
export type NavigationResult = {
|
||||
|
||||
@@ -918,6 +918,11 @@ function outsideProject(path: string): boolean {
|
||||
/** Files outside the project that code navigation opened: library sources, shown read-only. */
|
||||
const navigatedLibraryFiles = new Set<string>();
|
||||
|
||||
/** Marks `path` as a library source again, for a tab restored from a saved session. */
|
||||
export function markLibraryFile(path: string): void {
|
||||
navigatedLibraryFiles.add(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a code location a language server or the index answered (a declaration, an
|
||||
* implementation, a documentation link) and selects `selection`. A file outside the project is a
|
||||
|
||||
@@ -3,8 +3,10 @@ import { EditorSelection, EditorState, Transaction, type Extension } from "@code
|
||||
import { indentService, indentUnit } from "@codemirror/language";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { EDITOR_EXTRA_DEFAULTS, type LineClipboardOptions } from "@/platform/editorSettings";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { useWebConnection } from "@/platform/webBridge";
|
||||
import {
|
||||
clearClipboardHistory,
|
||||
clipboardHistory,
|
||||
@@ -27,6 +29,7 @@ const views: EditorView[] = [];
|
||||
beforeEach(() => {
|
||||
clearClipboardHistory();
|
||||
vi.stubGlobal("__TAURI_INTERNALS__", {});
|
||||
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
|
||||
Object.defineProperty(document, "execCommand", { configurable: true, value: vi.fn(() => false) });
|
||||
Object.defineProperty(document, "queryCommandSupported", { configurable: true, value: vi.fn(() => false) });
|
||||
});
|
||||
@@ -211,6 +214,73 @@ it.each([
|
||||
expect(create.mock.calls[0]![0]).toMatch(hasFile ? /assets\/image\.png$/ : /assets\/image-\d{8}-\d{6}\.png$/);
|
||||
});
|
||||
|
||||
describe("macOS menu paste into Markdown reads the clipboard natively", () => {
|
||||
// WebKit's execCommand("paste") from a menu makes macOS show a "Paste" callout.
|
||||
function markdownView() {
|
||||
usePlatform.setState({ os: "macos" });
|
||||
const view = new EditorView({
|
||||
extensions: [
|
||||
clipboardDocumentPath.of("/p/a.md"),
|
||||
clipboardFilesExtension,
|
||||
markdownImages({ path: "/p/a.md", folder: "assets", pattern: "image-{timestamp}" }),
|
||||
],
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
vi.mocked(document.queryCommandSupported).mockReturnValue(true);
|
||||
return view;
|
||||
}
|
||||
|
||||
it("saves a copied image without the webview's paste", async () => {
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] });
|
||||
vi.spyOn(commands, "clipboardImage").mockResolvedValue({ status: "ok", data: "data:image/png;base64,iVBORw==" });
|
||||
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
|
||||
const view = markdownView();
|
||||
await pasteEditorClipboard(view);
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toMatch(/^!\[\]\(assets\/image-\d{8}-\d{6}\.png\)$/));
|
||||
expect(create.mock.calls[0]![1]).toBe("iVBORw==");
|
||||
expect(document.execCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the execCommand paste in web mode, where the backend has no clipboard", async () => {
|
||||
useWebConnection.setState({ active: true });
|
||||
try {
|
||||
const list = vi.spyOn(commands, "clipboardFileList");
|
||||
vi.mocked(document.execCommand).mockReturnValue(true);
|
||||
await pasteEditorClipboard(markdownView());
|
||||
expect(document.execCommand).toHaveBeenCalledWith("paste");
|
||||
expect(list).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
useWebConnection.setState({ active: false });
|
||||
}
|
||||
});
|
||||
|
||||
it("pastes the text when the clipboard holds no image", async () => {
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: [] });
|
||||
vi.spyOn(commands, "clipboardImage").mockResolvedValue({ status: "ok", data: null });
|
||||
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: "plain" });
|
||||
const view = markdownView();
|
||||
await pasteEditorClipboard(view);
|
||||
expect(view.state.doc.toString()).toBe("plain");
|
||||
expect(document.execCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("embeds a copied image file like the paste event, not as a path", async () => {
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/src/pic.png"] });
|
||||
const image = vi.spyOn(commands, "clipboardImage");
|
||||
vi.stubGlobal("__TAURI_INTERNALS__", {
|
||||
invoke: vi.fn(async () => "data:image/png;base64,iVBORw=="),
|
||||
});
|
||||
const create = vi.spyOn(commands, "fsCreateFileBytes").mockResolvedValue({ status: "ok", data: null });
|
||||
const view = markdownView();
|
||||
await pasteEditorClipboard(view);
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toBe(""));
|
||||
expect(create.mock.calls[0]![0]).toMatch(/assets\/pic\.png$/);
|
||||
expect(image).not.toHaveBeenCalled();
|
||||
expect(document.execCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("does not insert into a read-only editor", async () => {
|
||||
const list = vi.spyOn(commands, "clipboardFileList");
|
||||
const view = new EditorView({ extensions: [clipboardFilesExtension, EditorState.readOnly.of(true)] });
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { EditorSelection, Facet, Prec, type EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { pasteClipboardFiles, readClipboardText } from "@/platform/clipboard";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { isWebMode } from "@/platform/webBridge";
|
||||
import type { LinePasteMode } from "@/platform/editorSettings";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { isLinewiseClipboardText } from "../clipboardHistory";
|
||||
import { isMarkdown, relativeImagePath } from "./markdownImages";
|
||||
import { isMarkdown, pasteMarkdownImages, relativeImagePath } from "./markdownImages";
|
||||
|
||||
export const clipboardDocumentPath = Facet.define<string, string>({ combine: (paths) => paths[0] ?? "" });
|
||||
|
||||
@@ -125,9 +128,19 @@ export function pasteEditorText(view: EditorView, text: string) {
|
||||
|
||||
export async function pasteEditorClipboard(view: EditorView) {
|
||||
if (!view.dom.isConnected || view.state.readOnly) return;
|
||||
const markdown = isMarkdown(view.state.facet(clipboardDocumentPath));
|
||||
// macOS WebKit asks the user to confirm execCommand("paste") from the editor context menu with a "Paste" callout
|
||||
// (the app-menu Edit > Paste is a native paste: selector and never gets here); the
|
||||
// backend reads the image (or copied image files) without asking, so text then takes the native path below.
|
||||
const native = markdown && isTauri() && !isWebMode() && usePlatform.getState().os === "macos";
|
||||
try {
|
||||
if (native) {
|
||||
const paths: string[] = await call(commands.clipboardFileList()).catch(() => []);
|
||||
const image = paths.length ? null : await call(commands.clipboardImage()).catch(() => null);
|
||||
if (pasteMarkdownImages(view, image ?? paths)) return;
|
||||
}
|
||||
// Successful native paste preserves image blobs and may complete after execCommand returns.
|
||||
if (isMarkdown(view.state.facet(clipboardDocumentPath)) && document.queryCommandSupported("paste")) {
|
||||
if (markdown && !native && document.queryCommandSupported("paste")) {
|
||||
view.focus();
|
||||
if (document.execCommand("paste")) return;
|
||||
}
|
||||
|
||||
@@ -111,6 +111,29 @@ interface ImageOptions {
|
||||
pattern: string;
|
||||
}
|
||||
|
||||
type ImageSource = () => Promise<{ blob: Blob | string; name: string }>;
|
||||
|
||||
// OS paths belong to this client even in a remote project.
|
||||
const fileSource =
|
||||
(path: string): ImageSource =>
|
||||
async () => ({ blob: await invokeLocal<string>("fs_read_image", { path }), name: path.replace(/^.*[\\/]/, "") });
|
||||
|
||||
const imageInserters = new WeakMap<EditorView, (sources: ImageSource[]) => void>();
|
||||
|
||||
/**
|
||||
* Saves and links images the menu Paste read natively, as a paste event would: image files by path, or a
|
||||
* raw clipboard image as a PNG data URL. False when `view` does not take images (not Markdown, read-only,
|
||||
* or not image files).
|
||||
*/
|
||||
export function pasteMarkdownImages(view: EditorView, images: string[] | string): boolean {
|
||||
const insert = imageInserters.get(view);
|
||||
if (!insert || view.state.readOnly) return false;
|
||||
if (typeof images === "string") insert([async () => ({ blob: images, name: "" })]);
|
||||
else if (images.length && images.every((p) => IMAGE_FILE.test(p))) insert(images.map(fileSource));
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function markdownImages(options: ImageOptions): Extension {
|
||||
if (!isMarkdown(options.path)) return [];
|
||||
return ViewPlugin.fromClass(
|
||||
@@ -118,7 +141,9 @@ export function markdownImages(options: ImageOptions): Extension {
|
||||
alive = true;
|
||||
pending = new Set<{ from: number; to: number }>();
|
||||
unregister: () => void;
|
||||
readonly insertSources = (sources: ImageSource[]) => this.insert(sources);
|
||||
constructor(readonly view: EditorView) {
|
||||
imageInserters.set(view, this.insertSources);
|
||||
this.unregister = registerFileDropHandler((paths, x, y) => {
|
||||
const rect = view.dom.getBoundingClientRect();
|
||||
if (
|
||||
@@ -130,14 +155,7 @@ export function markdownImages(options: ImageOptions): Extension {
|
||||
view.state.readOnly
|
||||
)
|
||||
return false;
|
||||
this.insert(
|
||||
paths.map((path) => async () => {
|
||||
// OS paths belong to this client even in a remote project.
|
||||
const url = await invokeLocal<string>("fs_read_image", { path });
|
||||
return { blob: url, name: path.replace(/^.*[\\/]/, "") };
|
||||
}),
|
||||
view.posAtCoords({ x, y }) ?? view.state.selection.main.head,
|
||||
);
|
||||
this.insert(paths.map(fileSource), view.posAtCoords({ x, y }) ?? view.state.selection.main.head);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -150,8 +168,9 @@ export function markdownImages(options: ImageOptions): Extension {
|
||||
destroy() {
|
||||
this.alive = false;
|
||||
this.unregister();
|
||||
if (imageInserters.get(this.view) === this.insertSources) imageInserters.delete(this.view);
|
||||
}
|
||||
insert(sources: Array<() => Promise<{ blob: Blob | string; name: string }>>, position?: number) {
|
||||
insert(sources: ImageSource[], position?: number) {
|
||||
const selection = this.view.state.selection.main;
|
||||
const range = { from: position ?? selection.from, to: position ?? selection.to };
|
||||
this.pending.add(range);
|
||||
|
||||
@@ -21,6 +21,8 @@ import {
|
||||
_provideOpenEditorPaths,
|
||||
_setActiveEditor,
|
||||
focusedCellEditor,
|
||||
isLibraryPath,
|
||||
markLibraryFile,
|
||||
shownLine,
|
||||
type NavigationLocation,
|
||||
} from "@/editor/api";
|
||||
@@ -114,7 +116,14 @@ import {
|
||||
import { EditorSlot, type SlotHost } from "./model/slot";
|
||||
import { NavigationHistory } from "./model/navHistory";
|
||||
import { EditHistory } from "./model/editHistory";
|
||||
import { loadSession, restoreTabsState, serializeSession, storeSession, type FileViewState } from "./model/session";
|
||||
import {
|
||||
loadSession,
|
||||
restoreTabsState,
|
||||
serializeSession,
|
||||
sessionLibraryFiles,
|
||||
storeSession,
|
||||
type FileViewState,
|
||||
} from "./model/session";
|
||||
import { docBackend, type DocBackend } from "./backend";
|
||||
import { isClassFile } from "@/platform/classFiles";
|
||||
import { isVirtualUri, virtualDocument } from "@/platform/virtualDocs";
|
||||
@@ -663,7 +672,7 @@ export class EditorController implements SlotHost {
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
storeSession(
|
||||
root,
|
||||
serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable),
|
||||
serializeSession(useTabs.getState(), files, (input) => !!kinds.get(input.kind)?.restorable, isLibraryPath),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -700,6 +709,8 @@ export class EditorController implements SlotHost {
|
||||
if (this.forgottenSessions.delete(root)) return;
|
||||
const session = loadSession(root);
|
||||
if (!session) return;
|
||||
// Before the documents open: a library source opens read-only.
|
||||
for (const path of sessionLibraryFiles(session)) markLibraryFile(path);
|
||||
const state = restoreTabsState(session, fileKey);
|
||||
const kinds = useContributions.getState().editorKinds;
|
||||
for (const pane of Object.values(state.panes))
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
parseSession,
|
||||
restoreTabsState,
|
||||
serializeSession,
|
||||
sessionLibraryFiles,
|
||||
slashPath,
|
||||
storeSession,
|
||||
type EditorSession,
|
||||
@@ -59,6 +60,17 @@ describe("editor session", () => {
|
||||
expect(r.layout).toMatchObject({ kind: "split", dir: "column" });
|
||||
});
|
||||
|
||||
it("remembers which file tabs are library sources", () => {
|
||||
let s = initialTabsState();
|
||||
s = open(s, "/p/main.swift");
|
||||
s = open(s, "/tmp/sk/Swift.String.swiftinterface");
|
||||
const library = (path: string) => path.endsWith(".swiftinterface");
|
||||
const session = serializeSession(s, {}, undefined, library)!;
|
||||
const parsed = parseSession(JSON.parse(JSON.stringify(session)))!;
|
||||
expect(sessionLibraryFiles(parsed)).toEqual(["/tmp/sk/Swift.String.swiftinterface"]);
|
||||
expect(sessionLibraryFiles(parseSession(JSON.parse(JSON.stringify(serializeSession(s, {})!)))!)).toEqual([]);
|
||||
});
|
||||
|
||||
it("saves tabs of restorable editor kinds with their input", () => {
|
||||
let s = initialTabsState();
|
||||
s = open(s, "/p/a.ts");
|
||||
|
||||
@@ -18,6 +18,8 @@ export interface SessionTab {
|
||||
input?: EditorInput;
|
||||
pinned?: boolean;
|
||||
preview?: boolean;
|
||||
/** A library source (read-only), e.g. an SDK interface code navigation opened outside the project. */
|
||||
library?: boolean;
|
||||
}
|
||||
|
||||
export type SessionLayout =
|
||||
@@ -43,11 +45,15 @@ const STORAGE_PREFIX = "openidea.editorSession.v1:";
|
||||
|
||||
const isFileTab = (t: Tab) => t.input.kind === "file" && !!t.input.path;
|
||||
|
||||
/** `restorable`: whether a non-file tab is saved (its kind asked for it). */
|
||||
/**
|
||||
* `restorable`: whether a non-file tab is saved (its kind asked for it). `library`: whether a
|
||||
* file tab shows a library source, so it opens read-only again.
|
||||
*/
|
||||
export function serializeSession(
|
||||
s: TabsState,
|
||||
files: Record<string, FileViewState>,
|
||||
restorable: (input: EditorInput) => boolean = () => false,
|
||||
library: (path: string) => boolean = () => false,
|
||||
): EditorSession | null {
|
||||
const saved = (t: Tab) => isFileTab(t) || (t.input.kind !== "file" && restorable(t.input));
|
||||
const walk = (n: LayoutNode): SessionLayout | null => {
|
||||
@@ -66,6 +72,7 @@ export function serializeSession(
|
||||
...(isFileTab(t) ? { path: t.input.path! } : { input: { ...t.input } }),
|
||||
...(t.pinned ? { pinned: true } : {}),
|
||||
...(t.preview ? { preview: true } : {}),
|
||||
...(isFileTab(t) && library(t.input.path!) ? { library: true } : {}),
|
||||
})),
|
||||
active,
|
||||
};
|
||||
@@ -151,6 +158,17 @@ export function parseSession(raw: unknown): EditorSession | null {
|
||||
};
|
||||
}
|
||||
|
||||
/** Paths of the file tabs saved as library sources. */
|
||||
export function sessionLibraryFiles(session: EditorSession): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (l: SessionLayout) =>
|
||||
l.kind === "pane"
|
||||
? l.tabs.forEach((t) => t.library === true && t.path && out.push(t.path))
|
||||
: l.children.forEach(walk);
|
||||
walk(session.layout);
|
||||
return out;
|
||||
}
|
||||
|
||||
let seq = 0;
|
||||
const id = (p: string) => `${p}r${++seq}`;
|
||||
|
||||
|
||||
@@ -283,6 +283,63 @@ describe("applying completions", () => {
|
||||
expect(view.state.selection.main.head).toBe(14);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ doc: " @Over|\n", prefix: "Over", label: "Override", expected: " @Override|\n" },
|
||||
{ doc: '@Supp|("unused")', prefix: "Supp", label: "SuppressWarnings", expected: '@SuppressWarnings|("unused")' },
|
||||
{ doc: "@java.lang.Over|", prefix: "Over", label: "Override", expected: "@java.lang.Override|" },
|
||||
{
|
||||
doc: "@Over| public void run() {}",
|
||||
prefix: "Over",
|
||||
label: "Override",
|
||||
expected: "@Override| public void run() {}",
|
||||
},
|
||||
{
|
||||
doc: "@Over|public void run() {}",
|
||||
prefix: "Over",
|
||||
label: "Override",
|
||||
expected: "@Override |public void run() {}",
|
||||
},
|
||||
{ doc: "implements Run|\n", prefix: "Run", label: "Runnable", expected: "implements Runnable |\n" },
|
||||
])("applies a Java interface completion in $doc", ({ doc, prefix, label, expected }) => {
|
||||
const { view, req, pos } = setup(doc);
|
||||
const suggestion = item({ label, kind: "interface", insertText: `${label} `, isSnippet: true });
|
||||
apply(view, makeCompletion(suggestion, { ...req, language: "java" }), pos - prefix.length);
|
||||
expect(view.state.doc.toString()).toBe(expected.replace("|", ""));
|
||||
expect(view.state.selection.main.head).toBe(expected.indexOf("|"));
|
||||
});
|
||||
|
||||
it("replaces a Java annotation name before its existing arguments with Tab", () => {
|
||||
const { view, req, pos } = setup('@Sup|pressWarnings("unused")');
|
||||
const suggestion = item({
|
||||
label: "SuppressWarnings",
|
||||
kind: "interface",
|
||||
insertText: "SuppressWarnings ",
|
||||
isSnippet: true,
|
||||
replaceRange: { start: { line: 0, col: 1 }, end: { line: 0, col: pos } },
|
||||
replaceRangeTab: { start: { line: 0, col: 1 }, end: { line: 0, col: 17 } },
|
||||
});
|
||||
applyLspCompletion(view, makeCompletion(suggestion, { ...req, language: "java" }), 1, pos, "replace");
|
||||
expect(view.state.doc.toString()).toBe('@SuppressWarnings("unused")');
|
||||
expect(view.state.selection.main.head).toBe(17);
|
||||
});
|
||||
|
||||
it("keeps spacing in a Java annotation attribute completion", () => {
|
||||
const { view, req } = setup("@Tag(va|)");
|
||||
const suggestion = item({ label: "value", kind: "field", insertText: "value = ", isSnippet: true });
|
||||
apply(view, makeCompletion(suggestion, { ...req, language: "java" }), 5);
|
||||
expect(view.state.doc.toString()).toBe("@Tag(value = )");
|
||||
expect(view.state.selection.main.head).toBe(13);
|
||||
});
|
||||
|
||||
it("accounts for what follows each Java annotation when completing at several carets", () => {
|
||||
const { view, req } = setup("@Ov|\n@Ovpublic void run() {}", "", [EditorState.allowMultipleSelections.of(true)]);
|
||||
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(3), EditorSelection.cursor(7)]) });
|
||||
const suggestion = item({ label: "Override", kind: "interface", insertText: "Override ", isSnippet: true });
|
||||
applyLspCompletion(view, makeCompletion(suggestion, { ...req, language: "java" }), 1, 3, "insert");
|
||||
expect(view.state.doc.toString()).toBe("@Override\n@Override public void run() {}");
|
||||
expect(view.state.selection.ranges.map((r) => r.head)).toEqual([9, 20]);
|
||||
});
|
||||
|
||||
it("lets Tab step out of the parentheses a completion inserted", () => {
|
||||
const { view, req } = setup("service.cr|", "", [tabOut]);
|
||||
applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert");
|
||||
|
||||
@@ -245,6 +245,23 @@ function applyLsp(view: EditorView, completion: Completion, from: number, to: nu
|
||||
applyLspCompletion(view, completion, from, to, replaceMode ? "replace" : "insert");
|
||||
}
|
||||
|
||||
function completionInsertText(
|
||||
item: CompletionItem,
|
||||
language: string | null,
|
||||
doc: Text,
|
||||
from: number,
|
||||
to: number,
|
||||
): string {
|
||||
const { insertText } = item;
|
||||
// JDT LS can append a space to a bare annotation name. It is useful only as a separator.
|
||||
if (language !== "java" || item.kind !== "interface" || insertText !== `${item.label} `) return insertText;
|
||||
const line = doc.lineAt(from);
|
||||
const before = line.text.slice(0, from - line.from);
|
||||
const after = doc.sliceString(to, to + 2);
|
||||
if (!/@(?:[\p{L}\p{N}\p{M}_$]+\.)*$/u.test(before) || identifierEnd(after, 0) > 0) return insertText;
|
||||
return item.label;
|
||||
}
|
||||
|
||||
/** ↵ (`insert`) or ⇥ (`replace`: also overwrites the rest of the identifier). */
|
||||
export function applyLspCompletion(
|
||||
view: EditorView,
|
||||
@@ -291,6 +308,7 @@ export function applyLspCompletion(
|
||||
return;
|
||||
}
|
||||
|
||||
const insertText = completionInsertText(item, req.language, state.doc, start, end);
|
||||
let insertedParens: ReturnType<typeof callParens> = null;
|
||||
let bareCall: number | null = null;
|
||||
if (item.isSnippet) {
|
||||
@@ -300,7 +318,7 @@ export function applyLspCompletion(
|
||||
start = tr.changes.mapPos(start, 1);
|
||||
end = tr.changes.mapPos(end, 1);
|
||||
}
|
||||
const source = lspSnippetToCm(item.insertText, snippetVariables(req.path));
|
||||
const source = lspSnippetToCm(insertText, snippetVariables(req.path));
|
||||
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
|
||||
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
|
||||
// signature help says there is nothing to pass.
|
||||
@@ -320,7 +338,7 @@ export function applyLspCompletion(
|
||||
? callParens(item, state.doc.lineAt(start), start, end)
|
||||
: null;
|
||||
insertedParens = parens;
|
||||
const changes = state.changes([...extra, { from: start, to: end, insert: item.insertText + (parens ? "()" : "") }]);
|
||||
const changes = state.changes([...extra, { from: start, to: end, insert: insertText + (parens ? "()" : "") }]);
|
||||
const caret = changes.mapPos(end, 1) - (parens === "inside" ? 1 : 0);
|
||||
view.dispatch({
|
||||
changes,
|
||||
@@ -391,11 +409,13 @@ function applyAtCarets(
|
||||
|
||||
// Parentheses depend on what follows each site: `a.cr|` gets them, `b.cr|()` does not.
|
||||
const textAt = (site: { from: number; to: number }): { text: string; caret: number } => {
|
||||
if (item.isSnippet) return lspSnippetToPlainWithCaret(item.insertText, snippetVariables(completion.req.path));
|
||||
const { language, path } = completion.req;
|
||||
const insertText = completionInsertText(item, language, state.doc, site.from, site.to);
|
||||
if (item.isSnippet) return lspSnippetToPlainWithCaret(insertText, snippetVariables(path));
|
||||
const parens = editorPrefs().completion.insertParentheses
|
||||
? callParens(item, state.doc.lineAt(site.from), site.from, site.to)
|
||||
: null;
|
||||
const text = item.insertText + (parens ? "()" : "");
|
||||
const text = insertText + (parens ? "()" : "");
|
||||
return { text, caret: text.length - (parens === "inside" ? 1 : 0) };
|
||||
};
|
||||
const texts = sites.map(textAt);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { viewShown, type EditorDocContext } from "@/editor/api";
|
||||
import { setLibraryRoots, viewShown, type EditorDocContext } from "@/editor/api";
|
||||
import { lspDoc } from "./lsp";
|
||||
import type { Diagnostic } from "@/bindings";
|
||||
import {
|
||||
@@ -60,6 +60,20 @@ describe("editor diagnostics store", () => {
|
||||
expect(calls).toBe(3);
|
||||
off();
|
||||
});
|
||||
it("keeps no diagnostics for library sources", () => {
|
||||
const dispose = setLibraryRoots("test", ["/sdk"]);
|
||||
const stop = installDiagnosticsEvents();
|
||||
emitLocalIdeEvent({
|
||||
type: "diagnostics",
|
||||
path: "/sdk/Swift.String.swiftinterface",
|
||||
source: "sk",
|
||||
items: [d(0, 0, 1)],
|
||||
});
|
||||
setFileDiagnostics("/sdk/Swift.String.swiftinterface", "local", [d(1, 0, 1)]);
|
||||
expect(diagnosticsFor("/sdk/Swift.String.swiftinterface")).toEqual([]);
|
||||
stop();
|
||||
dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe("toLintDiagnostics", () => {
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { Diagnostic, Severity } from "@/bindings";
|
||||
import { commands, ideEventsReady, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { publishLocalDiagnostics } from "@/platform/localDiagnostics";
|
||||
import { intentionsChanged, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api";
|
||||
import { intentionsChanged, isLibraryPath, scrollbarMarks, shownAgain, type ScrollbarMark } from "@/editor/api";
|
||||
import { rangeToOffsets } from "./positions";
|
||||
import { lspDoc } from "./lsp";
|
||||
import { showHint } from "./hint";
|
||||
@@ -54,6 +54,9 @@ export function setFileDiagnostics(path: string, source: string, items: Diagnost
|
||||
}
|
||||
|
||||
function storeDiagnostics(path: string, source: string, items: Diagnostic[], published = false) {
|
||||
// A library source opens read-only: errors a server reports in it (an SDK interface it
|
||||
// generated, a dependency's code) are not the user's to fix.
|
||||
if (isLibraryPath(path)) items = [];
|
||||
let sources = byPath.get(path);
|
||||
if (!items.length) {
|
||||
if (!sources?.delete(source) && !published) return;
|
||||
|
||||
@@ -66,6 +66,8 @@ import {
|
||||
isDeclarationName,
|
||||
isSelfTarget,
|
||||
localHighlights,
|
||||
projectIndexDefinitions,
|
||||
usageRole,
|
||||
type DeclarationTarget,
|
||||
} from "./syntaxFallback";
|
||||
import { showHint, showPendingHint } from "./hint";
|
||||
@@ -112,6 +114,27 @@ export async function navigateTo(loc: Location) {
|
||||
await openCodeLocation(loc.path, { line: loc.range.start.line, col: loc.range.start.col });
|
||||
}
|
||||
|
||||
const CLANGD_LANGUAGES = new Set(["c", "cpp", "objective-c", "objective-cpp"]);
|
||||
const CLANGD_SYNTAX_NOTE = "Based on syntax and the project index";
|
||||
const C_HEADER = /\.(?:h|hh|hpp|hxx|h\+\+)$/i;
|
||||
|
||||
/** `pki_check_bin` for `.../pki_check_bin.h`: the stem a source counterpart shares. */
|
||||
function fileStem(path: string): string {
|
||||
const name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
|
||||
const dot = name.lastIndexOf(".");
|
||||
return (dot > 0 ? name.slice(0, dot) : name).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* `pki_check_bin.c` for `pki_check_bin.h`, or every source when no stem matches: the same
|
||||
* declaration can be implemented in another component (a kernel tree holds many copies).
|
||||
*/
|
||||
function counterpartSources(header: string, sources: readonly DeclarationTarget[]): readonly DeclarationTarget[] {
|
||||
const stem = fileStem(header);
|
||||
const own = sources.filter((l) => fileStem(l.path) === stem);
|
||||
return own.length ? own : sources;
|
||||
}
|
||||
|
||||
const NOT_FOUND: Record<GotoKind, string> = {
|
||||
definition: "Cannot find declaration to go to",
|
||||
declaration: "Cannot find declaration to go to",
|
||||
@@ -373,6 +396,18 @@ async function onDeclarationName(view: EditorView, offset: number): Promise<bool
|
||||
return isDeclarationName(at);
|
||||
}
|
||||
|
||||
/** Whether the caret is on a function call, not a declaration whose self-target is legitimate. */
|
||||
async function onCallName(doc: EditorDocContext, pos: Pos): Promise<boolean> {
|
||||
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null);
|
||||
return usageRole(at) === "call";
|
||||
}
|
||||
|
||||
/** A C-family member must come from its receiver's type, not a project-wide bare-name lookup. */
|
||||
async function onMemberName(doc: EditorDocContext, pos: Pos): Promise<boolean> {
|
||||
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }).catch(() => null);
|
||||
return at?.node.kind === "field_identifier" || at?.node.kind === "property_identifier";
|
||||
}
|
||||
|
||||
/**
|
||||
* Go to Implementation targets for Python from the IDE's inheritance graph: its servers
|
||||
* declare no type hierarchy and analyse one root, so the graph also knows the attached
|
||||
@@ -400,7 +435,20 @@ async function implementationFallbackTargets(
|
||||
pos: Pos,
|
||||
): Promise<readonly DeclarationTarget[]> {
|
||||
const declaration = await requestNavigation(view, offset, "definition").catch(() => []);
|
||||
return declaration.filter((l) => !isSelfTarget([l], path, pos));
|
||||
const targets = declaration.filter((l) => !isSelfTarget([l], path, pos));
|
||||
if (targets.length) return targets;
|
||||
const doc = docOf(view);
|
||||
if (!doc || !CLANGD_LANGUAGES.has(doc.language)) return targets;
|
||||
// Without a compilation database clangd only sees this header. Look the name up in the
|
||||
// project index for a source definition; never offer another header declaration.
|
||||
const name = nameAt(view, offset) ?? (offset > 0 ? nameAt(view, offset - 1) : null);
|
||||
if (!name) return targets;
|
||||
const indexed = await projectIndexDefinitions(path, name, "call").catch(() => []);
|
||||
const sources = indexed.filter((l) => !isSelfTarget([l], path, pos) && !C_HEADER.test(l.path));
|
||||
if (!sources.length) return targets;
|
||||
// The caret's own header names the source that implements it: its stem picks that source
|
||||
// among same-name definitions elsewhere instead of turning the jump into a chooser.
|
||||
return C_HEADER.test(path) ? counterpartSources(path, sources) : sources;
|
||||
}
|
||||
|
||||
/** Whether `line` (0-based) of `text` is an import statement. */
|
||||
@@ -495,6 +543,7 @@ async function gotoResolved(
|
||||
const pos = offsetToPos(view.state.doc, offset);
|
||||
let locs: DeclarationTarget[];
|
||||
let fromSyntax = false;
|
||||
let syntaxNote = SYNTAX_NOTE;
|
||||
const declaration = kind === "definition" || kind === "declaration";
|
||||
// A segment of an import path names a file — possibly in a dependency project, which
|
||||
// neither the single-root server nor the name index resolves.
|
||||
@@ -580,6 +629,35 @@ async function gotoResolved(
|
||||
const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos);
|
||||
if (superseded()) return;
|
||||
locs = dedupeLocations(declarationTargets);
|
||||
if (declarationTargets.some((target) => target.name && target.kind)) {
|
||||
fromSyntax = true;
|
||||
syntaxNote = CLANGD_SYNTAX_NOTE;
|
||||
}
|
||||
}
|
||||
// Without a compilation database clangd may not resolve nested #include files. Its empty
|
||||
// answer is not authoritative for these languages; the project index still has the local
|
||||
// declarations. An implicit C declaration can also point at the call itself: replace that
|
||||
// pseudo target only when syntax and the index provide a real target elsewhere.
|
||||
if (declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language)) {
|
||||
const selfTargets = locs.length > 0 && locs.every((l) => isSelfTarget([l], doc.path, pos));
|
||||
if (!locs.length || (selfTargets && (await onCallName(doc, pos)))) {
|
||||
const fallback = await gotoFallback(view, doc, pos, false);
|
||||
if (fallback?.length) {
|
||||
if (!locs.length) {
|
||||
locs = fallback;
|
||||
fromSyntax = true;
|
||||
syntaxNote = CLANGD_SYNTAX_NOTE;
|
||||
} else {
|
||||
const elsewhere = fallback.filter((l) => !isSelfTarget([l], doc.path, pos));
|
||||
if (elsewhere.length) {
|
||||
locs = elsewhere;
|
||||
fromSyntax = true;
|
||||
syntaxNote = CLANGD_SYNTAX_NOTE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (superseded()) return;
|
||||
}
|
||||
if (!locs.length) {
|
||||
// The server has no definition here: a link (`href`, `#include`, Markdown) or a file path.
|
||||
@@ -600,8 +678,12 @@ async function gotoResolved(
|
||||
}
|
||||
// The server only resolves what it sees: answer from the project index, which also
|
||||
// covers attached dependency projects (an unresolved import into them). Never for a
|
||||
// module path: a segment is not a symbol name.
|
||||
if (declaration && !fromSyntax && !moduleName) {
|
||||
// module path: a segment is not a symbol name. A C-family member needs its receiver's
|
||||
// type, so a bare-name dependency lookup would be a guess here too.
|
||||
const clangMember =
|
||||
declaration && !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos));
|
||||
if (superseded()) return;
|
||||
if (declaration && !fromSyntax && !moduleName && !clangMember) {
|
||||
const name = nameAt(view, offset);
|
||||
const targets = name ? await indexDefinitions(doc.path, name).catch(() => []) : [];
|
||||
if (targets.length) {
|
||||
@@ -687,7 +769,7 @@ async function gotoResolved(
|
||||
setTimeout(() => {
|
||||
if (superseded()) return;
|
||||
const target = activeEditor()?.view;
|
||||
if (target) showHint(target, SYNTAX_NOTE, { timeout: 2500 });
|
||||
if (target) showHint(target, syntaxNote, { timeout: 2500 });
|
||||
}, 150);
|
||||
return;
|
||||
}
|
||||
@@ -775,11 +857,16 @@ async function followReferenceAt(
|
||||
}
|
||||
|
||||
/** Declaration targets from the structure service; null when it cannot answer for this file. */
|
||||
async function gotoFallback(view: EditorView, doc: EditorDocContext, pos: Pos): Promise<DeclarationTarget[] | null> {
|
||||
async function gotoFallback(
|
||||
view: EditorView,
|
||||
doc: EditorDocContext,
|
||||
pos: Pos,
|
||||
allowMember = true,
|
||||
): Promise<DeclarationTarget[] | null> {
|
||||
try {
|
||||
await whenSynced(view);
|
||||
const text = view.state.doc;
|
||||
const fb = await declarationFallback(doc, text, pos);
|
||||
const fb = await declarationFallback(doc, text, pos, undefined, allowMember);
|
||||
return fb.kind === "unsupported" ? null : fb.targets;
|
||||
} catch (e) {
|
||||
console.debug("[syntax] declaration fallback", e);
|
||||
@@ -936,11 +1023,14 @@ async function probeNavigation(
|
||||
navigable = !!(await gotoFallback(view, doc, pos))?.length;
|
||||
fromSyntax = true;
|
||||
}
|
||||
if (!navigable && !fromSyntax && CLANGD_LANGUAGES.has(doc.language))
|
||||
navigable = !!(await gotoFallback(view, doc, pos, false))?.length;
|
||||
if (!navigable && WEB_LANGUAGES.has(doc.language) && !doc.virtual)
|
||||
navigable = !!(await lspRequest(() => commands.webGoto(doc.doc, pos)).catch(() => null))?.targets.length;
|
||||
// The index answers across dependency roots too (unresolved imports), but a module path
|
||||
// segment is a file rather than a name.
|
||||
if (!navigable && !fromSyntax) {
|
||||
// segment is a file rather than a name. Keep member probing consistent with the click path.
|
||||
const clangMember = !fromSyntax && CLANGD_LANGUAGES.has(doc.language) && (await onMemberName(doc, pos));
|
||||
if (!navigable && !fromSyntax && !clangMember) {
|
||||
const moduleName = importModuleName(view, doc, offset);
|
||||
if (moduleName) navigable = !!(await moduleFile(doc, moduleName).catch(() => null));
|
||||
else {
|
||||
|
||||
@@ -3,9 +3,11 @@ import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { commands, Location } from "@/platform/ipc";
|
||||
|
||||
const { lspGoto, lspGotoImplementation } = vi.hoisted(() => ({
|
||||
const { lspGoto, lspGotoImplementation, findSymbols, navIndexDefinitions } = vi.hoisted(() => ({
|
||||
lspGoto: vi.fn<typeof commands.lspGoto>(),
|
||||
lspGotoImplementation: vi.fn<typeof commands.lspGotoImplementation>(),
|
||||
findSymbols: vi.fn<typeof commands.findSymbols>(),
|
||||
navIndexDefinitions: vi.fn<typeof commands.navIndexDefinitions>(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
@@ -17,7 +19,15 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => true,
|
||||
commands: { ...real.commands, lspGoto, lspGotoImplementation, fsReadText, navInheritance },
|
||||
commands: {
|
||||
...real.commands,
|
||||
lspGoto,
|
||||
lspGotoImplementation,
|
||||
findSymbols,
|
||||
navIndexDefinitions,
|
||||
fsReadText,
|
||||
navInheritance,
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("@tauri-apps/api/core", async (orig) => ({
|
||||
@@ -60,6 +70,8 @@ beforeEach(() => {
|
||||
invalidateConfigurationNavigation();
|
||||
lspGoto.mockResolvedValue(ok([]));
|
||||
lspGotoImplementation.mockResolvedValue(ok([]));
|
||||
findSymbols.mockResolvedValue({ status: "ok", data: [] });
|
||||
navIndexDefinitions.mockResolvedValue({ status: "ok", data: [] });
|
||||
view = editor(TEXT, "go", "/p/store.go");
|
||||
});
|
||||
afterEach(() => {
|
||||
@@ -154,4 +166,94 @@ describe("Go to Implementation on a symbol nothing implements", () => {
|
||||
await gotoTargets(view, "implementation", text.lastIndexOf("Order") + 2);
|
||||
expect(openFile).toHaveBeenCalledWith("/p/order.py", { selection: { line: 0, col: 6 }, focus: true });
|
||||
});
|
||||
|
||||
it("finds a C source definition from the project index when clangd only returns the header", async () => {
|
||||
const name = "verify_firmware";
|
||||
const text = `int ${name}(const char *signed_fw_path);\n`;
|
||||
const col = text.indexOf(name);
|
||||
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
|
||||
const symbol = (path: string, line: number) => ({
|
||||
name,
|
||||
kind: "function" as const,
|
||||
container: null,
|
||||
path,
|
||||
relPath: path.slice(1),
|
||||
range: { start: { line, col }, end: { line, col: col + name.length } },
|
||||
score: 1,
|
||||
indices: [],
|
||||
});
|
||||
view.destroy();
|
||||
view = editor(text, "c", "/p/pki_check_bin.h");
|
||||
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
|
||||
findSymbols.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [symbol("/p/pki_check_bin.h", 0), symbol("/p/pki_check_bin.c", 190)],
|
||||
});
|
||||
await gotoTargets(view, "implementation", col + 2);
|
||||
expect(findSymbols).toHaveBeenCalledWith(name, "all", 500);
|
||||
expect(openFile).toHaveBeenCalledWith("/p/pki_check_bin.c", { selection: { line: 190, col }, focus: true });
|
||||
expect(navIndexDefinitions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not treat another header declaration as a C implementation", async () => {
|
||||
const name = "verify_firmware";
|
||||
const text = `int ${name}(const char *signed_fw_path);\n`;
|
||||
const col = text.indexOf(name);
|
||||
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
|
||||
view.destroy();
|
||||
view = editor(text, "c", "/p/pki_check_bin.h");
|
||||
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
|
||||
findSymbols.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
{
|
||||
name,
|
||||
kind: "function" as const,
|
||||
container: null,
|
||||
path: "/p/other.h",
|
||||
relPath: "p/other.h",
|
||||
range,
|
||||
score: 1,
|
||||
indices: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
await gotoTargets(view, "implementation", col + 2);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found");
|
||||
});
|
||||
|
||||
it("prefers the header's own source among same-name definitions elsewhere", async () => {
|
||||
const name = "verify_firmware";
|
||||
const text = `int ${name}(const char *signed_fw_path);\n`;
|
||||
const col = text.indexOf(name);
|
||||
const range = { start: { line: 0, col }, end: { line: 0, col: col + name.length } };
|
||||
const symbol = (path: string, line: number) => ({
|
||||
name,
|
||||
kind: "function" as const,
|
||||
container: null,
|
||||
path,
|
||||
relPath: path.slice(1),
|
||||
range: { start: { line, col }, end: { line, col: col + name.length } },
|
||||
score: 1,
|
||||
indices: [],
|
||||
});
|
||||
view.destroy();
|
||||
view = editor(text, "c", "/p/pki_check_bin.h");
|
||||
lspGoto.mockResolvedValue(ok([{ path: "/p/pki_check_bin.h", range }]));
|
||||
findSymbols.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [
|
||||
symbol("/p/pki_check_bin.h", 0),
|
||||
symbol("/p/pki_check_bin.c", 190),
|
||||
symbol("/kernel/5.15/gvt/firmware.c", 149),
|
||||
symbol("/kernel/5.4/gvt/firmware.c", 154),
|
||||
],
|
||||
});
|
||||
await gotoTargets(view, "implementation", col + 2);
|
||||
expect(openFile).toHaveBeenCalledExactlyOnceWith("/p/pki_check_bin.c", {
|
||||
selection: { line: 190, col },
|
||||
focus: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -48,6 +48,8 @@ const { gotoTargets, navigationExtension, highlightUsages } = await import("./na
|
||||
const { registerNavigationProvider } = await import("@/editor/navigationProviders");
|
||||
const { startRename, renameNamePart } = await import("./rename");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
const { usePlatform } = await import("@/platform/platformInfo");
|
||||
const { resetNavigationModifier } = await import("@/platform/navigationModifier");
|
||||
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
|
||||
const { useLspPopup, closePopup } = await import("./popupStore");
|
||||
const { inplaceRenameExtension, inplaceSession } = await import("./inplaceRename");
|
||||
@@ -211,6 +213,36 @@ describe("declarationFallback", () => {
|
||||
expect(res).toMatchObject({ kind: "targets", ambiguous: true });
|
||||
});
|
||||
|
||||
it("can reject a member reported by locals without querying the index", async () => {
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "foo", range: r(1, 6, 9), reason: "member" }));
|
||||
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 }, undefined, false);
|
||||
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
|
||||
expect(cmd.syntaxNodeAt).not.toHaveBeenCalled();
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("can reject a C field node when locals are unavailable", async () => {
|
||||
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("field_identifier", r(1, 6, 9)), ancestors: [] }));
|
||||
const res = await fb.declarationFallback(
|
||||
{ ...doc, language: "c-fields" },
|
||||
text,
|
||||
{ line: 1, col: 7 },
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a no-identifier answer empty outside macro replacement bodies", async () => {
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] }));
|
||||
const res = await fb.declarationFallback(doc, text, { line: 1, col: 7 });
|
||||
expect(res).toEqual({ kind: "targets", targets: [], ambiguous: false });
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the node text for languages without locals, and gives up without a grammar", async () => {
|
||||
cmd.syntaxSupport.mockReturnValueOnce(ok({ tree: true, locals: false }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok({ node: node("identifier", r(1, 6, 9)), ancestors: [] }));
|
||||
@@ -345,6 +377,174 @@ describe("navigation wiring", () => {
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Cannot find declaration to go to");
|
||||
});
|
||||
|
||||
function clangCall(language: string, name = "indirect_call") {
|
||||
const text = `#include "direct.h"\nint main(void) { return ${name}(); }\n`;
|
||||
const path = language === "cpp" || language === "objective-cpp" ? "/p/main.cpp" : "/p/main.c";
|
||||
const col = text.split("\n")[1]!.indexOf(name);
|
||||
const range = r(1, col, col + name.length);
|
||||
const at: NodeAt = {
|
||||
node: node("identifier", range, "function"),
|
||||
ancestors: [node("call_expression", r(1, 0, text.split("\n")[1]!.length))],
|
||||
};
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name, range, reason: "topLevel" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
|
||||
const view = editor(text, language, text.indexOf(name) + 2, path);
|
||||
return { view, path, range, at, name };
|
||||
}
|
||||
|
||||
it.each(["c", "cpp", "objective-c", "objective-cpp"])(
|
||||
"uses the local project index when clangd cannot resolve a nested include in %s",
|
||||
async (language) => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const { view, name } = clangCall(language);
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")]));
|
||||
await gotoTargets(view, "definition");
|
||||
expect(openFile).toHaveBeenCalledWith("/p/include/indirect.h", { selection: { line: 3, col: 4 }, focus: true });
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("resolves a function name inside a C macro replacement body", async () => {
|
||||
const name = "sys_util_read_content";
|
||||
const text = `#define jy_read_country(buf, len) ${name}(FACTORY_DIR "country_code", buf, len)\n`;
|
||||
const col = text.indexOf(name);
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "noIdentifier" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(
|
||||
ok({
|
||||
node: node("preproc_arg", r(0, col, text.length - 1), "value"),
|
||||
ancestors: [node("preproc_function_def", r(0, 0, text.length - 1))],
|
||||
}),
|
||||
);
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")]));
|
||||
const view = editor(text, "c", col + 2, "/p/jy_lib.h");
|
||||
await gotoTargets(view, "definition");
|
||||
expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", {
|
||||
selection: { line: 3, col: 4 },
|
||||
focus: true,
|
||||
});
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("underlines a nested-include call when the hover probe uses the same index fallback", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const { view, name } = clangCall("c");
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/include/indirect.h")]));
|
||||
const os = usePlatform.getState().os;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
resetNavigationModifier();
|
||||
const offset = view.state.doc.toString().indexOf(name) + 2;
|
||||
vi.spyOn(view, "posAtCoords").mockReturnValue(offset);
|
||||
try {
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true }));
|
||||
await vi.waitFor(() => expect(view.dom.querySelector(".cm-lsp-link")).not.toBeNull());
|
||||
} finally {
|
||||
resetNavigationModifier();
|
||||
usePlatform.setState({ os });
|
||||
}
|
||||
});
|
||||
|
||||
it("replaces clangd's implicit-declaration self target with the indexed declaration", async () => {
|
||||
const { view, path, range, at, name } = clangCall("c");
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/jtutil/jt_sys_util.h")]));
|
||||
executeAction.mockClear();
|
||||
await gotoTargets(view, "definition");
|
||||
expect(openFile).toHaveBeenCalledWith("/p/jtutil/jt_sys_util.h", {
|
||||
selection: { line: 3, col: 4 },
|
||||
focus: true,
|
||||
});
|
||||
expect(executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a legitimate declaration self target instead of replacing it from the index", async () => {
|
||||
const name = "indirect_call";
|
||||
const range = r(0, 4, 4 + name.length);
|
||||
const path = "/p/main.c";
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(
|
||||
ok({
|
||||
node: node("identifier", range, "declarator"),
|
||||
ancestors: [node("function_declarator", r(0, 0, 4 + name.length + 8))],
|
||||
}),
|
||||
);
|
||||
const view = editor(`int ${name}(void) { return 0; }\n`, "c", 6, path);
|
||||
executeAction.mockClear();
|
||||
await gotoTargets(view, "definition");
|
||||
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps clangd's original self target when the local index has no better answer", async () => {
|
||||
const { view, path, range, at } = clangCall("c");
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([{ path, range }]));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at));
|
||||
executeAction.mockClear();
|
||||
await gotoTargets(view, "definition");
|
||||
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not guess a C member declaration from unrelated project symbols", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const range = r(0, 3, 10);
|
||||
const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] };
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok({ status: "notLocal", name: "handler", range, reason: "member" }));
|
||||
cmd.syntaxNodeAt.mockReturnValueOnce(ok(at)).mockReturnValueOnce(ok(at));
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")]));
|
||||
try {
|
||||
const view = editor("s->handler();\n", "c", 5, "/p/main.c");
|
||||
await gotoTargets(view, "definition");
|
||||
expect(cmd.findSymbols).not.toHaveBeenCalled();
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([]));
|
||||
}
|
||||
});
|
||||
|
||||
it("does not underline a C member from a bare-name dependency candidate", async () => {
|
||||
const range = r(0, 3, 10);
|
||||
const at: NodeAt = { node: node("field_identifier", range, "field"), ancestors: [] };
|
||||
cmd.lspGoto.mockReturnValue(ok([]));
|
||||
cmd.syntaxLocals.mockReturnValue(ok({ status: "notLocal", name: "handler", range, reason: "member" }));
|
||||
cmd.syntaxNodeAt.mockReturnValue(ok(at));
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([sym("handler", "method", "/p/other.c")]));
|
||||
const view = editor("s->handler();\n", "c", 5, "/p/main.c");
|
||||
const os = usePlatform.getState().os;
|
||||
usePlatform.setState({ os: "macos" });
|
||||
resetNavigationModifier();
|
||||
vi.spyOn(view, "posAtCoords").mockReturnValue(5);
|
||||
try {
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, metaKey: true }));
|
||||
await vi.waitFor(() => expect(cmd.syntaxNodeAt).toHaveBeenCalled());
|
||||
expect(view.dom.querySelector(".cm-lsp-link")).toBeNull();
|
||||
expect(cmd.navIndexDefinitions).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
resetNavigationModifier();
|
||||
usePlatform.setState({ os });
|
||||
cmd.lspGoto.mockReturnValue(unavailable());
|
||||
cmd.syntaxLocals.mockReturnValue(ok({ status: "noIdentifier" }));
|
||||
cmd.syntaxNodeAt.mockReturnValue(ok(null));
|
||||
cmd.navIndexDefinitions.mockReturnValue(ok([]));
|
||||
}
|
||||
});
|
||||
|
||||
it("shows ambiguous nested-include declarations as syntax-based candidates", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
const { view, name } = clangCall("c");
|
||||
cmd.findSymbols.mockReturnValueOnce(ok([sym(name, "function", "/p/a.c"), sym(name, "function", "/p/include/a.h")]));
|
||||
await gotoTargets(view, "definition");
|
||||
const popup = useLspPopup.getState().popup;
|
||||
expect(popup?.kind).toBe("list");
|
||||
if (popup?.kind !== "list") return;
|
||||
expect(popup.title).toBe(`Choose Declaration of ${name} (2 found, based on syntax)`);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("answers from the index when the server cannot resolve an import into a dependency project", async () => {
|
||||
cmd.lspGoto.mockReturnValueOnce(ok([]));
|
||||
cmd.navIndexDefinitions.mockReturnValueOnce(ok([sym("ParallelDims", "class", "/deps/engine/model.py")]));
|
||||
|
||||
@@ -154,6 +154,20 @@ export async function indexDefinitions(path: string, name: string): Promise<Decl
|
||||
);
|
||||
}
|
||||
|
||||
/** Exact-name declarations from the whole project index, filtered by use and language family. */
|
||||
export async function projectIndexDefinitions(
|
||||
path: string,
|
||||
name: string,
|
||||
role: UsageRole,
|
||||
): Promise<DeclarationTarget[]> {
|
||||
const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT));
|
||||
const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(path, s.path));
|
||||
return rankTargets(
|
||||
symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })),
|
||||
path,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Go to Declaration without a language server: a certain local definition,
|
||||
* otherwise project index symbols with exactly that name (filtered by the
|
||||
@@ -164,32 +178,43 @@ export async function declarationFallback(
|
||||
text: Text,
|
||||
pos: Pos,
|
||||
signal?: AbortSignal,
|
||||
allowMember = true,
|
||||
): Promise<DeclarationFallback> {
|
||||
const support = await structure.support(doc.language);
|
||||
if (!support.tree) return { kind: "unsupported" };
|
||||
let locals: Locals | null = null;
|
||||
if (support.locals) locals = await structure.locals(doc.doc, pos, { signal });
|
||||
if (locals?.status === "noIdentifier") return { kind: "targets", targets: [], ambiguous: false };
|
||||
if (locals?.status === "local") return { kind: "targets", ...localTargets(doc.path, locals.symbol) };
|
||||
if (!allowMember && locals?.status === "notLocal" && locals.reason === "member")
|
||||
return { kind: "targets", targets: [], ambiguous: false };
|
||||
|
||||
const at = await structure.nodeAt(doc.doc, { start: pos, end: pos }, { signal });
|
||||
const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at);
|
||||
if (locals?.status === "noIdentifier" && at?.node.kind !== "preproc_arg")
|
||||
return { kind: "targets", targets: [], ambiguous: false };
|
||||
if (!allowMember && at?.node.kind === "field_identifier") return { kind: "targets", targets: [], ambiguous: false };
|
||||
const name = locals?.status === "notLocal" ? locals.name : identifierText(text, at, pos);
|
||||
if (!name) return { kind: "targets", targets: [], ambiguous: false };
|
||||
// A member (`obj.name`) can be any member of that name; only a plain name has a syntactic role.
|
||||
const role = locals?.status === "notLocal" && locals.reason === "member" ? "other" : usageRole(at);
|
||||
const matches = await call(commands.findSymbols(name, "all", SYMBOL_LIMIT));
|
||||
const symbols = filterSymbols(matches, name, role).filter((s) => compatibleFiles(doc.path, s.path));
|
||||
const targets = rankTargets(
|
||||
symbols.map((s) => ({ path: s.path, range: s.range, name: s.name, kind: s.kind, container: s.container })),
|
||||
doc.path,
|
||||
);
|
||||
const targets = await projectIndexDefinitions(doc.path, name, role);
|
||||
return { kind: "targets", targets, ambiguous: targets.length > 1 };
|
||||
}
|
||||
|
||||
const IDENT = /^[\p{L}_$][\p{L}\p{N}_$]*$/u;
|
||||
const IDENT_PART = /[\p{L}\p{N}_$]/u;
|
||||
|
||||
/** Name of a leaf identifier node (languages without `locals.scm`). */
|
||||
function identifierText(text: Text, at: NodeAt | null): string | null {
|
||||
/** Name of a leaf identifier node, or the identifier at `pos` in a macro replacement body. */
|
||||
function identifierText(text: Text, at: NodeAt | null, pos: Pos): string | null {
|
||||
if (at?.node.kind === "preproc_arg") {
|
||||
if (pos.line >= text.lines) return null;
|
||||
const line = text.line(pos.line + 1).text;
|
||||
let from = Math.min(pos.col, line.length);
|
||||
let to = from;
|
||||
while (from > 0 && IDENT_PART.test(line[from - 1]!)) from--;
|
||||
while (to < line.length && IDENT_PART.test(line[to]!)) to++;
|
||||
const name = line.slice(from, to);
|
||||
return IDENT.test(name) ? name : null;
|
||||
}
|
||||
if (!at || !/identifier|^name$|^constant$|^word$/.test(at.node.kind)) return null;
|
||||
const { from, to } = rangeToOffsets(text, at.node.range);
|
||||
const name = text.sliceString(from, to);
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
* The cache outlives the editor view (switching tabs remounts it) until other
|
||||
* files change, a language server settles or its classpath changes: on some servers (jdtls) every
|
||||
* implementation search walks the whole workspace, so asking again is costly.
|
||||
* Library sources ask no inheritors from the server (`isLibrarySource`).
|
||||
* Library sources ask no inheritors from the server (`isLibrarySource`); explicit
|
||||
* Go to Implementation still answers.
|
||||
*/
|
||||
import { RangeSet, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
@@ -826,11 +827,13 @@ class MarkersPlugin {
|
||||
}
|
||||
|
||||
/**
|
||||
* In a library every method's overriders would be searched for across the whole project,
|
||||
* one search per visible method: only its classes and interfaces get ↓ markers.
|
||||
* Library symbols are referenced everywhere, so an inheritor search walks the whole
|
||||
* project and its dependencies (jdtls builds a full type hierarchy). A JDK interface
|
||||
* such as `java.util.function.Function` then keeps the status bar at "Creating type
|
||||
* hierarchy" and times out. Keep super-method markers, but ask for no inheritors.
|
||||
*/
|
||||
export function libraryCandidates(candidates: readonly MarkerCandidate[]): MarkerCandidate[] {
|
||||
return candidates.map((c) => (c.method && c.inheritable ? { ...c, inheritable: false } : c));
|
||||
return candidates.map((c) => ({ ...c, inheritable: false, implicit: false }));
|
||||
}
|
||||
|
||||
/** LSP access for one pass: this document's outline as known, others' opened on demand, each asked once. */
|
||||
|
||||
@@ -517,18 +517,22 @@ describe("library sources", () => {
|
||||
[`${SHAPE_PATH}:1`]: [loc("/p/Circle.java", 2, 18), loc("/p/Square.java", 1, 18)],
|
||||
};
|
||||
|
||||
it("ask for the inheritors of types only, not one project-wide search per method", async () => {
|
||||
it("ask for no inheritors: a library type's search walks the whole project and its dependencies", async () => {
|
||||
const { deps, calls } = server(shapeImpls, {});
|
||||
const candidates = libraryCandidates(markerCandidates(SHAPE_OUTLINE, lines(SHAPE)));
|
||||
const cache = emptyCache();
|
||||
await fillMarkers(SHAPE_PATH, candidates, ALL, deps(SHAPE_PATH), cache);
|
||||
expect(calls.implementations).toEqual([[{ line: 0, col: 17 }]]);
|
||||
expect(cachedMarkers(candidates, ALL, cache).map((m) => [m.line, m.kind, m.tooltip])).toEqual([
|
||||
[0, "implemented", "Is implemented by Circle, Square"],
|
||||
]);
|
||||
expect(calls.implementations).toEqual([]);
|
||||
expect(calls.subtypes).toBe(0);
|
||||
expect(cachedMarkers(candidates, ALL, cache)).toEqual([]);
|
||||
});
|
||||
|
||||
it("still ask the server for inheritors and subtypes", async () => {
|
||||
it("also drops Go's implicit interface queries", () => {
|
||||
const candidates = libraryCandidates(markerCandidates(GO_OUTLINE, lines(GO), { implicitInterfaces: true }));
|
||||
expect(candidates.some((c) => c.inheritable || c.implicit)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps super-method queries available without enabling inheritor searches", async () => {
|
||||
const off = setLibraryRoots("test", ["/venv/site-packages"]);
|
||||
try {
|
||||
const library = {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useId, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import type { AgentForm, AgentFormField, AgentTask } from "@/bindings";
|
||||
import { Button, Checkbox, Input, Radio, T } from "@/ui";
|
||||
import type { PermissionEntry } from "./permission";
|
||||
@@ -48,7 +49,7 @@ export function FormCard({ task, entry, form }: { task: AgentTask; entry: Permis
|
||||
};
|
||||
return (
|
||||
<form
|
||||
className={styles.questionCard}
|
||||
className={clsx(styles.questionCard, styles.questionCardPinned)}
|
||||
aria-label={entry.title}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -1632,9 +1632,11 @@
|
||||
font-size: var(--agent-fs-ui, var(--fs-ui));
|
||||
container: question-card / inline-size;
|
||||
}
|
||||
/* A question that outlived its turn waits above the composer, at the composer's width. */
|
||||
/* A question that outlived its turn waits above the composer, at the composer's width. It scrolls within at most
|
||||
half the window, and less when the session is shorter, so the composer and the card's buttons stay in view. */
|
||||
.questionCardPinned {
|
||||
flex: none;
|
||||
flex: 0 1 auto;
|
||||
min-height: 0;
|
||||
max-height: 50vh;
|
||||
overflow-y: auto;
|
||||
width: 100%;
|
||||
|
||||
@@ -276,6 +276,74 @@ describe("build feature", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps output the channel delivers after the build result (an >8 KiB line is fetched late)", async () => {
|
||||
// Tauri sends a channel message over 8 KiB through an async fetch and holds every later message
|
||||
// back to keep their order, so the command's result can arrive before the rest of the output.
|
||||
const run = startBuild("build");
|
||||
await act(async () => {});
|
||||
const long = `${"w".repeat(8_307)}`;
|
||||
const warning = warn("/p/src/B.java", 2);
|
||||
await act(async () => {
|
||||
fake.emit!({ kind: "output", text: "short\n", stderr: false });
|
||||
fake.resolve(result([warning], true));
|
||||
await run;
|
||||
});
|
||||
expect(useBuildRun.getState().status).toBe("success");
|
||||
await act(async () => {
|
||||
fake.emit!({ kind: "output", text: `${long}\n`, stderr: false });
|
||||
fake.emit!({ kind: "output", text: "stream-done\n", stderr: false });
|
||||
fake.emit!({ kind: "message", message: warning });
|
||||
fake.emit!({ kind: "progress", message: "late", fraction: null });
|
||||
fake.emit!({ kind: "output", text: "\nProcess finished with exit code 0\n", stderr: false });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
});
|
||||
const s = useBuildRun.getState();
|
||||
expect(s.lines.map((l) => l.text)).toEqual(["short", long, "stream-done", "", "Process finished with exit code 0"]);
|
||||
// The result already carries every message; a late one is not added twice.
|
||||
expect(s.messages).toEqual([warning]);
|
||||
expect(s.message).toBeNull();
|
||||
|
||||
// A newer build owns the console: the old channel's stragglers are dropped.
|
||||
const stale = fake.emit!;
|
||||
const second = startBuild("build");
|
||||
await act(async () => {});
|
||||
await act(async () => {
|
||||
stale({ kind: "output", text: "stale\n", stderr: false });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
});
|
||||
expect(useBuildRun.getState().lines.map((l) => l.text)).not.toContain("stale");
|
||||
await act(async () => {
|
||||
fake.resolve(result([], true));
|
||||
await second;
|
||||
});
|
||||
});
|
||||
|
||||
it("drops a finished build's late events once a launch build owns the Build window", async () => {
|
||||
const run = startBuild("build");
|
||||
await act(async () => {});
|
||||
const late = fake.emit!;
|
||||
await act(async () => {
|
||||
fake.resolve(result([], true));
|
||||
await run;
|
||||
});
|
||||
const follower = followLaunchBuild(44 as never, "Build before launch: App");
|
||||
follower.onEvent({ kind: "started", system: "maven", title: "launch" });
|
||||
await act(async () => {
|
||||
late({ kind: "step", command: "stale-step", cwd: "/stale" });
|
||||
late({ kind: "output", text: "stale\n", stderr: false });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
});
|
||||
const s = useBuildRun.getState();
|
||||
expect(s.lines.map((l) => l.text)).not.toContain("stale");
|
||||
expect(s.stepCwd).toBeNull();
|
||||
follower.finish("success");
|
||||
await act(async () => {
|
||||
late({ kind: "output", text: "stale2\n", stderr: false });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
});
|
||||
expect(useBuildRun.getState().lines.map((l) => l.text)).not.toContain("stale2");
|
||||
});
|
||||
|
||||
it("streams a failing build into the tree and console, then notifies and clears next time", async () => {
|
||||
const run = startBuild("build");
|
||||
await act(async () => {});
|
||||
|
||||
@@ -237,6 +237,9 @@ export async function startCompileFile(file: string, activate = true): Promise<B
|
||||
);
|
||||
}
|
||||
|
||||
/** The latest build: its channel may still deliver output after its result (see `executeBuild`). */
|
||||
let currentBuild: RequestId | null = null;
|
||||
|
||||
/** Streams one backend build into the Build tool window until it finishes. */
|
||||
async function executeBuild(
|
||||
request: RequestId,
|
||||
@@ -246,6 +249,13 @@ async function executeBuild(
|
||||
cancel: () => void,
|
||||
): Promise<BuildResult | null> {
|
||||
const ownsBuild = () => useBuildRun.getState().request === request;
|
||||
currentBuild = request;
|
||||
// Tauri delivers a channel message over 8 KiB through an async fetch and holds the later ones back
|
||||
// to keep their order, so output can still arrive after the command's result. It belongs to this
|
||||
// build until another build (or a launch build) takes the window; messages and progress are complete
|
||||
// in the result by then.
|
||||
const accepts = () => currentBuild === request;
|
||||
let finished = false;
|
||||
await maybeEditorService()
|
||||
?.saveAll()
|
||||
.catch(() => undefined);
|
||||
@@ -258,15 +268,17 @@ async function executeBuild(
|
||||
timer = undefined;
|
||||
const events = queue;
|
||||
queue = [];
|
||||
if (!ownsBuild() || !events.length) return;
|
||||
if (!accepts() || !events.length) return;
|
||||
let s = useBuildRun.getState();
|
||||
for (const e of events) s = { ...s, ...applyBuildEvent(s, e) };
|
||||
for (const e of events) {
|
||||
if (!finished || e.kind === "output" || e.kind === "step") s = { ...s, ...applyBuildEvent(s, e) };
|
||||
}
|
||||
useBuildRun.setState(s);
|
||||
if (s.message)
|
||||
if (!finished && s.message)
|
||||
upsertTask({ id: BUILD_TASK_ID, title: taskTitle, message: s.message, fraction: null, done: false, cancel });
|
||||
};
|
||||
const onEvent = (e: BuildEvent) => {
|
||||
if (!ownsBuild()) return;
|
||||
if (!accepts()) return;
|
||||
queue.push(e);
|
||||
timer ??= setTimeout(flush, 16);
|
||||
};
|
||||
@@ -276,6 +288,7 @@ async function executeBuild(
|
||||
result = await invoke(useBuildRun.getState().files, onEvent);
|
||||
if (!ownsBuild()) return null;
|
||||
flush();
|
||||
finished = true;
|
||||
const status: BuildStatus = result.success ? "success" : "failed";
|
||||
useBuildRun.setState({
|
||||
status,
|
||||
@@ -311,6 +324,7 @@ async function executeBuild(
|
||||
} catch (e) {
|
||||
if (!ownsBuild()) return null;
|
||||
flush();
|
||||
finished = true;
|
||||
if (isCancelled(e)) {
|
||||
useBuildRun.setState({ status: "cancelled", files: [], message: null });
|
||||
} else {
|
||||
@@ -385,6 +399,7 @@ export function followLaunchBuild(
|
||||
const take = () => {
|
||||
if (owned || isBuilding()) return;
|
||||
owned = true;
|
||||
currentBuild = null;
|
||||
const previous = useBuildRun.getState().files;
|
||||
useBuildRun.setState({ ...INITIAL, request, kind: "build", title, status: "running", files: previous });
|
||||
setContext(BUILD_LAST_STATUS, null);
|
||||
@@ -458,6 +473,7 @@ export function rerunBuild() {
|
||||
}
|
||||
|
||||
export function resetBuildRun() {
|
||||
currentBuild = null;
|
||||
stopBuild();
|
||||
removeTask(BUILD_TASK_ID);
|
||||
setContext(BUILD_RUNNING, false);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { Diagnostic } from "@/bindings";
|
||||
import { setLibraryRoots } from "@/editor/api";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
applyDiagnosticsEvent,
|
||||
@@ -300,3 +301,15 @@ describe("incremental bookkeeping", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("library sources", () => {
|
||||
beforeEach(() => clearProblems());
|
||||
|
||||
it("are not the project's problems", () => {
|
||||
const dispose = setLibraryRoots("test", ["/sdk"]);
|
||||
applyDiagnosticsEvent("/sdk/Foundation.swiftinterface", "sk", [d(1)]);
|
||||
applyDiagnosticsEvent("/p/main.swift", "sk", [d(2)]);
|
||||
expect([...useProblems.getState().map.keys()]).toEqual(["/p/main.swift"]);
|
||||
dispose();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import type { Diagnostic, Severity } from "@/bindings";
|
||||
import { isLibraryPath } from "@/editor/api";
|
||||
import { onIdeEvent } from "@/platform/ipc";
|
||||
import { onLocalDiagnostics } from "@/platform/localDiagnostics";
|
||||
import {
|
||||
@@ -256,6 +257,8 @@ function applyTo(snapshot: ProblemsSnapshot, path: string, source: string, items
|
||||
}
|
||||
|
||||
export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) {
|
||||
// Library sources (an SDK interface, a dependency's code) are not the project's problems.
|
||||
if (isLibraryPath(path)) items = [];
|
||||
useProblems.setState((s) => {
|
||||
// The file's sources map is replaced, not changed, so this is the list before the event.
|
||||
const before = mergedSources(s.map.get(path));
|
||||
|
||||
@@ -245,7 +245,11 @@ describe("remote attach requests", () => {
|
||||
port: 9229,
|
||||
localRoot: "/p",
|
||||
remoteRoot: "/usr/src/app",
|
||||
autoAttachChildProcesses: false,
|
||||
});
|
||||
// Without a remote root the program may be local, and its child processes are followed.
|
||||
const local = JSON.parse(remoteAttachConfig(configOf(nodeRemoteType), "/p")!.extraJson!);
|
||||
expect(local).not.toHaveProperty("autoAttachChildProcesses");
|
||||
});
|
||||
|
||||
it("Attach to Node.js reconnects automatically only when the option is on", () => {
|
||||
|
||||
@@ -502,7 +502,11 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig |
|
||||
type: "pwa-node",
|
||||
address: host,
|
||||
port: portOf(p, 9229),
|
||||
...(map ? { localRoot: map.local, remoteRoot: map.remote } : {}),
|
||||
// On a loopback address (a published container port, an SSH tunnel) js-debug makes the
|
||||
// program require its child-process bootloader by a path on this machine. Behind a
|
||||
// remote root that path is missing: tsx's esbuild worker dies of it and the program
|
||||
// waits for that worker forever.
|
||||
...(map ? { localRoot: map.local, remoteRoot: map.remote, autoAttachChildProcesses: false } : {}),
|
||||
skipFiles: skip ? ["<node_internals>/**", "**/node_modules/**"] : [],
|
||||
...(p.restart === "true" ? { restart: true } : {}),
|
||||
});
|
||||
|
||||
@@ -5,7 +5,8 @@ import { useProject } from "@/platform/project";
|
||||
import { usePlugins } from "./store";
|
||||
import { useEditorRegistry } from "@/editor/api";
|
||||
import { lspDoc } from "@/editor/lsp/lsp";
|
||||
import { synchronizeDocumentIndexes } from "@/workbench/contributions";
|
||||
import { notifications, provideNotificationService, synchronizeDocumentIndexes } from "@/workbench/contributions";
|
||||
import { setLocale, txTemplate, useI18n } from "@/platform/i18n";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
files: vi.fn(),
|
||||
@@ -215,3 +216,29 @@ it("keeps unrelated language-server queries available when plugin discovery fail
|
||||
await expect(synchronizeDocumentIndexes("/project/notes.txt", "refactor")).resolves.toBe(true);
|
||||
expect(mocks.index).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("indexes the first files of a large project and says how many it covers, in one sentence", async () => {
|
||||
mocks.files.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { paths: ["/project/A.java"], indexing: false, extensions: ["java"], total: 28684, truncated: true },
|
||||
});
|
||||
useProject.setState({ project: { root: "/project", name: "big-demo", trusted: true } as never });
|
||||
const notify = vi.fn();
|
||||
const previous = notifications();
|
||||
const locale = useI18n.getState().locale;
|
||||
provideNotificationService({ notify } as never);
|
||||
try {
|
||||
await setLocale("zh");
|
||||
off = startPluginNavigation();
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
expect(mocks.index.mock.calls[0]?.[0]).toEqual(["/project/A.java"]);
|
||||
expect(notify).toHaveBeenCalledTimes(1);
|
||||
const body = notify.mock.calls[0]![0].body;
|
||||
expect(body).toBe("插件导航仅覆盖 big-demo 中 28,684 个文件里的 1 个;可排除文件夹以缩小范围");
|
||||
// The balloon and the OS toast look the text up again: it stays whole.
|
||||
expect(txTemplate(body)).toBe(body);
|
||||
} finally {
|
||||
provideNotificationService(previous);
|
||||
await setLocale(locale);
|
||||
}
|
||||
});
|
||||
@@ -47,6 +47,19 @@ export function startPluginNavigation(): () => void {
|
||||
body: String(error),
|
||||
});
|
||||
}
|
||||
let reportedTruncated = false;
|
||||
function reportTruncated(count: number, total: number) {
|
||||
if (reportedTruncated) return;
|
||||
reportedTruncated = true;
|
||||
const project = useProject.getState().project;
|
||||
const name = project?.displayName || project?.name || "";
|
||||
notifications().notify({
|
||||
group: "plugins",
|
||||
level: "warning",
|
||||
title: "Plugin navigation indexing incomplete",
|
||||
body: tx`Plugin navigation covers ${count.toLocaleString()} of ${total.toLocaleString()} files in ${name}; exclude folders to narrow it`,
|
||||
});
|
||||
}
|
||||
let fileExtensions = new Set<string>();
|
||||
const extensions = () => fileExtensions;
|
||||
const eligible = (path: string) => extensions().has(path.split(".").pop() ?? "");
|
||||
@@ -142,6 +155,7 @@ export function startPluginNavigation(): () => void {
|
||||
inventory.paths.forEach((p) => known.add(p));
|
||||
queue(fresh);
|
||||
queue([...views.values()], true);
|
||||
if (inventory.truncated) reportTruncated(inventory.paths.length, inventory.total);
|
||||
} catch (error) {
|
||||
discovered = false;
|
||||
discoveryFailed = true;
|
||||
@@ -165,6 +179,7 @@ export function startPluginNavigation(): () => void {
|
||||
discoveryFailed = false;
|
||||
discovery = null;
|
||||
reportedError = false;
|
||||
reportedTruncated = false;
|
||||
notify();
|
||||
if (ready())
|
||||
void call(commands.pluginNavigationInvalidate(null))
|
||||
|
||||
@@ -7,6 +7,7 @@ import { applyKeymapSettings, installKeyboardDispatcher, useKeymap } from "@/pla
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import {
|
||||
provideEditorService,
|
||||
registerExternalFileOpenHandler,
|
||||
registerProjectViewRoot,
|
||||
setFileDecorations,
|
||||
type EditorService,
|
||||
@@ -493,6 +494,28 @@ describe("ProjectView", () => {
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
|
||||
});
|
||||
|
||||
it("selects a file opened externally on single click and opens it on double click", async () => {
|
||||
fs = new MemoryFs({ "/w/acme/notes.docx": "x" }, ROOT);
|
||||
setProjectFsForTests(fs, ROOT);
|
||||
initProjectTree(ROOT, "acme");
|
||||
const disposeExternal = registerExternalFileOpenHandler({
|
||||
id: "test.external",
|
||||
matches: (path) => path.endsWith(".docx"),
|
||||
open: vi.fn(async () => true),
|
||||
});
|
||||
try {
|
||||
const { row, rows } = setup();
|
||||
await waitFor(() => expect(rows()).toContain("notes.docx"));
|
||||
const content = row("notes.docx").querySelector("[data-project-path]")!;
|
||||
fireEvent.click(content, { detail: 1 });
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
fireEvent.doubleClick(row("notes.docx"));
|
||||
expect(openFile).toHaveBeenLastCalledWith("/w/acme/notes.docx", { preview: undefined, focus: true });
|
||||
} finally {
|
||||
disposeExternal();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens a selected file in a read-only Quick Preview with Space without creating an editor tab", async () => {
|
||||
dispatchViaKeymap();
|
||||
ipc.fsReadText.mockResolvedValue(ok("# Preview\n\nRead without opening a tab."));
|
||||
|
||||
@@ -34,6 +34,7 @@ import { macStroke, strokeOf } from "@/platform/keymap";
|
||||
import {
|
||||
OWNS_FILE_DROP,
|
||||
getFileDecoration,
|
||||
opensExternally,
|
||||
prepareMenuGroups,
|
||||
useFileDecoration,
|
||||
useFileDecorations,
|
||||
@@ -718,6 +719,7 @@ export function ProjectView() {
|
||||
if (o.singleClickExpand) toggleExpanded(node);
|
||||
return;
|
||||
}
|
||||
if (opensExternally(node.path)) return;
|
||||
if (!o.singleClickOpen && !previewTabEnabled()) return;
|
||||
const opts = { preview: o.singleClickOpen ? undefined : true, focus: false };
|
||||
if (node.member) void revealRange(node.path, { start: node.member.selection_range.start }, opts);
|
||||
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача