дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
36
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
462f4a5e1d | ||
|
|
1cfbb24b31 | ||
|
|
a8a0cdb315 | ||
|
|
8ab776ada6 | ||
|
|
88b463d888 | ||
|
|
ac88059d0f | ||
|
|
a09c9aa9ad | ||
|
|
7fef1e10a8 | ||
|
|
1748c98ac8 | ||
|
|
399ae25ab6 | ||
|
|
f28dd8125b | ||
|
|
d5f7e0a99b | ||
|
|
a66c9e6d05 | ||
|
|
59bcf7eac5 | ||
|
|
fe21c67537 | ||
|
|
c085f52b59 | ||
|
|
0104ed63c1 | ||
|
|
a441b2a906 | ||
|
|
c4f7fec86c | ||
|
|
37a8aae018 | ||
|
|
acc48a4816 | ||
|
|
8301326289 | ||
|
|
4c71299745 | ||
|
|
08249ca5fd | ||
|
|
edd6746439 | ||
|
|
695424beb2 | ||
|
|
9943d71d02 | ||
|
|
e03c5507f7 | ||
|
|
745099feaa | ||
|
|
6894d0a4e3 | ||
|
|
f80be658ea | ||
|
|
1c377b7f66 | ||
|
|
093cf6fdf8 | ||
|
|
9b578c2fad | ||
|
|
f5bb97babd | ||
|
|
e23088d558 |
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,6 +655,26 @@ pub async fn lsp_file_references(
|
||||
result
|
||||
}
|
||||
|
||||
/// The header of the document's source file or the source of its header (C, C++,
|
||||
/// Objective-C) as clangd finds it; `None` without clangd or an answer. Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_switch_source_header(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
doc: DocId,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let lsp = host.project(window)?.lsp.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::select! {
|
||||
result = lsp.switch_source_header(doc, cancel.clone()) => result,
|
||||
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
|
||||
};
|
||||
host.end_request(request);
|
||||
Ok(result?.map(|path| path.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
/// Implementations of the symbols at `positions`, one list per position (the
|
||||
/// editor's "is implemented / overridden" gutter markers). Cancel with
|
||||
/// `cancel_request(request)`.
|
||||
@@ -2409,6 +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::*;
|
||||
@@ -3294,6 +3343,7 @@ ide_command::domain!(
|
||||
lsp_hover,
|
||||
lsp_implementation_locations,
|
||||
lsp_file_references,
|
||||
lsp_switch_source_header,
|
||||
lsp_implementations,
|
||||
lsp_inlay_hints,
|
||||
lsp_inline_completion,
|
||||
|
||||
@@ -454,7 +454,10 @@ async fn start_inner(
|
||||
if ide_run::is_python_kind(&config.kind) {
|
||||
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
|
||||
}
|
||||
let config = container::prepare(host, &project.root, target, config).await?;
|
||||
let (config, note) = container::prepare(host, &project.root, target, config).await?;
|
||||
if let Some(note) = note {
|
||||
on_output(OutputChunk::System { text: format!("{note}\n") });
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
|
||||
@@ -6,8 +6,8 @@ use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_remote::docker::{
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root,
|
||||
compose_service, container_config, container_name, default_container_root,
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, NODE_DEBUG_FOLDER,
|
||||
compose_container_root, compose_service, container_config, container_name, default_container_root, node_debug,
|
||||
};
|
||||
use ide_remote::target::DEBUG_PARAM;
|
||||
use ide_run::RunConfig;
|
||||
@@ -16,15 +16,21 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service.
|
||||
pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config: RunConfig) -> IdeResult<RunConfig> {
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service, and for a
|
||||
/// Node.js debug run the line telling the debugger the project folder in the container.
|
||||
pub(super) async fn prepare(
|
||||
host: &Host,
|
||||
root: &Path,
|
||||
target: RunTarget,
|
||||
config: RunConfig,
|
||||
) -> IdeResult<(RunConfig, Option<String>)> {
|
||||
if config.kind == "dotnet" || config.kind == "dotnet-test" {
|
||||
return Err(IdeError::invalid(".NET Project requires the local machine"));
|
||||
}
|
||||
let debug = config.extras.params.get(DEBUG_PARAM).is_some_and(|v| v == "true");
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") {
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") && !node_debug(&config) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' can't be debugged in a container: only Python run configurations can",
|
||||
"'{}' can't be debugged in a container: only Python and Node.js run configurations can",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
@@ -41,7 +47,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
let (service_env, service_ports) = server_context(&data_dir, &root, &target, &config);
|
||||
let name = container_name(&config.id, &unique());
|
||||
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
|
||||
container_config(
|
||||
let note = (debug && node_debug(&config)).then(|| format!("{NODE_DEBUG_FOLDER}{container_root}"));
|
||||
let config = container_config(
|
||||
&config,
|
||||
&ContainerRun {
|
||||
target: &target,
|
||||
@@ -60,7 +67,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
debugpy: d.debugpy.as_deref(),
|
||||
}),
|
||||
},
|
||||
)
|
||||
)?;
|
||||
Ok((config, note))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -222,6 +222,8 @@ impl Host {
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
|
||||
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
|
||||
let styled = ide_tools::managed_npm_plugin(&data_dir, "typescript-styled-plugin");
|
||||
ide_sdk::apply::configure_styled(cfg, server_root, styled.as_deref());
|
||||
// After the global plugins: they keep the IDE's copies.
|
||||
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
|
||||
let container_python = effective.languages.python.run_target().is_some();
|
||||
|
||||
@@ -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)> {
|
||||
|
||||
@@ -37,6 +37,7 @@ mod pull;
|
||||
mod scope;
|
||||
mod server;
|
||||
mod source_actions;
|
||||
mod switch_source_header;
|
||||
mod tcp;
|
||||
mod text;
|
||||
mod ts_file_moves;
|
||||
@@ -326,6 +327,25 @@ fn goto_is_empty(r: &Option<lsp::GotoDefinitionResponse>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the caret is on the method name of a Java method reference (`Type::method`).
|
||||
/// A method reference can name a functional interface's method through JDT's selection-based
|
||||
/// definition when the referenced method is inherited, so ask the AST binding command instead.
|
||||
fn java_method_reference_at(text: &DocText, pos: Pos) -> bool {
|
||||
let line = text.line(pos.line as usize);
|
||||
let mut utf16 = 0u32;
|
||||
let mut at = line.len();
|
||||
for (i, c) in line.char_indices() {
|
||||
if utf16 >= pos.col {
|
||||
at = i;
|
||||
break;
|
||||
}
|
||||
utf16 += c.len_utf16() as u32;
|
||||
}
|
||||
let before = line[..at].trim_end();
|
||||
let Some(colon) = before.rfind("::") else { return false };
|
||||
before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
|
||||
}
|
||||
|
||||
fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
|
||||
match e {
|
||||
RpcError::Cancelled => IdeError::cancelled(),
|
||||
@@ -1792,7 +1812,31 @@ impl LspManager {
|
||||
}
|
||||
let (method, cap, feature) = goto_method(kind);
|
||||
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
|
||||
self.goto_in(&snap, &targets, method, pos, None, None).await
|
||||
let result = self.goto_in(&snap, &targets, method, pos, None, None).await;
|
||||
// JDT's selection-based definition can name the functional interface method for an
|
||||
// inherited method reference. Ask the Java binding command when that is what came back,
|
||||
// when the caret is on a method reference, or when the server found no target at all.
|
||||
let method_reference = snap.language.as_str() == "java" && java_method_reference_at(&snap.text, pos);
|
||||
if kind == GotoKind::Definition
|
||||
&& snap.language.as_str() == "java"
|
||||
&& (method_reference
|
||||
|| result.as_ref().is_ok_and(|locs| {
|
||||
locs.is_empty()
|
||||
|| locs.iter().any(|l| {
|
||||
let path = l.path.to_string_lossy().replace('\\', "/");
|
||||
let uri = l.uri.as_deref().unwrap_or_default();
|
||||
path.contains("java/util/function")
|
||||
|| path.contains("java.util.function")
|
||||
|| uri.contains("java/util/function")
|
||||
|| uri.contains("java.util.function")
|
||||
})
|
||||
}))
|
||||
&& let Ok(found) = self.java_method_reference_definition(&snap.path, pos).await
|
||||
&& !found.is_empty()
|
||||
{
|
||||
return Ok(found);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Go to Implementation, with the implementations found first passed to `partial` while
|
||||
@@ -4676,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::*;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Switch Header/Source for C, C++ and Objective-C through clangd's
|
||||
//! `textDocument/switchSourceHeader` extension. The editor falls back to a file with the
|
||||
//! same name when clangd does not serve the document or finds nothing.
|
||||
|
||||
use crate::{DEFAULT_TIMEOUT, LspManager, uri};
|
||||
use ide_core::{CancellationToken, DocId, IdeResult};
|
||||
use serde_json::Value;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const SERVER: &str = "clangd";
|
||||
const METHOD: &str = "textDocument/switchSourceHeader";
|
||||
|
||||
impl LspManager {
|
||||
/// clangd's header for the document's source file, or source for its header; `None`
|
||||
/// when clangd finds none or does not serve the document.
|
||||
pub async fn switch_source_header(&self, doc: DocId, cancel: CancellationToken) -> IdeResult<Option<PathBuf>> {
|
||||
let snap = self.snapshot(doc)?;
|
||||
let clangd: Vec<_> = snap.servers.iter().filter(|s| s.name == SERVER).cloned().collect();
|
||||
let Some(t) = self.ready_targets(&clangd, |_| true).await.into_iter().next() else { return Ok(None) };
|
||||
let found: Value = self.call(&t, METHOD, snap.ident(), Some(&cancel), DEFAULT_TIMEOUT).await?;
|
||||
Ok(found.as_str().and_then(uri::uri_to_path))
|
||||
}
|
||||
}
|
||||
@@ -8800,3 +8800,27 @@ async fn hierarchy_refactorings_use_phoxites_requests_when_the_server_advertises
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Protocol);
|
||||
assert_eq!(e.message, "any-name: index out of bounds");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn switch_source_header_asks_clangd_and_only_clangd() {
|
||||
let h = harness_for("objective-c", "m", &[("clangd", incremental_caps())], &[]);
|
||||
let (doc, path) = h.open("Foo.m", "#import \"Foo.h\"\n");
|
||||
h.wait_status("clangd", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("clangd");
|
||||
let header = h.root.join("Foo.h");
|
||||
s.respond("textDocument/switchSourceHeader", json!(uri_of(&header)));
|
||||
assert_eq!(h.mgr.switch_source_header(doc, CancellationToken::new()).await.unwrap(), Some(header));
|
||||
assert_eq!(s.requested("textDocument/switchSourceHeader"), vec![json!({ "uri": uri_of(&path) })]);
|
||||
// clangd found nothing: the editor falls back to a file of the same name.
|
||||
s.respond("textDocument/switchSourceHeader", Value::Null);
|
||||
assert_eq!(h.mgr.switch_source_header(doc, CancellationToken::new()).await.unwrap(), None);
|
||||
h.mgr.shutdown_all().await;
|
||||
|
||||
// Another server is never sent clangd's extension.
|
||||
let h = harness_for("objective-c", "m", &[("mock", incremental_caps())], &[]);
|
||||
let (doc, _) = h.open("Foo.m", "");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
assert_eq!(h.mgr.switch_source_header(doc, CancellationToken::new()).await.unwrap(), None);
|
||||
assert!(h.launcher.state("mock").requested("textDocument/switchSourceHeader").is_empty());
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
@@ -1082,6 +1082,83 @@ async fn css_modules_kit_navigates_between_tsx_and_module_css() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `@styled/typescript-styled-plugin` on vtsls: CSS diagnostics, completion and hover inside
|
||||
/// styled-components and emotion templates (#6900), with the settings hook's own plugin
|
||||
/// configuration. A tsconfig that declares the plugin too still gets one copy: each
|
||||
/// diagnostic shows once. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with
|
||||
/// `npm i @vtsls/language-server typescript@6 @styled/[email protected]`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vtsls/language-server and @styled/typescript-styled-plugin (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn styled_plugin_checks_and_completes_css_in_templates() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
// (library, its import and tag, the tsconfig declares the plugin)
|
||||
let cases = [
|
||||
("styled-components", "import styled from 'styled-components';", "styled.div", false),
|
||||
("@emotion/styled", "import styled from '@emotion/styled';", "styled.div", true),
|
||||
("@emotion/react", "import { css } from '@emotion/react';", "css", false),
|
||||
];
|
||||
for (library, import, tag, declared) in cases {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::write(root.join("package.json"), format!(r#"{{"name":"app","dependencies":{{"{library}":"*"}}}}"#))
|
||||
.unwrap();
|
||||
let plugins = if declared { r#", "plugins": [{ "name": "@styled/typescript-styled-plugin" }]"# } else { "" };
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
format!(r#"{{ "compilerOptions": {{ "strict": true, "module": "ESNext", "moduleResolution": "Bundler"{plugins} }}, "include": ["src"] }}"#),
|
||||
)
|
||||
.unwrap();
|
||||
// The library itself isn't installed: the plugin goes by the tag name.
|
||||
let types = "declare module 'styled-components' { const styled: any; export default styled; }\n\
|
||||
declare module '@emotion/styled' { const styled: any; export default styled; }\n\
|
||||
declare module '@emotion/react' { export const css: any; }\n";
|
||||
std::fs::write(root.join("src/libs.d.ts"), types).unwrap();
|
||||
let path = root.join("src/box.ts");
|
||||
let text = format!("{import}\nexport const box = {tag}`\n color: blue;\n colr: red;\n justify-con\n`;\n");
|
||||
std::fs::write(&path, &text).unwrap();
|
||||
let mut vtsls = npm_server(&tools, "vtsls", "vtsls", None);
|
||||
vtsls.tsserver_project = true;
|
||||
assert!(ide_sdk::apply::configure_styled(&mut vtsls, &root, Some(&tools)));
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
assert!(!ide_sdk::apply::configure_tsconfig_plugins(&mut vtsls, &root, data.path()));
|
||||
let registry = LanguageRegistry::from_configs(vec![lang("typescript", "ts", vtsls)]);
|
||||
let (mgr, events) = manager(&root, registry);
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &path, &LanguageId::new("typescript"), 1, &text);
|
||||
let case = format!("{library}, declared: {declared}");
|
||||
|
||||
let unknown = retry("unknown property diagnostic", Duration::from_secs(90), || {
|
||||
let found = events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path: p, items, .. } if p == &path => Some(
|
||||
items.iter().filter(|d| d.message.contains("Unknown property: 'colr'")).map(|d| d.range).collect(),
|
||||
),
|
||||
_ => None,
|
||||
});
|
||||
async move { found.filter(|v: &Vec<_>| !v.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!(unknown.len(), 1, "{case}: one copy of the plugin, {unknown:?}");
|
||||
assert_eq!(unknown[0].start.line, 3, "{case}");
|
||||
let list = retry("CSS property completion", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move {
|
||||
let list = mgr.completion(doc, Pos::new(4, 13), None, Default::default()).await.ok()?;
|
||||
list.items.iter().any(|i| i.label == "justify-content").then_some(list)
|
||||
}
|
||||
})
|
||||
.await;
|
||||
assert!(list.items.iter().any(|i| i.label == "justify-items"), "{case}");
|
||||
let hover = retry("CSS property hover", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.hover(doc, Pos::new(2, 4), Default::default()).await.ok().flatten() }
|
||||
})
|
||||
.await;
|
||||
assert!(hover.contents.value.to_lowercase().contains("color"), "{case}: {}", hover.contents.value);
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
const MDX_BUTTON: &str =
|
||||
"export function Button(props: { label: string }) {\n return <button>{props.label}</button>;\n}\n";
|
||||
const MDX_DOC: &str = "import { Button } from \"./Button\"\n\nexport const count = 2\n\n# Hello\n\n<Button label=\"hi\" />\n\n<Button label={count} />\n\n{count.toFixed()}\n";
|
||||
|
||||
@@ -613,11 +613,14 @@ impl PluginEngine {
|
||||
pub fn compile_cached(&self, wasm: &Path, cache_dir: &Path) -> Result<Component, String> {
|
||||
let bytes = std::fs::read(wasm).map_err(|e| format!("{}: {e}", wasm.display()))?;
|
||||
let file = cache_dir.join(format!("{}.cwasm", self.cache_key(&bytes)));
|
||||
if file.is_file() {
|
||||
// Read into memory rather than `deserialize_file`: that maps the file and makes its pages
|
||||
// executable, which the hardened runtime of the signed macOS app refuses ("failed to make
|
||||
// memory executable"), so the cache never hit and every activation compiled again.
|
||||
if let Ok(precompiled) = std::fs::read(&file) {
|
||||
// SAFETY: the cache directory belongs to the IDE (inside its plugins
|
||||
// directory) and is written only by `store_precompiled` below from
|
||||
// components this engine compiled; a corrupt file fails validation.
|
||||
match unsafe { Component::deserialize_file(&self.engine, &file) } {
|
||||
match unsafe { Component::deserialize(&self.engine, &precompiled) } {
|
||||
Ok(component) => return Ok(component),
|
||||
Err(e) => {
|
||||
tracing::info!("discarding precompiled {}: {e}", file.display());
|
||||
@@ -3035,6 +3038,26 @@ impl Runtime {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The second compile of the same component loads the cached one instead of compiling and
|
||||
/// writing it again (a failed load deletes and rewrites the file).
|
||||
#[test]
|
||||
fn a_precompiled_component_is_loaded_from_the_cache() {
|
||||
let engine = PluginEngine::new().unwrap();
|
||||
let wasm = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/hello/dist/plugin.wasm");
|
||||
let cache = tempfile::tempdir().unwrap();
|
||||
engine.compile_cached(&wasm, cache.path()).unwrap();
|
||||
let cached = || {
|
||||
let entries: Vec<_> = std::fs::read_dir(cache.path()).unwrap().flatten().map(|e| e.path()).collect();
|
||||
assert_eq!(entries.len(), 1, "{entries:?}");
|
||||
let file = entries[0].clone();
|
||||
(std::fs::metadata(&file).unwrap().modified().unwrap(), file)
|
||||
};
|
||||
let before = cached();
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
engine.compile_cached(&wasm, cache.path()).unwrap();
|
||||
assert_eq!(cached(), before, "loaded, not compiled and stored again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_field_extensions_are_parsed_and_unknown_or_malformed_fields_are_skipped() {
|
||||
let fields = [
|
||||
|
||||
@@ -33,12 +33,13 @@ pub struct ContainerRun<'a> {
|
||||
pub name: &'a str,
|
||||
/// `--user uid:gid`; `None` keeps the image's user.
|
||||
pub user: Option<(u32, u32)>,
|
||||
/// Runs the Python program under debugpy, for the debugger to attach.
|
||||
/// Runs the program for the debugger to attach: Python under debugpy, Node.js (a `js-debug`
|
||||
/// configuration) with its inspector waiting.
|
||||
pub debug: Option<ContainerDebug<'a>>,
|
||||
}
|
||||
|
||||
/// A debug run: the program starts under [`DEBUG_BOOTSTRAP`], which waits for the
|
||||
/// debugger on `port` (published on this machine's loopback interface only).
|
||||
/// A debug run: the program starts under [`DEBUG_BOOTSTRAP`] (Node.js: with `--inspect-brk`),
|
||||
/// which waits for the debugger on `port` (published on this machine's loopback interface only).
|
||||
pub struct ContainerDebug<'a> {
|
||||
pub port: u16,
|
||||
/// Folder on this machine holding [`DEBUG_BOOTSTRAP`] as [`DEBUG_BOOTSTRAP_NAME`].
|
||||
@@ -57,6 +58,14 @@ const DEBUG_DIR: &str = "/opt/openidea/debug";
|
||||
const DEBUGPY_DIR: &str = "/opt/openidea/debugpy-lib";
|
||||
/// Start of the line the bootstrap prints when the debugger can attach.
|
||||
pub const DEBUG_READY: &str = "debugpy is waiting for the debugger on port ";
|
||||
/// Start of the line printed before a Node.js program starts for debugging on a run target,
|
||||
/// followed by the project folder there. Node prints `Debugger listening on ws://…` itself.
|
||||
pub const NODE_DEBUG_FOLDER: &str = "Starting Node.js for the debugger, project folder ";
|
||||
|
||||
/// Whether a debug run of `config` starts Node.js with its inspector rather than debugpy.
|
||||
pub fn node_debug(config: &RunConfig) -> bool {
|
||||
config.debug_adapter.as_deref() == Some("js-debug")
|
||||
}
|
||||
|
||||
/// The container folder of the project when a Docker target sets none.
|
||||
pub fn default_container_root(root: &Path) -> String {
|
||||
@@ -243,9 +252,12 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
if let Some((uid, gid)) = run.user {
|
||||
args.extend(["--user".into(), format!("{uid}:{gid}")]);
|
||||
}
|
||||
let node = node_debug(config);
|
||||
if let Some(debug) = &run.debug {
|
||||
let port = debug.port;
|
||||
args.extend(["--publish".into(), format!("127.0.0.1:{port}:{port}")]);
|
||||
}
|
||||
if let Some(debug) = run.debug.as_ref().filter(|_| !node) {
|
||||
args.extend(["--volume".into(), format!("{}:{DEBUG_DIR}:ro", debug.bootstrap_dir.to_string_lossy())]);
|
||||
if let Some(lib) = debug.debugpy {
|
||||
args.extend(["--volume".into(), format!("{}:{DEBUGPY_DIR}:ro", lib.to_string_lossy())]);
|
||||
@@ -262,11 +274,15 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
match (command.shell_line, &run.debug) {
|
||||
(Some(_), Some(_)) => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' is a shell command line: only a Python script, module or console script can be debugged in a container. Set Command to the Python executable and put the script or -m module in Arguments",
|
||||
"'{}' is a shell command line: only a Python or Node.js program can be debugged in a container. Set Command to the Python or Node.js executable and put the script in Arguments",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
|
||||
// Inside the container the inspector listens on every interface, for the published port.
|
||||
(None, Some(debug)) if node => {
|
||||
args.extend(node_debug_command(&command.program, &command.args, "0.0.0.0", debug.port)?)
|
||||
}
|
||||
(None, Some(debug)) => {
|
||||
let bootstrap = format!("{DEBUG_DIR}/{DEBUG_BOOTSTRAP_NAME}");
|
||||
args.extend(debug_command(
|
||||
@@ -347,6 +363,43 @@ fn is_python(program: &str) -> bool {
|
||||
name == "python" || name == "python2" || name.starts_with("python3")
|
||||
}
|
||||
|
||||
/// Why tsx can't be debugged on a run target yet: js-debug's attach never lets the program start
|
||||
/// past tsx's loader worker.
|
||||
const TSX_UNSUPPORTED: &str = "tsx can't be debugged on a run target yet: the program does not start once the debugger attaches. For TypeScript, set the Node interpreter to node and add --experimental-strip-types to the Node options";
|
||||
|
||||
/// `program args` (a Node.js command on a run target) with the inspector waiting for the debugger
|
||||
/// on `host:port`: `--inspect-brk` goes right after `node`, so the configuration's Node options keep
|
||||
/// applying.
|
||||
pub(crate) fn node_debug_command(program: &str, args: &[String], host: &str, port: u16) -> IdeResult<Vec<String>> {
|
||||
let name = |s: &str| s.rsplit(['/', '\\']).next().unwrap_or(s).trim_end_matches(".exe").to_owned();
|
||||
// `node --import tsx` registers the same loader worker (`--loader tsx` fails on its own).
|
||||
let tsx_import = |value: &str| value == "tsx" || value.starts_with("tsx/") || value.contains("/tsx/");
|
||||
let mut imports_tsx = false;
|
||||
let mut i = 0;
|
||||
while let Some(a) = args.get(i).filter(|a| a.starts_with('-')) {
|
||||
if a == "--import" {
|
||||
imports_tsx |= args.get(i + 1).is_some_and(|v| tsx_import(v));
|
||||
i += 1;
|
||||
}
|
||||
imports_tsx |= a.strip_prefix("--import=").is_some_and(tsx_import);
|
||||
i += 1;
|
||||
}
|
||||
match name(program).as_str() {
|
||||
"node" if imports_tsx => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
|
||||
"node" => {}
|
||||
"tsx" => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
|
||||
"npx" if args.first().is_some_and(|a| a == "tsx") => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
|
||||
_ => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"`{program}` can't be debugged on a run target: set the Node interpreter to node"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut line = vec![program.to_owned(), format!("--inspect-brk={host}:{port}")];
|
||||
line.extend(args.iter().cloned());
|
||||
Ok(line)
|
||||
}
|
||||
|
||||
/// The command line that runs `program args` under [`DEBUG_BOOTSTRAP`] (at `bootstrap` in the
|
||||
/// container or on the SSH host): `python [options] <bootstrap> <port> <folder> (script | -m module | -c code) args`.
|
||||
/// A console script (`pytest`) runs as a module of the interpreter next to it, or of the
|
||||
@@ -741,6 +794,52 @@ mod tests {
|
||||
assert!(args.contains("openidea/debug:ro python:3.12") && !args.contains("debugpy-lib"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn debug_starts_node_with_the_inspector_on_the_published_port() {
|
||||
let target = RunTarget { kind: RunTargetKind::Docker, image: "node:22".into(), ..Default::default() };
|
||||
let line = |command: &str, args: &[&str]| {
|
||||
let c = RunConfig { debug_adapter: Some("js-debug".into()), ..config(command, args) };
|
||||
let args = debugged(&target, &c).unwrap().join(" ");
|
||||
assert!(args.contains("--publish 127.0.0.1:41234:41234 node:22"), "{args}");
|
||||
assert!(!args.contains("openidea/debug"), "no bootstrap for Node.js: {args}");
|
||||
args.split_once("node:22 ").unwrap().1.to_owned()
|
||||
};
|
||||
let inspect = "--inspect-brk=0.0.0.0:41234";
|
||||
assert_eq!(
|
||||
line("/usr/local/bin/node", &["--env-file=.env", "/work/proj/main.js", "a"]),
|
||||
format!("node {inspect} --env-file=.env /workspaces/proj/main.js a"),
|
||||
"the configuration's Node options stay"
|
||||
);
|
||||
assert_eq!(
|
||||
line("node", &["--import", "./setup.mjs", "main.js", "--import", "tsx"]),
|
||||
format!("node {inspect} --import ./setup.mjs main.js --import tsx"),
|
||||
"other imports, and the program's own arguments, don't count"
|
||||
);
|
||||
assert_eq!(
|
||||
line("node", &["--experimental-strip-types", "main.ts"]),
|
||||
format!("node {inspect} --experimental-strip-types main.ts")
|
||||
);
|
||||
// tsx hangs once js-debug attaches: refused, pointing to type stripping.
|
||||
for (command, args, error) in [
|
||||
("/work/proj/node_modules/.bin/tsx", &["main.ts"][..], "--experimental-strip-types"),
|
||||
("npx", &["tsx", "main.ts"][..], "tsx can't be debugged"),
|
||||
("node", &["--import", "tsx", "main.ts"][..], "tsx can't be debugged"),
|
||||
("node", &["--import=tsx/esm", "main.ts"][..], "tsx can't be debugged"),
|
||||
(
|
||||
"node",
|
||||
&["--env-file=.env", "--import", "/opt/lib/node_modules/tsx/dist/loader.mjs", "main.ts"][..],
|
||||
"tsx",
|
||||
),
|
||||
("npm", &["run", "dev"][..], "set the Node interpreter to node"),
|
||||
("node main.js", &[][..], "shell command line"),
|
||||
] {
|
||||
let c = RunConfig { debug_adapter: Some("js-debug".into()), ..config(command, args) };
|
||||
let err = debugged(&target, &c).unwrap_err();
|
||||
assert!(err.message.contains(error), "{command}: {}", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_files_printed_in_the_container_through_the_longest_mount() {
|
||||
let root = Path::new("project");
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, Tran
|
||||
use crate::mapping::{Excludes, Mappings, ResolvedMapping, posix};
|
||||
use crate::target::{
|
||||
DEBUG_PARAM, PROBE_NO_FOLDER, RemoteDebug, RemoteRuns, RemoteStart, SyncFn, debug_interpreter, debugpy_probe,
|
||||
remote_command, rewrite_external_classpath, ssh_debug_command,
|
||||
remote_command, rewrite_external_classpath, ssh_debug_command, ssh_node_debug_command,
|
||||
};
|
||||
use ide_core::remote_settings::{AutoUpload, DeploymentServer, DeploymentType, RunTarget};
|
||||
use ide_core::settings::Settings;
|
||||
@@ -605,14 +605,21 @@ async fn prepare_debug(
|
||||
remote_root: &str,
|
||||
debugpy_lib: Option<&Path>,
|
||||
) -> IdeResult<(RemoteDebug, Option<SyncFn>)> {
|
||||
if config.debug_adapter.as_deref() != Some("debugpy") {
|
||||
let node = crate::docker::node_debug(config);
|
||||
if config.debug_adapter.as_deref() != Some("debugpy") && !node {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' can't be debugged on an SSH run target: only Python run configurations can",
|
||||
"'{}' can't be debugged on an SSH run target: only Python and Node.js run configurations can",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
let dir = join(&fs.home().await?, DEBUG_FOLDER);
|
||||
let port = std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port();
|
||||
if node {
|
||||
let command = ssh_node_debug_command(&remote_command(config, target, root, remote_root), port)?;
|
||||
let tunnel = forward(session, port).await?;
|
||||
let note = Some(format!("{}{remote_root}", crate::docker::NODE_DEBUG_FOLDER));
|
||||
return Ok((RemoteDebug { command, tunnel, note }, None));
|
||||
}
|
||||
let dir = join(&fs.home().await?, DEBUG_FOLDER);
|
||||
// Unique among this machine's debug runs; other machines' runs use other temporary names too.
|
||||
let temp = |path: &str| format!("{path}.{}-{port}.tmp", std::process::id());
|
||||
// Named after its content and never rewritten: a concurrent run may be reading it.
|
||||
@@ -671,13 +678,19 @@ async fn prepare_debug(
|
||||
}));
|
||||
}
|
||||
}
|
||||
let tunnel = forward(session, port).await?;
|
||||
Ok((RemoteDebug { command, tunnel, note: None }, upload))
|
||||
}
|
||||
|
||||
/// Forwards local `port` to the same port on the host's loopback interface.
|
||||
async fn forward(session: &Arc<ide_ssh::Session>, port: u16) -> IdeResult<ide_ssh::Tunnel> {
|
||||
let tunnel = ide_ssh::Tunnel::listen_on(session.clone(), Some(port), "127.0.0.1", port).await?;
|
||||
if tunnel.port() != port {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"local port {port} for the debugger was taken meanwhile; try again"
|
||||
)));
|
||||
}
|
||||
Ok((RemoteDebug { command, tunnel }, upload))
|
||||
Ok(tunnel)
|
||||
}
|
||||
|
||||
/// Uploads outside-root classpath entries to their mirrored remote copies,
|
||||
|
||||
@@ -153,6 +153,18 @@ pub fn ssh_debug_command(
|
||||
})
|
||||
}
|
||||
|
||||
/// `command` (an SSH target's Node.js command) with the inspector waiting on the host's loopback
|
||||
/// `port`, which the IDE reaches through an SSH forward.
|
||||
pub fn ssh_node_debug_command(command: &RemoteCommand, port: u16) -> IdeResult<RemoteCommand> {
|
||||
if command.shell_line.is_some() {
|
||||
return Err(IdeError::invalid(
|
||||
"a shell command line can't be debugged on a run target: set the Node interpreter to node and the JavaScript file to the script",
|
||||
));
|
||||
}
|
||||
let line = crate::docker::node_debug_command(&command.program, &command.args, "127.0.0.1", port)?;
|
||||
Ok(RemoteCommand { program: line[0].clone(), args: line[1..].to_vec(), shell_line: None, ..command.clone() })
|
||||
}
|
||||
|
||||
/// The interpreter of an [`ssh_debug_command`] (with its options, or behind `uv run`).
|
||||
pub fn debug_interpreter(debug: &RemoteCommand, bootstrap: &str) -> RemoteCommand {
|
||||
let end = debug.args.iter().position(|a| a == bootstrap).unwrap_or(debug.args.len());
|
||||
@@ -358,6 +370,8 @@ pub struct RemoteStart {
|
||||
pub struct RemoteDebug {
|
||||
pub command: RemoteCommand,
|
||||
pub tunnel: ide_ssh::Tunnel,
|
||||
/// Printed right before the program starts (`docker::NODE_DEBUG_FOLDER`).
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
impl RemoteRuns {
|
||||
@@ -485,6 +499,9 @@ async fn run_remote(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
on_output(OutputChunk::System { text: format!("{}\n", command.display()) });
|
||||
if let Some(note) = start.debug.as_ref().and_then(|d| d.note.as_ref()) {
|
||||
on_output(OutputChunk::System { text: format!("{note}\n") });
|
||||
}
|
||||
let out = on_output.clone();
|
||||
let process = start
|
||||
.session
|
||||
@@ -556,6 +573,26 @@ mod tests {
|
||||
assert_eq!(c.program, "make");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn debugs_node_on_an_ssh_host_through_its_loopback_port() {
|
||||
let target = RunTarget { node: "/opt/node/bin/node".into(), ..Default::default() };
|
||||
let plain = remote_command(
|
||||
&config("/usr/local/bin/node", &["--enable-source-maps", "/work/proj/src/main.js"], None),
|
||||
&target,
|
||||
Path::new("/work/proj"),
|
||||
"/home/me/proj",
|
||||
);
|
||||
let debug = ssh_node_debug_command(&plain, 50123).unwrap();
|
||||
assert_eq!(debug.program, "/opt/node/bin/node");
|
||||
assert_eq!(debug.args, ["--inspect-brk=127.0.0.1:50123", "--enable-source-maps", "/home/me/proj/src/main.js"]);
|
||||
assert_eq!((debug.cwd.as_str(), &debug.env), (plain.cwd.as_str(), &plain.env));
|
||||
let tsx = RemoteCommand { program: "tsx".into(), ..plain.clone() };
|
||||
assert!(ssh_node_debug_command(&tsx, 50123).unwrap_err().message.contains("--experimental-strip-types"));
|
||||
let shell = RemoteCommand { shell_line: Some("node main.js".into()), ..plain };
|
||||
assert!(ssh_node_debug_command(&shell, 50123).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn debugs_python_on_an_ssh_host_through_its_loopback_port() {
|
||||
|
||||
@@ -1654,6 +1654,20 @@ pub fn configure_css_modules(cfg: &mut LanguageServerConfig, server_root: &Path,
|
||||
true
|
||||
}
|
||||
|
||||
/// Registers `@styled/typescript-styled-plugin` (installed under `location`) as a vtsls global
|
||||
/// plugin when a package.json at, above or below `server_root` depends on styled-components or
|
||||
/// emotion (#6900). No-op elsewhere, and without the plugin (`None`).
|
||||
pub fn configure_styled(cfg: &mut LanguageServerConfig, server_root: &Path, location: Option<&Path>) -> bool {
|
||||
if cfg.name != "vtsls" || !cfg.tsserver_project {
|
||||
return false;
|
||||
}
|
||||
let Some(location) = location.filter(|_| crate::styled::used(server_root)) else {
|
||||
return false;
|
||||
};
|
||||
push_global_plugin(cfg, crate::styled::tsserver_plugin(location));
|
||||
true
|
||||
}
|
||||
|
||||
/// Adds `plugin` to vtsls' `globalPlugins`, replacing an entry of the same name.
|
||||
fn push_global_plugin(cfg: &mut LanguageServerConfig, plugin: Value) {
|
||||
insert_global_plugin(cfg, plugin, None);
|
||||
|
||||
@@ -15,21 +15,22 @@ pub(crate) fn enabled(server_root: &Path) -> bool {
|
||||
if ide_language::marked_root(None, server_root, &markers).is_some() {
|
||||
return true;
|
||||
}
|
||||
// ponytail: bounded walk, as for the path aliases; deeper workspace members go without.
|
||||
files_below(server_root, "tsconfig.json")
|
||||
.any(|p| p.parent().is_some_and(|dir| ide_language::marked_root(Some(dir), dir, &markers).is_some()))
|
||||
}
|
||||
|
||||
/// The files named `name` in `root` and the packages below it, outside `node_modules`.
|
||||
pub(crate) fn files_below(root: &Path, name: &'static str) -> impl Iterator<Item = std::path::PathBuf> {
|
||||
// A bounded walk, as for the path aliases; deeper workspace members are not seen.
|
||||
const MAX_DEPTH: usize = 4;
|
||||
const MAX_ENTRIES: usize = 50_000;
|
||||
let mut walker = ignore::WalkBuilder::new(server_root);
|
||||
let mut walker = ignore::WalkBuilder::new(root);
|
||||
walker
|
||||
.max_depth(Some(MAX_DEPTH))
|
||||
.require_git(ide_core::ignored::inside_git_repo(server_root))
|
||||
.require_git(ide_core::ignored::inside_git_repo(root))
|
||||
.follow_links(false)
|
||||
.filter_entry(|e| e.file_name() != "node_modules");
|
||||
walker
|
||||
.build()
|
||||
.take(MAX_ENTRIES)
|
||||
.flatten()
|
||||
.filter(|e| e.file_name() == "tsconfig.json")
|
||||
.any(|e| e.path().parent().is_some_and(|dir| ide_language::marked_root(Some(dir), dir, &markers).is_some()))
|
||||
walker.build().take(MAX_ENTRIES).flatten().filter(move |e| e.file_name() == name).map(|e| e.into_path())
|
||||
}
|
||||
|
||||
/// vtsls `globalPlugins` entry of the plugin installed under `location` (the folder holding its
|
||||
|
||||
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"java-usages",
|
||||
"1.19.0",
|
||||
"1.20.1",
|
||||
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ pub mod php;
|
||||
pub mod pinned;
|
||||
pub mod python;
|
||||
pub mod ruby;
|
||||
mod styled;
|
||||
mod tsconfig_plugins;
|
||||
mod vue;
|
||||
mod zig;
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//! `@styled/typescript-styled-plugin`: the tsserver plugin vtsls loads for CSS completion, hover
|
||||
//! and diagnostics inside styled-components and emotion template literals (#6900). It matches
|
||||
//! templates by tag name (`styled`, `css`, `createGlobalStyle`, `keyframes`, `injectGlobal`).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The package (and tsserver plugin name) the IDE installs as the `typescript-styled-plugin` tool.
|
||||
pub(crate) const PLUGIN: &str = "@styled/typescript-styled-plugin";
|
||||
/// The CSS-in-JS libraries whose templates the plugin understands.
|
||||
const LIBRARIES: &[&str] = &["styled-components", "@emotion/styled", "@emotion/react", "@emotion/css"];
|
||||
|
||||
fn depends(manifest: &Path) -> bool {
|
||||
std::fs::read_to_string(manifest)
|
||||
.is_ok_and(|text| crate::libraries::package_dependencies(&text).iter().any(|d| LIBRARIES.contains(&d.as_str())))
|
||||
}
|
||||
|
||||
/// A package.json at `server_root`, above it, or in a package below it depends on one of them.
|
||||
pub(crate) fn used(server_root: &Path) -> bool {
|
||||
server_root.ancestors().any(|dir| depends(&dir.join("package.json")))
|
||||
|| crate::css_modules::files_below(server_root, "package.json").any(|p| depends(&p))
|
||||
}
|
||||
|
||||
/// vtsls `globalPlugins` entry of the plugin installed under `location` (the folder holding its
|
||||
/// `node_modules`).
|
||||
pub(crate) fn tsserver_plugin(location: &Path) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"name": PLUGIN,
|
||||
"location": location.to_string_lossy(),
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_package_depending_on_styled_components_or_emotion_turns_it_on() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = &dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("apps/web/node_modules/dep")).unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "react": "^19.0.0" } }"#).unwrap();
|
||||
let styled = r#"{ "dependencies": { "styled-components": "^6.1.0" } }"#;
|
||||
std::fs::write(root.join("apps/web/node_modules/dep/package.json"), styled).unwrap();
|
||||
assert!(!used(root), "dependencies don't count");
|
||||
std::fs::write(root.join("apps/web/package.json"), styled).unwrap();
|
||||
assert!(used(root), "a package below the server root");
|
||||
assert!(used(&root.join("apps/web/src")), "the package.json above");
|
||||
std::fs::write(root.join("apps/web/package.json"), r#"{ "devDependencies": { "@emotion/react": "^11" } }"#)
|
||||
.unwrap();
|
||||
assert!(used(root), "emotion");
|
||||
std::fs::write(root.join("apps/web/package.json"), r#"{ "dependencies": { "@emotion/cache": "^11" } }"#)
|
||||
.unwrap();
|
||||
assert!(!used(root));
|
||||
}
|
||||
}
|
||||
@@ -4037,3 +4037,55 @@ fn css_modules_kit_stays_the_ides_copy_when_the_project_declares_or_installs_it(
|
||||
assert!(location.join("node_modules/project-plugin").exists());
|
||||
assert!(!location.join("node_modules/@css-modules-kit").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vtsls_gets_the_styled_plugin_where_a_package_uses_styled_components_or_emotion() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, tools) = (tmp.path().join("app"), tmp.path().join("tools"));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "react": "^19.0.0" } }"#).unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
cfg.tsserver_project = true;
|
||||
assert!(!crate::apply::configure_styled(&mut cfg, &root, Some(&tools)), "no CSS-in-JS library");
|
||||
assert!(cfg.initialization_options.is_none());
|
||||
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "@emotion/styled": "^11.14.0" } }"#).unwrap();
|
||||
assert!(!crate::apply::configure_styled(&mut cfg, &root, None), "plugin not installed");
|
||||
let mut native = server("vtsls");
|
||||
assert!(!crate::apply::configure_styled(&mut native, &root, Some(&tools)), "TypeScript 7 hosts no plugins");
|
||||
for _ in 0..2 {
|
||||
assert!(crate::apply::configure_styled(&mut cfg, &root, Some(&tools)));
|
||||
}
|
||||
let init = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
init.pointer("/vtsls/tsserver/globalPlugins").unwrap(),
|
||||
&serde_json::json!([{
|
||||
"name": "@styled/typescript-styled-plugin",
|
||||
"location": tools.to_string_lossy(),
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
}]),
|
||||
"once"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_styled_plugin_stays_one_ides_copy_when_the_tsconfig_declares_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, tools, data) = (tmp.path().join("app"), tmp.path().join("tools"), tmp.path().join("data"));
|
||||
std::fs::create_dir_all(root.join("node_modules/@styled/typescript-styled-plugin")).unwrap();
|
||||
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "styled-components": "^6.1.0" } }"#).unwrap();
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
r#"{ "compilerOptions": { "plugins": [{ "name": "@styled/typescript-styled-plugin" }] } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
cfg.tsserver_project = true;
|
||||
// In the host's order: the global plugins, then the tsconfig's.
|
||||
assert!(crate::apply::configure_styled(&mut cfg, &root, Some(&tools)));
|
||||
assert!(!crate::apply::configure_tsconfig_plugins(&mut cfg, &root, &data), "no probe location for it");
|
||||
let init = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
|
||||
let plugins = init.pointer("/vtsls/tsserver/globalPlugins").unwrap().as_array().unwrap();
|
||||
assert_eq!(plugins.len(), 1);
|
||||
assert_eq!(plugins[0]["location"], tools.to_string_lossy().as_ref());
|
||||
assert!(init.pointer("/typescript/tsserver/pluginPaths").is_none());
|
||||
}
|
||||
@@ -139,6 +139,9 @@ pub const TYPESCRIPT: &str = "typescript@6";
|
||||
/// new pin here (the installed one then reads as missing and is offered again).
|
||||
pub const CSS_MODULES_KIT: &str = "@css-modules-kit/[email protected]";
|
||||
|
||||
/// The tsserver plugin for CSS in styled-components / emotion templates, pinned likewise.
|
||||
pub const TYPESCRIPT_STYLED_PLUGIN: &str = "@styled/[email protected]";
|
||||
|
||||
pub static TOOLS: &[ToolSpec] = &[
|
||||
ToolSpec {
|
||||
name: "unity-debug",
|
||||
@@ -319,6 +322,17 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/mizdra/css-modules-kit",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "typescript-styled-plugin",
|
||||
display: "typescript-styled-plugin (tsserver plugin)",
|
||||
kind: Plugin,
|
||||
commands: &["@styled/typescript-styled-plugin"],
|
||||
method: Method::Npm { packages: &[TYPESCRIPT_STYLED_PLUGIN] },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/styled-components/typescript-styled-plugin",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "typescript-language-server",
|
||||
display: "typescript-language-server",
|
||||
@@ -1393,7 +1407,8 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
];
|
||||
|
||||
/// Plugin tools and the tool that loads them.
|
||||
pub const PLUGIN_HOSTS: &[(&str, &str)] = &[("lombok", "jdtls"), ("css-modules-kit", "vtsls")];
|
||||
pub const PLUGIN_HOSTS: &[(&str, &str)] =
|
||||
&[("lombok", "jdtls"), ("css-modules-kit", "vtsls"), ("typescript-styled-plugin", "vtsls")];
|
||||
|
||||
pub fn find(name: &str) -> Option<&'static ToolSpec> {
|
||||
TOOLS.iter().find(|t| t.name == name)
|
||||
|
||||
@@ -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:?}"
|
||||
);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use parking_lot::{Mutex, RwLock};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
/// Exclude globs from settings (`files.exclude`), e.g. `**/node_modules`.
|
||||
@@ -97,6 +98,11 @@ pub(crate) struct GitignoreStack {
|
||||
/// `.git/info/exclude` and the global excludes file, rooted at the repo root.
|
||||
repo_level: RwLock<Vec<Gitignore>>,
|
||||
cache: Mutex<HashMap<PathBuf, Option<Arc<Gitignore>>>>,
|
||||
/// Bumped (under the `cache` lock) by every invalidation. A lookup that read the ignore
|
||||
/// files before an invalidation doesn't store what it read: the watcher thread may be
|
||||
/// matching a new file while a command rewrites `.gitignore` and invalidates, and its
|
||||
/// older rules must not land in the cache after that.
|
||||
generation: AtomicU64,
|
||||
nested: Mutex<NestedRepos>,
|
||||
}
|
||||
|
||||
@@ -127,7 +133,7 @@ impl GitignoreStack {
|
||||
pub fn new(near: &Path) -> Self {
|
||||
let repo_root = find_repo_root(near);
|
||||
let repo_level = RwLock::new(Self::load_repo_level(repo_root.as_deref()));
|
||||
Self { repo_root, repo_level, cache: Mutex::default(), nested: Mutex::default() }
|
||||
Self { repo_root, repo_level, cache: Mutex::default(), generation: AtomicU64::new(0), nested: Mutex::default() }
|
||||
}
|
||||
|
||||
/// [`new`](Self::new) for listing a directory over and over (expanding a tree, a slow share):
|
||||
@@ -163,6 +169,7 @@ impl GitignoreStack {
|
||||
repo_root: entry.repo_root.clone(),
|
||||
repo_level: RwLock::new(entry.rules.clone()),
|
||||
cache: Mutex::default(),
|
||||
generation: AtomicU64::new(0),
|
||||
nested: Mutex::default(),
|
||||
}
|
||||
}
|
||||
@@ -217,6 +224,7 @@ impl GitignoreStack {
|
||||
}
|
||||
}
|
||||
let mut cache = self.cache.lock();
|
||||
self.generation.fetch_add(1, Ordering::Relaxed);
|
||||
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
|
||||
if cache.contains_key(dir) {
|
||||
cache.retain(|k, _| !k.starts_with(dir));
|
||||
@@ -232,7 +240,9 @@ impl GitignoreStack {
|
||||
for stack in self.nested.lock().by_root.values() {
|
||||
stack.invalidate(dir);
|
||||
}
|
||||
self.cache.lock().remove(dir);
|
||||
let mut cache = self.cache.lock();
|
||||
self.generation.fetch_add(1, Ordering::Relaxed);
|
||||
cache.remove(dir);
|
||||
}
|
||||
|
||||
/// Returns the shared `GitignoreStack` of the nested repository enclosing `dir`, if any.
|
||||
@@ -273,6 +283,7 @@ impl GitignoreStack {
|
||||
repo_root: Some(root),
|
||||
repo_level,
|
||||
cache: Mutex::default(),
|
||||
generation: AtomicU64::new(0),
|
||||
nested: Mutex::default(),
|
||||
})
|
||||
})
|
||||
@@ -281,9 +292,13 @@ impl GitignoreStack {
|
||||
}
|
||||
|
||||
fn matcher_for(&self, dir: &Path) -> Option<Arc<Gitignore>> {
|
||||
if let Some(cached) = self.cache.lock().get(dir) {
|
||||
return cached.clone();
|
||||
}
|
||||
let generation = {
|
||||
let cache = self.cache.lock();
|
||||
if let Some(cached) = cache.get(dir) {
|
||||
return cached.clone();
|
||||
}
|
||||
self.generation.load(Ordering::Relaxed)
|
||||
};
|
||||
let mut builder = GitignoreBuilder::new(dir);
|
||||
let mut any = false;
|
||||
for name in [".gitignore", ".ignore"] {
|
||||
@@ -307,7 +322,10 @@ impl GitignoreStack {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.cache.lock().insert(dir.to_path_buf(), matcher.clone());
|
||||
let mut cache = self.cache.lock();
|
||||
if self.generation.load(Ordering::Relaxed) == generation {
|
||||
cache.insert(dir.to_path_buf(), matcher.clone());
|
||||
}
|
||||
matcher
|
||||
}
|
||||
|
||||
@@ -476,6 +494,38 @@ mod tests {
|
||||
assert!(Arc::ptr_eq(&nested, stack.nested.lock().by_root.get(&repo).unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lookup_racing_an_invalidation_does_not_cache_the_older_rules() {
|
||||
// The watcher thread matches new files while a command rewrites `.gitignore` and
|
||||
// invalidates; whatever it read before the rewrite must not outlive the invalidation.
|
||||
// A long file keeps the reader busy building its matcher, widening the window.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir(root.join(".git")).unwrap();
|
||||
let filler: String = (0..20_000).map(|n| format!("generated-{n}/\n")).collect();
|
||||
let stack = Arc::new(GitignoreStack::new(&root));
|
||||
for i in 0..20 {
|
||||
let name = format!("f{i}.tmp-ignore");
|
||||
std::fs::write(root.join(".gitignore"), &filler).unwrap();
|
||||
stack.invalidate(&root);
|
||||
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let reader = {
|
||||
let (stack, stop, path) = (stack.clone(), stop.clone(), root.join(&name));
|
||||
std::thread::spawn(move || {
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
stack.is_ignored(&path, false);
|
||||
}
|
||||
})
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
std::fs::write(root.join(".gitignore"), format!("{filler}{name}\n")).unwrap();
|
||||
stack.invalidate(&root);
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
reader.join().unwrap();
|
||||
assert!(stack.is_ignored(&root.join(&name), false), "round {i} kept the older rules");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repository_created_inside_the_workspace_becomes_a_boundary() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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() }];
|
||||
|
||||
@@ -115,7 +115,7 @@ The debugger adds attach-only types such as **Remote JVM Debug**, **Go Remote**,
|
||||
|
||||
### Common fields
|
||||
|
||||
- **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Only Python configurations can be debugged on a run target; see [Python debugging](/en/languages/python#debugging). See [SSH](/en/guide/remote/ssh).
|
||||
- **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Python and Node.js configurations can be debugged on a run target (Node.js run with tsx not yet); see [Python debugging](/en/languages/python#debugging) and [JavaScript debugging](/en/languages/javascript#debugging). See [SSH](/en/guide/remote/ssh).
|
||||
- **Working directory**: relative to the project root; empty means the project root. It may use the path macros `$PROJECT_DIR$`, `$ContentRoot$`, `$MODULE_DIR$`, `$MODULE_WORKING_DIR$` and `$USER_HOME$`, expanded when the configuration starts, so a shared configuration works on every machine.
|
||||
- **Environment variables**: `VAR=value` pairs separated by `;`. The list button opens the **Environment Variables** dialog, where **Include system environment variables** can be turned off.
|
||||
- **Debug adapter**: which debugger **Debug** uses for this configuration (for example `debugpy`, `js-debug`, `codelldb`, `delve`).
|
||||
|
||||
@@ -32,6 +32,10 @@ clangd needs the flags each file is compiled with. Without them it guesses, and
|
||||
clangd looks for `compile_commands.json` in the file's parent directories and in a `build/` subdirectory of each. If your build directory has another name (for example `cmake-build-debug` from a CMake profile), add a `.clangd` file with `CompileFlags: { CompilationDatabase: cmake-build-debug }` or copy or link the file to the project root.
|
||||
</Tip>
|
||||
|
||||
### Header and source
|
||||
|
||||
**Switch Header/Source** (in Find Action; `F10`, `⌥O` / `Alt+O` in the VS Code keymaps) opens the counterpart of the current file: `Foo.m` or `Foo.cpp` from `Foo.h`, and back. It asks clangd first (`textDocument/switchSourceHeader`, which also finds a source file in another folder). When clangd is not running for the file or has no answer, it opens a project file with the same name and a counterpart extension, preferring the same folder. **Related Symbol…** (`⌃⌘↑` / `Ctrl+Alt+Home`) lists every match by name instead.
|
||||
|
||||
### Apple's clangd
|
||||
|
||||
The `clangd` that ships with Xcode and the Command Line Tools does not run clang-tidy. When a project has a `.clang-tidy` file and the IDE is using Apple's clangd, it shows a warning with an **Install** button that installs the LLVM build instead.
|
||||
|
||||
@@ -121,6 +121,7 @@ Cypress runs report through Cypress's built-in `teamcity` reporter unless the co
|
||||
Debugging uses the JavaScript Debugger (vscode-js-debug); if it is missing, the first debug session offers to install it.
|
||||
|
||||
- **Debug** works for npm script configurations, Node.js files and `deno run` / `deno test`. Child processes are attached automatically.
|
||||
- A Node.js configuration or a `.js` / `.ts` file run on an SSH, Docker or Compose run target is debugged there: Node starts with `--inspect-brk` on a free port (published from the container on this machine's loopback interface, or forwarded through the SSH connection) and the debugger attaches as **Attach to Node.js** does, with the project folder mapped onto the target's. The interpreter must be `node`, and the configuration's Node options are kept. For TypeScript, add `--experimental-strip-types` to the Node options: tsx (`tsx`, `npx tsx`, `node --import tsx`) can't be debugged on a run target yet, because the program does not start once the debugger attaches. npm script configurations can only be run on a target.
|
||||
- **Attach to Node.js** is a run configuration type for a process started with `--inspect` on this or another machine (default port 9229), with local and remote root mapping. With **Reconnect automatically** on, the session waits while the process restarts (nodemon, `node --watch`, `tsx watch`) and attaches to it again with the same breakpoints.
|
||||
- **Attach to Process…** in the Run menu lists running Node.js processes.
|
||||
- **JavaScript Debug** is a run configuration type that opens a URL in Chrome or Edge and debugs the page's JavaScript and TypeScript through source maps. Start the page's server first (for example with the `dev` npm script); **Web root** is the folder the URL serves, the project root by default.
|
||||
|
||||
@@ -111,7 +111,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
|
||||
|
||||
### 通用字段
|
||||
|
||||
- **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上只能调试 Python 配置,见 [Python 调试](/zh/languages/python#调试)。参见 [SSH](/zh/guide/remote/ssh)。
|
||||
- **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上可以调试 Python 和 Node.js 配置(用 tsx 运行的 Node.js 暂不支持),见 [Python 调试](/zh/languages/python#调试) 与 [JavaScript 调试](/zh/languages/javascript#调试)。参见 [SSH](/zh/guide/remote/ssh)。
|
||||
- **工作目录**:相对于项目根目录,留空即项目根目录。可以使用路径宏 `$PROJECT_DIR$`、`$ContentRoot$`、`$MODULE_DIR$`、`$MODULE_WORKING_DIR$` 和 `$USER_HOME$`,在配置启动时展开,因此共享的配置在每台机器上都能用。
|
||||
- **环境变量**:`VAR=value` 形式,用 `;` 分隔。点旁边的列表按钮打开“环境变量”对话框,可以关闭 **包括系统环境变量**。
|
||||
- **调试适配器**:按“调试”时这个配置使用哪个调试器(如 `debugpy`、`js-debug`、`codelldb`、`delve`)。
|
||||
|
||||
@@ -32,6 +32,10 @@ clangd 需要知道每个文件的编译参数,否则只能猜测,常见的
|
||||
clangd 会在文件的各级父目录以及这些目录下的 `build/` 子目录里查找 `compile_commands.json`。如果构建目录叫别的名字(例如 CMake 配置生成的 `cmake-build-debug`),在项目根目录添加一个 `.clangd`,写上 `CompileFlags: { CompilationDatabase: cmake-build-debug }`,或者把该文件复制或链接到项目根目录。
|
||||
</Tip>
|
||||
|
||||
### 头文件与源文件
|
||||
|
||||
**切换头文件/源文件**(可在“查找操作”中运行;`F10`,VS Code 键位下为 `⌥O` / `Alt+O`)打开当前文件对应的另一半:在 `Foo.h` 中打开 `Foo.m` 或 `Foo.cpp`,反之亦然。它先询问 clangd(`textDocument/switchSourceHeader`,能找到放在其他文件夹里的源文件);clangd 没有为该文件运行或没有给出结果时,打开项目中同名、扩展名对应的文件,优先同一文件夹。**相关符号…**(`⌃⌘↑` / `Ctrl+Alt+Home`)则按名称列出所有匹配。
|
||||
|
||||
### Apple 自带的 clangd
|
||||
|
||||
Xcode 和 Command Line Tools 自带的 `clangd` 不运行 clang-tidy。如果项目里有 `.clang-tidy`,而 IDE 正在使用 Apple 的 clangd,会弹出提示并提供 **安装** 按钮,改装 LLVM 版本的 clangd。
|
||||
|
||||
@@ -122,6 +122,7 @@ Cypress 运行时使用 Cypress 内置的 `teamcity` 报告器(配置里指定
|
||||
调试使用 JavaScript 调试器(vscode-js-debug);未安装时,第一次调试会提示安装。
|
||||
|
||||
- **调试** 适用于 npm 脚本配置、Node.js 文件以及 `deno run` / `deno test`,子进程会自动附加。
|
||||
- 在 SSH、Docker 或 Compose 运行目标上运行的 Node.js 配置或 `.js` / `.ts` 文件,会在目标上调试:Node 以 `--inspect-brk` 在空闲端口上启动(容器中的端口发布到本机回环地址,SSH 主机上的端口经 SSH 连接转发),调试器像 **附加到 Node.js** 一样附加,并把项目文件夹映射到目标上的项目文件夹。解释器须为 `node`,配置中的 Node 选项保持不变。TypeScript 请在 Node 选项中加上 `--experimental-strip-types`:tsx(`tsx`、`npx tsx`、`node --import tsx`)暂时不能在运行目标上调试,因为调试器附加后程序不会开始运行。npm 脚本配置在运行目标上只能运行。
|
||||
- **附加到 Node.js** 是一种运行配置类型,用于附加到本机或其他机器上以 `--inspect` 启动的进程(默认端口 9229),可设置本地与远程根目录映射。勾选 **自动重新连接** 后,进程重启时(nodemon、`node --watch`、`tsx watch`)会话会等待,并以相同的断点重新附加。
|
||||
- 运行菜单中的 **附加到进程…** 会列出正在运行的 Node.js 进程。
|
||||
- **JavaScript 调试** 是一种运行配置类型:在 Chrome 或 Edge 中打开一个 URL,通过 source map 调试页面中的 JavaScript 和 TypeScript。先启动页面的服务(例如 `dev` npm 脚本);**Web 根目录** 是该 URL 对应的文件夹,默认为项目根目录。
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -459,6 +459,7 @@ lsp_snapshot_completion trusted project_host bin
|
||||
lsp_snapshot_diagnostics trusted project_host bindings async
|
||||
lsp_source_action_text trusted project_host bindings async
|
||||
lsp_stop trusted project_host bindings async
|
||||
lsp_switch_source_header trusted project_host bindings async
|
||||
lsp_type_hierarchy trusted project_host bindings async
|
||||
lsp_virtual_document trusted project_host bindings async
|
||||
lsp_workspace_symbols trusted project_host bindings async
|
||||
|
||||
@@ -1210,6 +1210,12 @@ export const commands = {
|
||||
lspSourceActionText: (path: string, text: string, kind: string, request: RequestId) => typedError<TextEdit[], IdeError>(__TAURI_INVOKE("lsp_source_action_text", { path, text, kind, request })),
|
||||
/** Stops a language server; it starts again when a file it serves is opened. */
|
||||
lspStop: (server: ServerId) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_stop", { server })),
|
||||
/**
|
||||
* The header of the document's source file or the source of its header (C, C++,
|
||||
* Objective-C) as clangd finds it; `None` without clangd or an answer. Cancel with
|
||||
* `cancel_request(request)`.
|
||||
*/
|
||||
lspSwitchSourceHeader: (request: RequestId, doc: DocId) => typedError<string | null, IdeError>(__TAURI_INVOKE("lsp_switch_source_header", { request, doc })),
|
||||
lspTypeHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<HierarchyItem[], IdeError>(__TAURI_INVOKE("lsp_type_hierarchy", { doc, pos, direction })),
|
||||
/**
|
||||
* Contents of a read-only language-server document, including JDT library
|
||||
@@ -11742,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;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { insertNewlineAndIndent } from "@codemirror/commands";
|
||||
import { LanguageDescription, type Language } from "@codemirror/language";
|
||||
import { LanguageDescription, indentUnit, type Language } from "@codemirror/language";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getIndentation } from "@codemirror/language";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { logWarning } from "./highlight";
|
||||
import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
|
||||
import { commentTokens, fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
describe("language modes", () => {
|
||||
it("highlights Julia declarations, calls, types, macros and literals without semantic tokens", async () => {
|
||||
@@ -765,3 +765,43 @@ describe("language modes", () => {
|
||||
expect(found).not.toContain("yes:keyword");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Slint indentation", () => {
|
||||
it("indents element blocks by their braces under the C highlighting mode", async () => {
|
||||
const support = await loadSupport(findLanguageDescription("C", "/p/app.slint")!);
|
||||
const slint = commentTokens({
|
||||
id: "slint",
|
||||
name: "Slint",
|
||||
extensions: ["slint"],
|
||||
uiMode: "C",
|
||||
lineComment: "//",
|
||||
blockComment: ["/*", "*/"],
|
||||
indent: { tabSize: 4, insertSpaces: true },
|
||||
});
|
||||
const enter = (doc: string, at = doc.length) => {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
selection: EditorSelection.cursor(at),
|
||||
extensions: [support!, slint, indentUnit.of(" ")],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
insertNewlineAndIndent(view);
|
||||
const out = view.state.doc.toString();
|
||||
view.destroy();
|
||||
return out;
|
||||
};
|
||||
const app = "export component App inherits Window {";
|
||||
expect(enter(app)).toBe(`${app}\n `);
|
||||
expect(enter(`${app}}`, app.length)).toBe(`${app}\n \n}`);
|
||||
expect(enter(`${app}\n width: 100px;`)).toBe(`${app}\n width: 100px;\n `);
|
||||
// After a child element closes, the next line stays at the child's level.
|
||||
expect(enter(`${app}\n Text {\n text: "hi";\n }`)).toBe(
|
||||
`${app}\n Text {\n text: "hi";\n }\n `,
|
||||
);
|
||||
expect(enter(`${app}\n Text {\n }\n Rectangle {`)).toBe(
|
||||
`${app}\n Text {\n }\n Rectangle {\n `,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -740,6 +740,13 @@ const NO_INDENT_LANGS = new Set([
|
||||
"gitattributes",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Languages highlighted by a borrowed mode whose own indentation doesn't fit them: Slint's
|
||||
* element blocks (`Text { … }` without a `;`) read as unfinished C statements, so Enter after
|
||||
* one lands at the wrong column. These use the brace-based fallback indentation instead.
|
||||
*/
|
||||
const BRACE_INDENT_OVER_MODE = new Set(["slint"]);
|
||||
|
||||
function opensBlock(code: string, language: string | undefined): boolean {
|
||||
if (!code) return false;
|
||||
if (/[{([]$/.test(code)) return true;
|
||||
@@ -779,7 +786,7 @@ function indentationCode(text: string, lineComment: string | undefined): string
|
||||
*/
|
||||
export function fallbackIndent(language?: string): Extension {
|
||||
return indentService.of((cx, pos) => {
|
||||
if (cx.state.facet(languageFacet)) return undefined;
|
||||
if (cx.state.facet(languageFacet) && !BRACE_INDENT_OVER_MODE.has(language ?? "")) return undefined;
|
||||
const lineComment = cx.state.languageDataAt<{ line?: string }>("commentTokens", pos)[0]?.line;
|
||||
const stripComment = (text: string) => indentationCode(text, lineComment);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача