дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
Порівняти коміти
48
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
468118df57 | ||
|
|
88a6bbca14 | ||
|
|
b9e555300f | ||
|
|
7ff223001b | ||
|
|
cc9279a6d6 | ||
|
|
1cfbb24b31 | ||
|
|
a8a0cdb315 | ||
|
|
8ab776ada6 | ||
|
|
88b463d888 | ||
|
|
ac88059d0f | ||
|
|
a09c9aa9ad | ||
|
|
7fef1e10a8 | ||
|
|
1748c98ac8 | ||
|
|
399ae25ab6 | ||
|
|
f28dd8125b | ||
|
|
d5f7e0a99b | ||
|
|
a66c9e6d05 | ||
|
|
59bcf7eac5 | ||
|
|
fe21c67537 | ||
|
|
c085f52b59 | ||
|
|
0104ed63c1 | ||
|
|
a441b2a906 | ||
|
|
c4f7fec86c | ||
|
|
37a8aae018 | ||
|
|
acc48a4816 | ||
|
|
8301326289 | ||
|
|
4c71299745 | ||
|
|
08249ca5fd | ||
|
|
edd6746439 | ||
|
|
695424beb2 | ||
|
|
9943d71d02 | ||
|
|
e03c5507f7 | ||
|
|
745099feaa | ||
|
|
6894d0a4e3 | ||
|
|
f80be658ea | ||
|
|
1c377b7f66 | ||
|
|
093cf6fdf8 | ||
|
|
9b578c2fad | ||
|
|
f5bb97babd | ||
|
|
e23088d558 | ||
|
|
7279f515db | ||
|
|
710d120689 | ||
|
|
38709947fe | ||
|
|
d9fbb19787 | ||
|
|
6aa613d4ec | ||
|
|
60ef498deb | ||
|
|
719b73ecd9 | ||
|
|
6c3284c300 |
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"
|
||||
|
||||
@@ -24,6 +24,7 @@ pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
mod swiftpm;
|
||||
pub mod unity;
|
||||
|
||||
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
@@ -613,6 +614,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");
|
||||
@@ -625,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,
|
||||
@@ -1080,6 +1094,9 @@ impl DebugManager {
|
||||
.await?;
|
||||
arguments["program"] = json!(program);
|
||||
}
|
||||
if let Some(spm) = arguments.as_object_mut().and_then(|o| o.remove("swiftpm")) {
|
||||
arguments["program"] = json!(swiftpm::program(&cwd, &spm, &cancel).await?);
|
||||
}
|
||||
// Attach to a Node process started without `--inspect`: open its inspector first.
|
||||
if config.adapter == "js-debug" && config.request == "attach" && arguments.get("port").is_none() {
|
||||
let pid = arguments.get("processId").and_then(|p| match p {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
//! SwiftPM launch integration: a launch request may carry
|
||||
//! `"swiftpm": {"product": "greet", "buildArgs": ["-c", "release"]}` instead of `program`.
|
||||
//! The run configuration's before launch task has built the product; this asks
|
||||
//! `swift build <buildArgs> --show-bin-path` where it went (`.build/<triple>/<configuration>`,
|
||||
//! or wherever `--scratch-path` / `--build-path` put it) and launches it from there.
|
||||
|
||||
use crate::adapter::find_binary;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
|
||||
/// `swift build` arguments that print the bin path for `buildArgs` without building.
|
||||
pub fn bin_path_args(swiftpm: &Value) -> Vec<String> {
|
||||
let mut args = vec!["build".to_owned()];
|
||||
if let Some(a) = swiftpm.get("buildArgs").and_then(Value::as_array) {
|
||||
args.extend(a.iter().filter_map(|v| v.as_str().map(str::to_owned)));
|
||||
}
|
||||
args.push("--show-bin-path".into());
|
||||
args
|
||||
}
|
||||
|
||||
/// The built product of `swiftpm` (see the module docs).
|
||||
pub async fn program(cwd: &Path, swiftpm: &Value, cancel: &ide_core::CancellationToken) -> IdeResult<PathBuf> {
|
||||
let product = swiftpm
|
||||
.get("product")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|p| !p.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("the SwiftPM launch names no product"))?;
|
||||
let swift = find_binary("swift", cwd).ok_or_else(|| IdeError::unavailable("`swift` not found on PATH"))?;
|
||||
let args = bin_path_args(swiftpm);
|
||||
let mut cmd = tokio::process::Command::new(swift);
|
||||
cmd.current_dir(cwd);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
|
||||
let out = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
out = cmd.output() => out.map_err(|e| IdeError::unavailable(format!("failed to run swift: {e}")))?,
|
||||
};
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("swift {} failed: {}", args.join(" "), err.trim())));
|
||||
}
|
||||
// The bin path is the last line: SwiftPM may print warnings about the manifest first.
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let dir = stdout.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or_default();
|
||||
if dir.is_empty() {
|
||||
return Err(IdeError::invalid("swift build --show-bin-path printed no path"));
|
||||
}
|
||||
let exe = if cfg!(windows) { format!("{product}.exe") } else { product.to_owned() };
|
||||
Ok(cwd.join(dir).join(exe))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn asks_swift_build_for_the_bin_path_of_the_run_configurations_build() {
|
||||
assert_eq!(bin_path_args(&json!({"product": "greet"})), ["build", "--show-bin-path"]);
|
||||
assert_eq!(
|
||||
bin_path_args(&json!({"product": "greet", "buildArgs": ["-c", "release"]})),
|
||||
["build", "-c", "release", "--show-bin-path"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2164,6 +2164,21 @@ fn frames_keep_their_instruction_pointer() {
|
||||
assert!(json.get("instructionPointerReference").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_drop_pseudo_paths_of_referenced_sources() {
|
||||
let frame = |path: &str, reference: i64| {
|
||||
frame_from(&json!({"id": 1, "name": "f", "line": 1,
|
||||
"source": {"path": path, "sourceReference": reference}}))
|
||||
.path
|
||||
};
|
||||
let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow";
|
||||
assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly");
|
||||
assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent");
|
||||
let here = env!("CARGO_MANIFEST_DIR");
|
||||
assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file");
|
||||
assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn smart_step_into_and_reset_frame() {
|
||||
let h = harness(Script::default());
|
||||
|
||||
@@ -173,6 +173,21 @@ pub const DYNAMIC_PLUGIN_TOOLS: &str = "pluginTools";
|
||||
pub const DYNAMIC_FLUTTER_BUILD: &str = "flutterBuild";
|
||||
/// Id (and `menu.` label key) of the Build › Flutter submenu.
|
||||
pub const FLUTTER_BUILD_MENU: &str = "build.flutter";
|
||||
/// Build › Xcode: Clean Build Folder and Delete DerivedData, filled only when the project has
|
||||
/// Xcode schemes. A submenu after Build › Flutter when it has items, like it.
|
||||
pub const DYNAMIC_XCODE_BUILD: &str = "xcodeBuild";
|
||||
/// Id (and `menu.` label key) of the Build › Xcode submenu.
|
||||
pub const XCODE_BUILD_MENU: &str = "build.xcode";
|
||||
|
||||
/// The submenu (id, English label) a dynamic slot is shown as when it has items, followed by a
|
||||
/// separator; `None`: its items are listed in place.
|
||||
pub fn dynamic_submenu(slot: &str) -> Option<(&'static str, &'static str)> {
|
||||
match slot {
|
||||
DYNAMIC_FLUTTER_BUILD => Some((FLUTTER_BUILD_MENU, "Flutter")),
|
||||
DYNAMIC_XCODE_BUILD => Some((XCODE_BUILD_MENU, "Xcode")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu bar for `os`. Labels are English defaults; the frontend replaces
|
||||
/// them with `menu.<id>` strings from the active locale catalog.
|
||||
@@ -622,6 +637,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"Build",
|
||||
vec![
|
||||
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD),
|
||||
Entry::Dynamic(DYNAMIC_XCODE_BUILD),
|
||||
act("build.buildProject", "Build Project"),
|
||||
act("build.buildModule", "Build Module"),
|
||||
act("build.compileFile", "Recompile"),
|
||||
@@ -1298,12 +1314,12 @@ pub fn model(spec: &[Entry], recent: &[RecentItem], config: &MenuConfig) -> Vec<
|
||||
}
|
||||
}));
|
||||
}
|
||||
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD) => {
|
||||
let items = config.dynamic_items(DYNAMIC_FLUTTER_BUILD);
|
||||
Entry::Dynamic(slot) if let Some((id, label)) = dynamic_submenu(slot) => {
|
||||
let items = config.dynamic_items(slot);
|
||||
if !items.is_empty() {
|
||||
out.push(MenuNode::Submenu {
|
||||
id: FLUTTER_BUILD_MENU.into(),
|
||||
label: "Flutter".into(),
|
||||
id: id.into(),
|
||||
label: label.into(),
|
||||
current: None,
|
||||
children: items.iter().map(DynamicItem::model).collect(),
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -52,6 +52,8 @@ pub mod tools;
|
||||
pub mod vcs;
|
||||
pub mod web;
|
||||
pub mod xcode_bsp;
|
||||
pub mod xcode_clean;
|
||||
pub mod xcode_files;
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
@@ -140,6 +142,8 @@ ide_command::domains!(
|
||||
vcs_commands: crate::ops::vcs::commands,
|
||||
web: crate::ops::web,
|
||||
xcode_bsp: crate::ops::xcode_bsp,
|
||||
xcode_clean: crate::ops::xcode_clean,
|
||||
xcode_files: crate::ops::xcode_files,
|
||||
);
|
||||
|
||||
/// A blocking task that panicked or was cancelled, as the error a command returns.
|
||||
|
||||
@@ -454,7 +454,10 @@ async fn start_inner(
|
||||
if ide_run::is_python_kind(&config.kind) {
|
||||
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
|
||||
}
|
||||
let config = container::prepare(host, &project.root, target, config).await?;
|
||||
let (config, note) = container::prepare(host, &project.root, target, config).await?;
|
||||
if let Some(note) = note {
|
||||
on_output(OutputChunk::System { text: format!("{note}\n") });
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
@@ -552,6 +555,15 @@ async fn start_inner(
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == ide_run::xcode_clean::KIND {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode_clean::prepare(&dir, &cache, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == "go" && config.extras.params.get("scope").is_some_and(|s| s == "file") {
|
||||
let root = project.root.clone();
|
||||
config = host
|
||||
|
||||
@@ -6,8 +6,8 @@ use ide_core::remote_settings::{RunTarget, RunTargetKind};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::DockerEndpoint;
|
||||
use ide_remote::docker::{
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root,
|
||||
compose_service, container_config, container_name, default_container_root,
|
||||
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, NODE_DEBUG_FOLDER,
|
||||
compose_container_root, compose_service, container_config, container_name, default_container_root, node_debug,
|
||||
};
|
||||
use ide_remote::target::DEBUG_PARAM;
|
||||
use ide_run::RunConfig;
|
||||
@@ -16,15 +16,21 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service.
|
||||
pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config: RunConfig) -> IdeResult<RunConfig> {
|
||||
/// `config` rewritten to run in a new container of `target`'s image or service, and for a
|
||||
/// Node.js debug run the line telling the debugger the project folder in the container.
|
||||
pub(super) async fn prepare(
|
||||
host: &Host,
|
||||
root: &Path,
|
||||
target: RunTarget,
|
||||
config: RunConfig,
|
||||
) -> IdeResult<(RunConfig, Option<String>)> {
|
||||
if config.kind == "dotnet" || config.kind == "dotnet-test" {
|
||||
return Err(IdeError::invalid(".NET Project requires the local machine"));
|
||||
}
|
||||
let debug = config.extras.params.get(DEBUG_PARAM).is_some_and(|v| v == "true");
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") {
|
||||
if debug && config.debug_adapter.as_deref() != Some("debugpy") && !node_debug(&config) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"'{}' can't be debugged in a container: only Python run configurations can",
|
||||
"'{}' can't be debugged in a container: only Python and Node.js run configurations can",
|
||||
config.name
|
||||
)));
|
||||
}
|
||||
@@ -41,7 +47,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
let (service_env, service_ports) = server_context(&data_dir, &root, &target, &config);
|
||||
let name = container_name(&config.id, &unique());
|
||||
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
|
||||
container_config(
|
||||
let note = (debug && node_debug(&config)).then(|| format!("{NODE_DEBUG_FOLDER}{container_root}"));
|
||||
let config = container_config(
|
||||
&config,
|
||||
&ContainerRun {
|
||||
target: &target,
|
||||
@@ -60,7 +67,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
|
||||
debugpy: d.debugpy.as_deref(),
|
||||
}),
|
||||
},
|
||||
)
|
||||
)?;
|
||||
Ok((config, note))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Deleting an Xcode project's DerivedData (#6665 C6). Clean Build Folder is a run of
|
||||
//! `ide_run::xcode_clean::KIND`; this is the part a run can't do: moving folders to the Trash.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
async fn dirs(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: Option<String>,
|
||||
params: BTreeMap<String, String>,
|
||||
) -> IdeResult<Vec<PathBuf>> {
|
||||
let project = host.project(window)?;
|
||||
let dir = project.root.join(cwd.unwrap_or_default());
|
||||
let cache = project.cache_dir.clone();
|
||||
super::blocking(move || ide_run::xcode_clean::derived_data_dirs(&dir, &cache, ¶ms)).await
|
||||
}
|
||||
|
||||
/// The DerivedData folders [`xcode_delete_derived_data`] would delete for an `xcode`
|
||||
/// configuration (its `cwd` and `params`), for the user to confirm.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_derived_data(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: Option<String>,
|
||||
params: BTreeMap<String, String>,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
Ok(dirs(host, window, cwd, params).await?.iter().map(|d| d.to_string_lossy().into_owned()).collect())
|
||||
}
|
||||
|
||||
/// Moves the configuration's DerivedData folders to the Trash, then restarts sourcekit-lsp: a
|
||||
/// build server config (xcode-build-server's `build_root`) reads build logs and the index there.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_delete_derived_data(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: Option<String>,
|
||||
params: BTreeMap<String, String>,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let found = dirs(host, window, cwd, params).await?;
|
||||
let deleted = found.clone();
|
||||
super::blocking(move || found.iter().try_for_each(|d| ide_vfs::delete(d))).await?;
|
||||
let project = host.project(window)?;
|
||||
for server in project.lsp.servers().into_iter().filter(|s| s.name == "sourcekit-lsp") {
|
||||
project.lsp.restart(server.id).await?;
|
||||
}
|
||||
Ok(deleted.iter().map(|d| d.to_string_lossy().into_owned()).collect())
|
||||
}
|
||||
|
||||
ide_command::domain!(xcode_clean: xcode_derived_data, xcode_delete_derived_data);
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Source files created, renamed or deleted in an Xcode project (#6665 C7). `xcodebuild` compiles
|
||||
//! only the files a target lists, so a new file in a classic `.xcodeproj` group is silently left
|
||||
//! out. The IDE does not edit `project.pbxproj`: for XcodeGen / Tuist projects it offers to
|
||||
//! regenerate the project, and for a classic project it says which new files the project doesn't
|
||||
//! name, unless the project uses Xcode 16 synchronized folders, which pick new files up themselves.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::IdeResult;
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Source files a target compiles; other files don't make `xcodebuild` miss code.
|
||||
const SOURCE_EXTENSIONS: [&str; 9] = ["swift", "m", "mm", "h", "c", "cc", "cpp", "hpp", "metal"];
|
||||
|
||||
/// What the changed files need in their Xcode project.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum XcodeFileSync {
|
||||
/// The project is generated from `project.yml` (`xcodegen`) or `Project.swift` (`tuist`) in `dir`.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Generated { dir: PathBuf, tool: String },
|
||||
/// `files` (file names) are not named in `project`, a classic `.xcodeproj`.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
NotInProject { project: PathBuf, files: Vec<String> },
|
||||
}
|
||||
|
||||
fn is_source(path: &Path) -> bool {
|
||||
path.extension().and_then(|e| e.to_str()).is_some_and(|e| SOURCE_EXTENSIONS.contains(&e))
|
||||
}
|
||||
|
||||
/// Hidden folders and the bundles themselves are not project sources.
|
||||
fn is_project_file(path: &Path, root: &Path) -> bool {
|
||||
path.strip_prefix(root).is_ok_and(|rel| {
|
||||
rel.components().all(|c| {
|
||||
let name = c.as_os_str().to_string_lossy();
|
||||
!name.starts_with('.') && !name.ends_with(".xcodeproj") && !name.ends_with(".xcworkspace")
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
enum Owner {
|
||||
Generated(PathBuf, &'static str),
|
||||
Classic(Vec<PathBuf>),
|
||||
}
|
||||
|
||||
/// The nearest folder from `path` up to `root` with a project spec or `.xcodeproj` bundles.
|
||||
fn owner(path: &Path, root: &Path) -> Option<Owner> {
|
||||
let mut dir = path.parent()?;
|
||||
loop {
|
||||
if dir.join("project.yml").is_file() {
|
||||
return Some(Owner::Generated(dir.to_path_buf(), "xcodegen"));
|
||||
}
|
||||
if dir.join("Project.swift").is_file() {
|
||||
return Some(Owner::Generated(dir.to_path_buf(), "tuist"));
|
||||
}
|
||||
// A local Swift package builds its files from the folder layout, not from a project.
|
||||
if dir.join("Package.swift").is_file() {
|
||||
return None;
|
||||
}
|
||||
let mut projects: Vec<PathBuf> = std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "xcodeproj") && p.is_dir())
|
||||
.collect();
|
||||
if !projects.is_empty() {
|
||||
projects.sort();
|
||||
return Some(Owner::Classic(projects));
|
||||
}
|
||||
if dir == root {
|
||||
return None;
|
||||
}
|
||||
dir = dir.parent()?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `text` names `file` as a whole name (`/* View.swift */`, `path = View.swift;`,
|
||||
/// `"My View.swift"`), not as the end of another one (`AppView.swift`).
|
||||
fn names(text: &str, file: &str) -> bool {
|
||||
let part_of_name = |c: char| c.is_alphanumeric() || "_-.+".contains(c);
|
||||
text.match_indices(file).any(|(at, _)| {
|
||||
!text[..at].chars().next_back().is_some_and(part_of_name)
|
||||
&& !text[at + file.len()..].chars().next().is_some_and(part_of_name)
|
||||
})
|
||||
}
|
||||
|
||||
/// What `created` (created or renamed to) and `removed` source files under `root` need; the
|
||||
/// first Xcode project they belong to wins.
|
||||
pub fn file_sync(root: &Path, created: &[PathBuf], removed: &[PathBuf]) -> Option<XcodeFileSync> {
|
||||
let relevant = |p: &&PathBuf| is_source(p) && is_project_file(p, root);
|
||||
let mut classic: Option<(Vec<PathBuf>, Vec<String>)> = None;
|
||||
for (path, is_new) in
|
||||
created.iter().filter(relevant).map(|p| (p, true)).chain(removed.iter().filter(relevant).map(|p| (p, false)))
|
||||
{
|
||||
match owner(path, root) {
|
||||
Some(Owner::Generated(dir, tool)) => return Some(XcodeFileSync::Generated { dir, tool: tool.into() }),
|
||||
// A deleted file is still named in the project; Xcode shows it in red.
|
||||
Some(Owner::Classic(projects)) if is_new => {
|
||||
let (owner_projects, files) = classic.get_or_insert_with(|| (projects.clone(), Vec::new()));
|
||||
if *owner_projects == projects {
|
||||
files.push(path.file_name()?.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (projects, files) = classic?;
|
||||
// Plain string checks on project.pbxproj, no parsing; a project mixing groups and
|
||||
// synchronized folders counts as synchronized, as does a name that's taken by another file.
|
||||
let texts: Vec<String> =
|
||||
projects.iter().filter_map(|p| std::fs::read_to_string(p.join("project.pbxproj")).ok()).collect();
|
||||
if texts.is_empty() || texts.iter().any(|t| t.contains("PBXFileSystemSynchronizedRootGroup")) {
|
||||
return None;
|
||||
}
|
||||
let mut files: Vec<String> = files.into_iter().filter(|f| !texts.iter().any(|t| names(t, f))).collect();
|
||||
files.sort();
|
||||
files.dedup();
|
||||
(!files.is_empty()).then(|| XcodeFileSync::NotInProject { project: projects[0].clone(), files })
|
||||
}
|
||||
|
||||
/// What source files created, renamed or deleted in the project need in their Xcode project;
|
||||
/// `None` when they are in none, or it picks them up itself.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn xcode_file_sync(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
created: Vec<PathBuf>,
|
||||
removed: Vec<PathBuf>,
|
||||
) -> IdeResult<Option<XcodeFileSync>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
host.blocking(move || Ok(file_sync(&root, &created, &removed))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(xcode_files: xcode_file_sync);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn project(files: &[(&str, &str)]) -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for (path, text) in files {
|
||||
let path = dir.path().join(path);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
const CLASSIC: &str = "/* Begin PBXFileReference section */ AppView.swift /* End */";
|
||||
|
||||
#[test]
|
||||
fn names_new_sources_a_classic_project_does_not_mention() {
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC), ("App/AppView.swift", "")]);
|
||||
let root = dir.path();
|
||||
let created = [
|
||||
root.join("App/AppView.swift"),
|
||||
root.join("App/New.swift"),
|
||||
root.join("App/View.swift"),
|
||||
root.join("App/notes.md"),
|
||||
];
|
||||
assert_eq!(
|
||||
file_sync(root, &created, &[]),
|
||||
Some(XcodeFileSync::NotInProject {
|
||||
project: root.join("App.xcodeproj"),
|
||||
files: vec!["New.swift".into(), "View.swift".into()]
|
||||
})
|
||||
);
|
||||
// Deleting a file needs nothing in a classic project.
|
||||
assert_eq!(file_sync(root, &[], &[root.join("App/AppView.swift")]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusts_synchronized_folders() {
|
||||
let text = "/* Begin PBXFileSystemSynchronizedRootGroup section */";
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", text)]);
|
||||
assert_eq!(file_sync(dir.path(), &[dir.path().join("App/New.swift")], &[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offers_the_generator_of_the_nearest_spec() {
|
||||
let dir =
|
||||
project(&[("project.yml", ""), ("App.xcodeproj/project.pbxproj", CLASSIC), ("Mod/Project.swift", "")]);
|
||||
let root = dir.path();
|
||||
let generated = |dir: PathBuf, tool: &str| Some(XcodeFileSync::Generated { dir, tool: tool.into() });
|
||||
assert_eq!(file_sync(root, &[], &[root.join("Sources/Old.swift")]), generated(root.into(), "xcodegen"));
|
||||
assert_eq!(file_sync(root, &[root.join("Mod/A.m")], &[]), generated(root.join("Mod"), "tuist"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_files_of_a_local_package_next_to_the_project() {
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC), ("Packages/Feature/Package.swift", "")]);
|
||||
let root = dir.path();
|
||||
assert_eq!(file_sync(root, &[root.join("Packages/Feature/Sources/Feature/New.swift")], &[]), None);
|
||||
// Files of the app itself are still checked.
|
||||
assert!(file_sync(root, &[root.join("App/New.swift")], &[]).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_files_outside_any_project() {
|
||||
let dir = project(&[("App.xcodeproj/project.pbxproj", CLASSIC)]);
|
||||
let root = dir.path();
|
||||
assert_eq!(file_sync(&root.join("Sub"), &[root.join("Sub/A.swift")], &[]), None);
|
||||
assert_eq!(file_sync(root, &[root.join(".build/A.swift"), PathBuf::from("/elsewhere/A.swift")], &[]), None);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,22 @@ pub struct NavigationFiles {
|
||||
pub paths: Vec<ide_core::IpcPath>,
|
||||
pub indexing: bool,
|
||||
pub extensions: Vec<String>,
|
||||
/// In-scope files matching `extensions`; `paths` holds the first
|
||||
/// `MAX_NAVIGATION_FILES` of them.
|
||||
pub total: u32,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Discovery offers at most this many files; larger projects get navigation
|
||||
/// on the first ones instead of none.
|
||||
const MAX_NAVIGATION_FILES: usize = 20_000;
|
||||
|
||||
/// The first `limit` files `in_scope` accepts, and how many it accepts in all.
|
||||
fn first_in_scope(files: Vec<PathBuf>, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec<PathBuf>, usize) {
|
||||
let mut files: Vec<_> = files.into_iter().filter(in_scope).collect();
|
||||
let total = files.len();
|
||||
files.truncate(limit);
|
||||
(files, total)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -24,19 +40,25 @@ pub async fn plugin_navigation_files(
|
||||
blocking(move || {
|
||||
let extensions = plugins.navigation_extensions(&project.root);
|
||||
if extensions.is_empty() {
|
||||
return Ok(NavigationFiles { paths: vec![], indexing: false, extensions: vec![] });
|
||||
return Ok(NavigationFiles {
|
||||
paths: vec![],
|
||||
indexing: false,
|
||||
extensions: vec![],
|
||||
total: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
let indexing = project.index.status().indexing;
|
||||
let files = project.index.files_with_extensions(&extensions, 20_001);
|
||||
if files.len() > 20_000 {
|
||||
return Err(IdeError::unavailable("plugin navigation supports up to 20,000 matching files"));
|
||||
}
|
||||
let files = project.index.files_with_extensions(&extensions, usize::MAX);
|
||||
// A project window group's members are project scope: their files are
|
||||
// in the group's index (the group root holds none of them).
|
||||
let members = crate::project::workspace_member_roots(&project.root);
|
||||
let in_scope = |p: &PathBuf| p.starts_with(&project.root) || members.iter().any(|m| p.starts_with(m));
|
||||
let (files, total) = first_in_scope(files, in_scope, MAX_NAVIGATION_FILES);
|
||||
Ok(NavigationFiles {
|
||||
paths: files.into_iter().filter(in_scope).map(Into::into).collect(),
|
||||
truncated: total > files.len(),
|
||||
total: u32::try_from(total).unwrap_or(u32::MAX),
|
||||
paths: files.into_iter().map(Into::into).collect(),
|
||||
indexing,
|
||||
extensions,
|
||||
})
|
||||
@@ -210,3 +232,19 @@ ide_command::domain!(
|
||||
plugin_navigation_invalidate,
|
||||
plugin_navigation_markers,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() {
|
||||
let files: Vec<PathBuf> = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
|
||||
let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3);
|
||||
// Out-of-scope files neither take a slot nor count toward the total.
|
||||
assert_eq!(total, 4);
|
||||
assert_eq!(kept, ["/p/0/f0.xml", "/p/0/f2.xml", "/p/0/f4.xml"].map(PathBuf::from));
|
||||
let (kept, total) = first_in_scope(kept, |_| true, 20_000);
|
||||
assert_eq!((kept.len(), total), (3, 3));
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
@@ -414,7 +414,7 @@ pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
|
||||
});
|
||||
|
||||
// Caches & LSP & Web & Workspace & HTTP helpers already available through ide-host dependencies.
|
||||
dispatcher.add("caches_local_data_info", TrustClass::Trusted, |c| async move {
|
||||
dispatcher.add("caches_local_data_info", TrustClass::Always, |c| async move {
|
||||
let current = c.host.local_data_dir.to_string_lossy().into_owned();
|
||||
Ok(LocalDataInfo {
|
||||
default_dir: current.clone(),
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Swift packages (`Package.swift`): one `swift run <product>` per executable product, built
|
||||
//! first by `swift build --product <product>` and debuggable with lldb-dap on the built
|
||||
//! `.build/debug/<product>`. Read from the manifest's source: `swift package describe` would
|
||||
//! product (found by `swift build --show-bin-path` when debugging). Read from the manifest's source: `swift package describe` would
|
||||
//! compile and run the manifest, and detection never runs the project's build code.
|
||||
|
||||
use super::zig::{call_body, code_only, string_at};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Xcode schemes: one configuration per scheme that builds its app and runs it on the iOS
|
||||
//! Simulator (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
|
||||
//! Simulator or the Mac (see [`crate::xcode::prepare`]). A workspace next to the projects builds them all,
|
||||
//! so its schemes and theirs are built through it.
|
||||
|
||||
use super::{ConfigExt, config};
|
||||
|
||||
@@ -23,6 +23,7 @@ pub mod tomcat;
|
||||
mod utf8;
|
||||
pub mod wrap;
|
||||
pub mod xcode;
|
||||
pub mod xcode_clean;
|
||||
|
||||
pub use detect::cmake::{build_configs as cmake_build_configs, prepare as prepare_cmake};
|
||||
pub use process::{DetachedProcessKills, ProcessManager, StartOptions};
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
//! projects without any, but it takes a second or two, too slow for detection.
|
||||
//!
|
||||
//! A scheme's run configuration builds it for the iOS Simulator and launches the app there with
|
||||
//! `simctl`; [`prepare`] turns the configuration into that process when it starts.
|
||||
//! `simctl`, or, for a macOS app, builds it for the Mac and runs its executable;
|
||||
//! [`prepare`] turns the configuration into that process when it starts.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use quick_xml::{Reader, XmlVersion, events::Event};
|
||||
@@ -208,15 +209,24 @@ fn pick_simulator(json: &str) -> Option<String> {
|
||||
|
||||
/// The run configuration parameter that holds the simulator's UDID. Empty means
|
||||
/// [`default_simulator`]: the one place a device selector can feed its choice into.
|
||||
/// [`MAC`] runs an app that supports both on the Mac instead.
|
||||
pub const SIMULATOR_PARAM: &str = "simulator";
|
||||
|
||||
/// Set (to anything but empty) by Debug: the app is launched suspended
|
||||
/// (`simctl launch --wait-for-debugger`) until the debugger attaches to the pid simctl prints.
|
||||
pub const WAIT_FOR_DEBUGGER_PARAM: &str = "waitForDebugger";
|
||||
|
||||
/// The [`SIMULATOR_PARAM`] value that runs a multiplatform app on the Mac.
|
||||
pub const MAC: &str = "macos";
|
||||
|
||||
/// The `xcodebuild` arguments that pick what is built, and where, for a `kind = "xcode"`
|
||||
/// configuration: its `container`, `scheme` and `configuration` params and the simulator.
|
||||
pub fn build_args(params: &BTreeMap<String, String>, udid: &str, derived_data: &Path) -> Result<Vec<String>, String> {
|
||||
/// configuration: its `container`, `scheme` and `configuration` params and the `-destination`
|
||||
/// (`id=<udid>`, `platform=macOS`; None leaves it to the scheme).
|
||||
pub fn build_args(
|
||||
params: &BTreeMap<String, String>,
|
||||
destination: Option<&str>,
|
||||
derived_data: &Path,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let param = |key: &str| params.get(key).map(|v| v.trim()).filter(|v| !v.is_empty());
|
||||
let container = param("container").ok_or("No Xcode project or workspace is set")?;
|
||||
let scheme = param("scheme").ok_or("No scheme is set")?;
|
||||
@@ -225,30 +235,50 @@ pub fn build_args(params: &BTreeMap<String, String>, udid: &str, derived_data: &
|
||||
if let Some(configuration) = param("configuration") {
|
||||
args.extend(["-configuration".to_owned(), configuration.to_owned()]);
|
||||
}
|
||||
args.extend([
|
||||
"-destination".to_owned(),
|
||||
format!("id={udid}"),
|
||||
"-derivedDataPath".to_owned(),
|
||||
derived_data.to_string_lossy().into_owned(),
|
||||
]);
|
||||
if let Some(destination) = destination {
|
||||
args.extend(["-destination".to_owned(), destination.to_owned()]);
|
||||
}
|
||||
args.extend(["-derivedDataPath".to_owned(), derived_data.to_string_lossy().into_owned()]);
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The application targets' build settings in `xcodebuild -showBuildSettings -json` output.
|
||||
fn app_settings(settings: &str) -> Result<Vec<serde_json::Value>, String> {
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_str(settings).map_err(|e| format!("Unreadable build settings: {e}"))?;
|
||||
let targets = json.as_array().cloned().unwrap_or_default();
|
||||
Ok(targets
|
||||
.into_iter()
|
||||
.map(|mut t| t["buildSettings"].take())
|
||||
.filter(|b| b["PRODUCT_TYPE"] == "com.apple.product-type.application")
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Whether the scheme's first application runs on the Mac, from its `SUPPORTED_PLATFORMS` in
|
||||
/// build settings read without a destination: it supports macOS but not the iOS Simulator, or
|
||||
/// both and `simulator` is [`MAC`].
|
||||
pub fn runs_on_mac(settings: &str, simulator: &str) -> Result<bool, String> {
|
||||
let apps = app_settings(settings)?;
|
||||
let app = apps.first().ok_or("The scheme builds no application")?;
|
||||
let platforms: Vec<&str> = app["SUPPORTED_PLATFORMS"].as_str().unwrap_or_default().split_whitespace().collect();
|
||||
Ok(platforms.contains(&"macosx") && (simulator.trim() == MAC || !platforms.contains(&"iphonesimulator")))
|
||||
}
|
||||
|
||||
/// The executable inside the built macOS `.app`: `TARGET_BUILD_DIR/EXECUTABLE_PATH`.
|
||||
pub fn mac_executable(settings: &str) -> Result<PathBuf, String> {
|
||||
let apps = app_settings(settings)?;
|
||||
let app = apps.iter().find(|b| b["PLATFORM_NAME"] == "macosx").ok_or("The scheme builds no macOS application")?;
|
||||
let get =
|
||||
|key: &str| app[key].as_str().filter(|v| !v.is_empty()).ok_or(format!("The build settings have no {key}"));
|
||||
Ok(Path::new(get("TARGET_BUILD_DIR")?).join(get("EXECUTABLE_PATH")?))
|
||||
}
|
||||
|
||||
/// The built `.app` and its bundle id, from `xcodebuild -showBuildSettings -json`: the
|
||||
/// scheme's first application target.
|
||||
pub fn built_app(settings: &str) -> Result<(PathBuf, String), String> {
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_str(settings).map_err(|e| format!("Unreadable build settings: {e}"))?;
|
||||
let targets = json.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
let apps = || {
|
||||
targets
|
||||
.iter()
|
||||
.map(|t| &t["buildSettings"])
|
||||
.filter(|b| b["PRODUCT_TYPE"] == "com.apple.product-type.application")
|
||||
};
|
||||
let Some(app) = apps().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else {
|
||||
return Err(match apps().next().and_then(|b| b["PLATFORM_NAME"].as_str()) {
|
||||
Some("macosx") => "Running macOS apps is not supported yet; only iOS apps run on the Simulator".to_owned(),
|
||||
let apps = app_settings(settings)?;
|
||||
let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else {
|
||||
return Err(match apps.first().and_then(|b| b["PLATFORM_NAME"].as_str()) {
|
||||
Some(platform) => format!("The scheme builds an app for {platform}, not the iOS Simulator"),
|
||||
None => "The scheme builds no application".to_owned(),
|
||||
});
|
||||
@@ -311,33 +341,79 @@ fn announce_suspended(udid: &str, bundle_id: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The script a macOS run executes: build, then become the app's executable, so its output
|
||||
/// reaches the console and a Stop's SIGINT reaches the app. Its arguments follow as `$@`.
|
||||
pub fn mac_launch_script(build_args: &[String], executable: &Path) -> String {
|
||||
let build: Vec<String> = build_args.iter().map(|a| sh_quote(a)).collect();
|
||||
format!("set -e\nxcodebuild {} build\nexec {} \"$@\"\n", build.join(" "), sh_quote(&executable.to_string_lossy()))
|
||||
}
|
||||
|
||||
/// The `-destination` of a run of `params` on a Mac.
|
||||
pub const MAC_DESTINATION: &str = "platform=macOS";
|
||||
|
||||
/// Runs `program` in `dir` and returns its stdout; a failure carries its stderr.
|
||||
fn output(dir: &Path, program: &str, args: &[String]) -> IdeResult<String> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
cmd.args(args).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd)
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("Cannot run {program}: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("{program} {} failed:\n{}", args.join(" "), err.trim())));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
}
|
||||
|
||||
/// Where a run of `params` builds: [`MAC_DESTINATION`] when the scheme's app runs on the Mac
|
||||
/// ([`runs_on_mac`]), else `id=<udid>` of the configured simulator or the default one. A Clean
|
||||
/// Build Folder of the configuration uses the same destination.
|
||||
pub fn destination(dir: &Path, params: &BTreeMap<String, String>, derived_data: &Path) -> IdeResult<String> {
|
||||
let simulator = params.get(SIMULATOR_PARAM).map_or("", String::as_str);
|
||||
let args = [
|
||||
build_args(params, None, derived_data).map_err(IdeError::invalid)?,
|
||||
vec!["-showBuildSettings".into(), "-json".into()],
|
||||
]
|
||||
.concat();
|
||||
if runs_on_mac(&output(dir, "xcodebuild", &args)?, simulator).map_err(IdeError::invalid)? {
|
||||
return Ok(MAC_DESTINATION.to_owned());
|
||||
}
|
||||
let udid = match Some(simulator.trim()).filter(|s| !s.is_empty() && *s != MAC) {
|
||||
Some(udid) => udid.to_owned(),
|
||||
None => default_simulator().ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
|
||||
};
|
||||
Ok(format!("id={udid}"))
|
||||
}
|
||||
|
||||
/// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches
|
||||
/// its scheme on the simulator. `dir` is the run's working directory; DerivedData goes under
|
||||
/// `cache_dir`. The configuration's environment reaches the app as `SIMCTL_CHILD_*`.
|
||||
/// `cache_dir`. The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`.
|
||||
/// A macOS app ([`runs_on_mac`]) is built for `platform=macOS` and run directly, with no simulator.
|
||||
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Err(IdeError::unavailable("Xcode schemes run on macOS only"));
|
||||
}
|
||||
let output = |program: &str, args: &[String]| -> IdeResult<String> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
cmd.args(args).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd)
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("Cannot run {program}: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("{program} {} failed:\n{}", args.join(" "), err.trim())));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
};
|
||||
let params = &config.extras.params;
|
||||
let udid = match params.get(SIMULATOR_PARAM).map(|s| s.trim()).filter(|s| !s.is_empty()) {
|
||||
Some(udid) => udid.to_owned(),
|
||||
None => default_simulator().ok_or_else(|| IdeError::unavailable("No iOS simulator is available"))?,
|
||||
};
|
||||
let derived_data = cache_dir.join("xcode/DerivedData");
|
||||
let args = build_args(params, &udid, &derived_data).map_err(IdeError::invalid)?;
|
||||
let settings = output("xcodebuild", &[args.as_slice(), &["-showBuildSettings".into(), "-json".into()]].concat())?;
|
||||
let derived_data = crate::xcode_clean::ide_derived_data(cache_dir);
|
||||
let show =
|
||||
|args: &[String]| output(dir, "xcodebuild", &[args, &["-showBuildSettings".into(), "-json".into()]].concat());
|
||||
let destination = destination(dir, params, &derived_data)?;
|
||||
if destination == MAC_DESTINATION {
|
||||
let args = build_args(params, Some(MAC_DESTINATION), &derived_data).map_err(IdeError::invalid)?;
|
||||
let executable = mac_executable(&show(&args)?).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
config.command = "/bin/sh".into();
|
||||
config.args = ["-c".to_owned(), mac_launch_script(&args, &executable), "xcode-run".to_owned()]
|
||||
.into_iter()
|
||||
.chain(app_args)
|
||||
.collect();
|
||||
// Foundation buffers a GUI app's stdout when it is not a terminal; Xcode sets this too.
|
||||
config.env.entry("NSUnbufferedIO".to_owned()).or_insert_with(|| "YES".to_owned());
|
||||
return Ok(());
|
||||
}
|
||||
let udid = destination.trim_start_matches("id=").to_owned();
|
||||
let args = build_args(params, Some(&destination), &derived_data).map_err(IdeError::invalid)?;
|
||||
let settings = show(&args)?;
|
||||
let (app, bundle_id) = built_app(&settings).map_err(IdeError::invalid)?;
|
||||
let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str));
|
||||
let wait = params.get(WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty());
|
||||
@@ -477,7 +553,7 @@ mod tests {
|
||||
.into();
|
||||
let dd = Path::new("/cache/DerivedData");
|
||||
assert_eq!(
|
||||
build_args(¶ms, "U1", dd).unwrap(),
|
||||
build_args(¶ms, Some("id=U1"), dd).unwrap(),
|
||||
[
|
||||
"-workspace",
|
||||
"App.xcworkspace",
|
||||
@@ -494,11 +570,11 @@ mod tests {
|
||||
params.insert("container".into(), "App.xcodeproj".into());
|
||||
params.remove("configuration");
|
||||
assert_eq!(
|
||||
build_args(¶ms, "U1", dd).unwrap()[..5],
|
||||
build_args(¶ms, Some("id=U1"), dd).unwrap()[..5],
|
||||
["-project", "App.xcodeproj", "-scheme", "App", "-destination"]
|
||||
);
|
||||
params.remove("scheme");
|
||||
assert_eq!(build_args(¶ms, "U1", dd).unwrap_err(), "No scheme is set");
|
||||
assert_eq!(build_args(¶ms, Some("id=U1"), dd).unwrap_err(), "No scheme is set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -517,10 +593,101 @@ mod tests {
|
||||
built_app(&settings("iphonesimulator")).unwrap(),
|
||||
(PathBuf::from("/dd/Build/Products/Debug-iphonesimulator/App.app"), "dev.example.App".to_owned())
|
||||
);
|
||||
assert!(built_app(&settings("macosx")).unwrap_err().contains("macOS apps is not supported"));
|
||||
assert_eq!(
|
||||
built_app(&settings("macosx")).unwrap_err(),
|
||||
"The scheme builds an app for macosx, not the iOS Simulator"
|
||||
);
|
||||
assert_eq!(built_app("[]").unwrap_err(), "The scheme builds no application");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mac_only_app_or_a_multiplatform_one_pinned_to_the_mac_runs_on_the_mac() {
|
||||
let settings = |platforms: &str| {
|
||||
format!(
|
||||
r#"[{{"target": "Kit", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.framework", "SUPPORTED_PLATFORMS": "macosx"}}}},
|
||||
{{"target": "App", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.application", "SUPPORTED_PLATFORMS": "{platforms}"}}}}]"#
|
||||
)
|
||||
};
|
||||
assert!(runs_on_mac(&settings("macosx"), "").unwrap());
|
||||
assert!(runs_on_mac(&settings("macosx"), "SOME-UDID").unwrap());
|
||||
assert!(!runs_on_mac(&settings("iphoneos iphonesimulator"), "").unwrap());
|
||||
assert!(!runs_on_mac(&settings("iphoneos iphonesimulator"), MAC).unwrap());
|
||||
assert!(!runs_on_mac(&settings("iphoneos iphonesimulator macosx"), "SOME-UDID").unwrap());
|
||||
assert!(runs_on_mac(&settings("iphoneos iphonesimulator macosx"), " macos ").unwrap());
|
||||
assert_eq!(runs_on_mac("[]", "").unwrap_err(), "The scheme builds no application");
|
||||
|
||||
let mac = r#"[{"target": "App", "buildSettings": {"PRODUCT_TYPE": "com.apple.product-type.application",
|
||||
"PLATFORM_NAME": "macosx", "TARGET_BUILD_DIR": "/dd/Build/Products/Debug", "EXECUTABLE_PATH": "My App.app/Contents/MacOS/My App"}}]"#;
|
||||
assert_eq!(
|
||||
mac_executable(mac).unwrap(),
|
||||
PathBuf::from("/dd/Build/Products/Debug/My App.app/Contents/MacOS/My App")
|
||||
);
|
||||
assert_eq!(mac_executable(&settings("macosx")).unwrap_err(), "The scheme builds no macOS application");
|
||||
let dd = Path::new("/dd");
|
||||
let params: BTreeMap<String, String> =
|
||||
[("container", "App.xcodeproj"), ("scheme", "App")].map(|(k, v)| (k.to_owned(), v.to_owned())).into();
|
||||
assert_eq!(
|
||||
build_args(¶ms, Some("platform=macOS"), dd).unwrap(),
|
||||
[
|
||||
"-project",
|
||||
"App.xcodeproj",
|
||||
"-scheme",
|
||||
"App",
|
||||
"-destination",
|
||||
"platform=macOS",
|
||||
"-derivedDataPath",
|
||||
"/dd"
|
||||
]
|
||||
);
|
||||
assert!(!build_args(¶ms, None, dd).unwrap().iter().any(|a| a == "-destination"));
|
||||
}
|
||||
|
||||
/// The script builds, then runs the executable in its place: the stub app logs its arguments
|
||||
/// and environment and exits on the SIGINT a Stop sends.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn mac_launch_script_builds_then_runs_the_executable_until_stopped() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let log = dir.path().join("log");
|
||||
let stub = |path: &Path, then: &str| {
|
||||
let body = format!(
|
||||
"#!/bin/sh\nprintf '%s' \"${{0##*/}}\" >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}"
|
||||
);
|
||||
fs::write(path, body).unwrap();
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
stub(&dir.path().join("xcodebuild"), "");
|
||||
let exe = dir.path().join("My App");
|
||||
stub(
|
||||
&exe,
|
||||
"echo \"GREETING=$GREETING\" >> \"$LOG\"\ntrap 'echo stopped >> \"$LOG\"; exit 0' INT\nwhile :; do sleep 0.05; done\n",
|
||||
);
|
||||
let build = ["-scheme".to_owned(), "It's".to_owned(), "-destination".to_owned(), "platform=macOS".to_owned()];
|
||||
let mut child = std::process::Command::new("/bin/sh")
|
||||
.args(["-c", &mac_launch_script(&build, &exe), "xcode-run", "--greeting", "hi there"])
|
||||
.env("PATH", format!("{}:/usr/bin:/bin", dir.path().display()))
|
||||
.env("LOG", &log)
|
||||
.env("GREETING", "hello")
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
while !fs::read_to_string(&log).unwrap_or_default().contains("GREETING") && std::time::Instant::now() < deadline
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(200));
|
||||
unsafe { libc::kill(child.id() as i32, libc::SIGINT) };
|
||||
assert!(child.wait().unwrap().success());
|
||||
assert_eq!(
|
||||
fs::read_to_string(&log).unwrap(),
|
||||
"xcodebuild [-scheme] [It's] [-destination] [platform=macOS] [build]\n\
|
||||
My App [--greeting] [hi there]\n\
|
||||
GREETING=hello\n\
|
||||
stopped\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// Runs the script against stub `xcodebuild`, `xcrun` and `open` that log their arguments; the
|
||||
/// stub `simctl launch` runs until it gets SIGTERM, which a Stop's SIGINT must turn into.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Product › Clean Build Folder and deleting a project's DerivedData, for the `kind = "xcode"`
|
||||
//! configurations of `crate::detect::xcode`.
|
||||
use crate::xcode::{build_args, destination};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The configuration kind of a Clean Build Folder run; its params are an `xcode` configuration's.
|
||||
pub const KIND: &str = "xcode-clean";
|
||||
|
||||
/// Where the IDE's runs of a project build: `xcodebuild -derivedDataPath`, under the project's cache.
|
||||
pub fn ide_derived_data(cache_dir: &Path) -> PathBuf {
|
||||
cache_dir.join("xcode/DerivedData")
|
||||
}
|
||||
|
||||
/// Turns a [`KIND`] configuration into `xcodebuild clean` of the build its `xcode` configuration
|
||||
/// runs: the same container, scheme, configuration, destination (the simulator, or the Mac for a
|
||||
/// macOS app) and DerivedData. `dir` is the configuration's working directory.
|
||||
pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> {
|
||||
let params = &config.extras.params;
|
||||
let derived_data = ide_derived_data(cache_dir);
|
||||
let destination = destination(dir, params, &derived_data)?;
|
||||
config.args = clean_args(params, &destination, &derived_data).map_err(IdeError::invalid)?;
|
||||
config.command = "xcodebuild".into();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clean_args(
|
||||
params: &BTreeMap<String, String>,
|
||||
destination: &str,
|
||||
derived_data: &Path,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let mut args = build_args(params, Some(destination), derived_data)?;
|
||||
args.push("clean".into());
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// `xcodebuild -showBuildSettings -json` of the scheme as Xcode builds it: no destination and no
|
||||
/// `-derivedDataPath`, so the build folder is the one in Xcode's DerivedData location.
|
||||
fn settings_args(params: &BTreeMap<String, String>) -> Result<Vec<String>, String> {
|
||||
let param = |key: &str| params.get(key).map(|v| v.trim()).filter(|v| !v.is_empty());
|
||||
let container = param("container").ok_or("No Xcode project or workspace is set")?;
|
||||
let scheme = param("scheme").ok_or("No scheme is set")?;
|
||||
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
|
||||
let mut args = vec![flag.to_owned(), container.to_owned(), "-scheme".to_owned(), scheme.to_owned()];
|
||||
if let Some(configuration) = param("configuration") {
|
||||
args.extend(["-configuration".to_owned(), configuration.to_owned()]);
|
||||
}
|
||||
args.extend(["-showBuildSettings".to_owned(), "-json".to_owned()]);
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The project's `<Name>-<hash>` folder in Xcode's DerivedData: the ancestor of the build
|
||||
/// settings' `BUILD_DIR` (else `OBJROOT`) that sits directly in a `DerivedData` folder. `None`
|
||||
/// when the build folder is elsewhere (a custom DerivedData location or a legacy `build/`).
|
||||
pub fn derived_data_of(settings: &str) -> Option<PathBuf> {
|
||||
let json: serde_json::Value = serde_json::from_str(settings).ok()?;
|
||||
let build = json.as_array()?.iter().find_map(|t| {
|
||||
let s = &t["buildSettings"];
|
||||
s["BUILD_DIR"].as_str().or(s["OBJROOT"].as_str()).filter(|v| !v.is_empty())
|
||||
})?;
|
||||
Path::new(build)
|
||||
.ancestors()
|
||||
.find(|dir| dir.parent().and_then(Path::file_name).is_some_and(|name| name == "DerivedData"))
|
||||
.map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// The existing DerivedData folders of an `xcode` configuration's project: Xcode's
|
||||
/// `<Name>-<hash>` one (Xcode's own builds and the scheme's tests) and the IDE's runs' one.
|
||||
/// `dir` is the configuration's working directory.
|
||||
pub fn derived_data_dirs(dir: &Path, cache_dir: &Path, params: &BTreeMap<String, String>) -> IdeResult<Vec<PathBuf>> {
|
||||
let args = settings_args(params).map_err(IdeError::invalid)?;
|
||||
let mut cmd = std::process::Command::new("xcodebuild");
|
||||
cmd.args(&args).current_dir(dir);
|
||||
let out = ide_core::process::prepare(&mut cmd)
|
||||
.output()
|
||||
.map_err(|e| IdeError::unavailable(format!("Cannot run xcodebuild: {e}")))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("xcodebuild {} failed:\n{}", args.join(" "), err.trim())));
|
||||
}
|
||||
let xcode = derived_data_of(&String::from_utf8_lossy(&out.stdout));
|
||||
Ok(xcode.into_iter().chain([ide_derived_data(cache_dir)]).filter(|d| d.is_dir()).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn params(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
|
||||
pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_cleans_the_build_a_run_makes() {
|
||||
let p = params(&[("container", "App.xcworkspace"), ("scheme", "App"), ("configuration", "Debug")]);
|
||||
assert_eq!(
|
||||
clean_args(&p, "id=UDID", Path::new("/cache/xcode/DerivedData")).unwrap(),
|
||||
[
|
||||
"-workspace",
|
||||
"App.xcworkspace",
|
||||
"-scheme",
|
||||
"App",
|
||||
"-configuration",
|
||||
"Debug",
|
||||
"-destination",
|
||||
"id=UDID",
|
||||
"-derivedDataPath",
|
||||
"/cache/xcode/DerivedData",
|
||||
"clean"
|
||||
]
|
||||
);
|
||||
assert_eq!(ide_derived_data(Path::new("/cache")), Path::new("/cache/xcode/DerivedData"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_settings_are_read_where_xcode_builds() {
|
||||
let p = params(&[("container", "App.xcodeproj"), ("scheme", "App")]);
|
||||
assert_eq!(
|
||||
settings_args(&p).unwrap(),
|
||||
["-project", "App.xcodeproj", "-scheme", "App", "-showBuildSettings", "-json"]
|
||||
);
|
||||
assert!(settings_args(¶ms(&[("container", "App.xcodeproj")])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_data_is_the_folder_in_derived_data_that_holds_the_build() {
|
||||
let settings = |key: &str, dir: &str| format!(r#"[{{"target":"App","buildSettings":{{"{key}":"{dir}"}}}}]"#);
|
||||
let dd = "/Users/me/Library/Developer/Xcode/DerivedData/App-abcdef";
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", &format!("{dd}/Build/Products"))), Some(dd.into()));
|
||||
assert_eq!(
|
||||
derived_data_of(&settings("OBJROOT", &format!("{dd}/Build/Intermediates.noindex"))),
|
||||
Some(dd.into())
|
||||
);
|
||||
// A custom location or a legacy build folder: nothing to delete.
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", "/Volumes/Builds/App-abcdef/Build/Products")), None);
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", "/src/App/build")), None);
|
||||
// The DerivedData folder itself is never the answer.
|
||||
assert_eq!(derived_data_of(&settings("BUILD_DIR", "/x/DerivedData")), None);
|
||||
assert_eq!(derived_data_of("not json"), None);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -464,11 +464,16 @@ fn renamed_from(
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The log index, locked only around reads and writes: Git runs without it, so commit
|
||||
/// details and one-commit queries need not wait for a long history walk.
|
||||
fn lock(index: &std::sync::Mutex<crate::log_index::LogIndex>) -> std::sync::MutexGuard<'_, crate::log_index::LogIndex> {
|
||||
index.lock().unwrap_or_else(|p| p.into_inner())
|
||||
}
|
||||
|
||||
pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut index = r.log_index.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let result = if q.summary_only {
|
||||
let mut all = q.clone();
|
||||
all.skip = 0;
|
||||
@@ -483,14 +488,19 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
|
||||
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
|
||||
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
|
||||
let cached = index.views.get(&key).cloned();
|
||||
let cached = lock(&r.log_index).views.get(&key).cloned();
|
||||
let view = if let Some(cached) = cached {
|
||||
cached
|
||||
} else {
|
||||
// Immutable metadata is reused across roots, filters, merges and ref changes.
|
||||
all.request = q.request;
|
||||
let rows =
|
||||
std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(r, &all, cancel, &mut index)?));
|
||||
let rows = std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(
|
||||
r,
|
||||
&all,
|
||||
cancel,
|
||||
&r.log_index,
|
||||
)?));
|
||||
let mut index = lock(&r.log_index);
|
||||
if index.views.len() >= 4 {
|
||||
index.views.clear();
|
||||
}
|
||||
@@ -512,6 +522,7 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
let retain = q.retain_until.as_ref().and_then(|id| find_pos(id)).map(|i| i + 1).unwrap_or(0);
|
||||
let limit = if q.limit == 0 { usize::MAX } else { (q.limit as usize).max(retain.saturating_sub(start)) };
|
||||
let total = view.rows.len() as u32;
|
||||
let mut index = lock(&r.log_index);
|
||||
let db = index.db().cloned();
|
||||
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
|
||||
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
|
||||
@@ -538,9 +549,9 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
log_indexed(r, q, cancel, &mut index)
|
||||
log_indexed(r, q, cancel, &r.log_index)
|
||||
};
|
||||
index.flush();
|
||||
lock(&r.log_index).flush();
|
||||
result
|
||||
}
|
||||
|
||||
@@ -640,7 +651,7 @@ fn log_indexed(
|
||||
r: &Repo,
|
||||
q: &LogQuery,
|
||||
cancel: &CancellationToken,
|
||||
index: &mut crate::log_index::LogIndex,
|
||||
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
|
||||
) -> IdeResult<Vec<Commit>> {
|
||||
let repo = r.gix()?;
|
||||
let shallow: HashSet<ObjectId> =
|
||||
@@ -676,6 +687,8 @@ fn log_indexed(
|
||||
&& q.since_ms.is_none()
|
||||
&& q.until_ms.is_none()
|
||||
{
|
||||
let mut guard = lock(shared);
|
||||
let index = &mut *guard;
|
||||
update_head_reachable(&repo, index, cancel)?;
|
||||
let id = tips[0];
|
||||
let record = index.get(&repo, id)?;
|
||||
@@ -706,7 +719,9 @@ fn log_indexed(
|
||||
commit.message_truncated = false;
|
||||
return Ok(vec![commit]);
|
||||
}
|
||||
let rows = log_indexed_rows(r, q, cancel, index)?;
|
||||
let rows = log_indexed_rows(r, q, cancel, shared)?;
|
||||
let mut guard = lock(shared);
|
||||
let index = &mut *guard;
|
||||
let db = index.db().cloned();
|
||||
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
|
||||
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
|
||||
@@ -724,7 +739,7 @@ fn log_indexed_rows(
|
||||
r: &Repo,
|
||||
q: &LogQuery,
|
||||
cancel: &CancellationToken,
|
||||
index: &mut crate::log_index::LogIndex,
|
||||
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
|
||||
) -> IdeResult<Vec<crate::log_index::IndexedRow>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -775,7 +790,7 @@ fn log_indexed_rows(
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?)
|
||||
Some(sort_shared(&repo, ids, q, &shallow, cancel, shared)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -802,14 +817,17 @@ fn log_indexed_rows(
|
||||
};
|
||||
let authors: Vec<_> =
|
||||
q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect();
|
||||
update_head_reachable(&repo, index, cancel)?;
|
||||
let mut range_ids_set = range_ids.as_ref().map(|ids| ids.iter().copied().collect::<HashSet<_>>());
|
||||
type Walk<'a> = Box<dyn Iterator<Item = IdeResult<ObjectId>> + 'a>;
|
||||
let walk: Walk<'_> = if let Some(ids) = range_ids {
|
||||
Box::new(ids.into_iter().map(Ok))
|
||||
} else if q.summary_only {
|
||||
let ids = index.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
|
||||
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
|
||||
// One guard for both: a concurrent query with another shallow set resets `nodes`.
|
||||
let mut guard = lock(shared);
|
||||
let ids = guard.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
|
||||
let sorted = sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &guard.nodes)?;
|
||||
drop(guard);
|
||||
Box::new(sorted.into_iter().map(Ok))
|
||||
} else if repo.is_shallow().unwrap_or(false) || q.request.is_some() {
|
||||
// The process can be interrupted even during indegree preparation. Git also
|
||||
// respects shallow boundaries while retaining a topological order.
|
||||
@@ -866,7 +884,7 @@ fn log_indexed_rows(
|
||||
LogOrder::Topo | LogOrder::Standard => topo::Sorting::TopoOrder,
|
||||
LogOrder::Date => topo::Sorting::DateOrder,
|
||||
};
|
||||
let topo = topo::Builder::from_iters(&repo.objects, tips, None::<Vec<ObjectId>>)
|
||||
let topo = topo::Builder::from_iters(&repo.objects, tips.clone(), None::<Vec<ObjectId>>)
|
||||
.sorting(sorting)
|
||||
.parents(if q.first_parent { Parents::First } else { Parents::All })
|
||||
.with_commit_graph(graph)
|
||||
@@ -876,11 +894,20 @@ fn log_indexed_rows(
|
||||
};
|
||||
let walk: Walk<'_> = if q.order == LogOrder::Standard {
|
||||
let ids = walk.collect::<IdeResult<Vec<_>>>()?;
|
||||
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
|
||||
Box::new(sort_shared(&repo, ids, q, &shallow, cancel, shared)?.into_iter().map(Ok))
|
||||
} else {
|
||||
walk
|
||||
};
|
||||
let text = q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten();
|
||||
let mut guard = lock(shared);
|
||||
let index = &mut *guard;
|
||||
// Under the guard that builds the rows: a query run meanwhile (after a branch switch)
|
||||
// may have moved the shared set to another HEAD.
|
||||
update_head_reachable(&repo, index, cancel)?;
|
||||
// A query started before a shallow change may have reset `nodes` to its older set.
|
||||
if index.shallow != shallow {
|
||||
index.ensure_nodes(&repo, &tips, &shallow, cancel)?;
|
||||
}
|
||||
let db = index.db().cloned();
|
||||
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
|
||||
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
|
||||
@@ -952,6 +979,21 @@ fn log_indexed_rows(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sorts with the shared nodes only when they were built for this query's shallow set.
|
||||
fn sort_shared(
|
||||
repo: &gix::Repository,
|
||||
ids: Vec<ObjectId>,
|
||||
q: &LogQuery,
|
||||
shallow: &HashSet<ObjectId>,
|
||||
cancel: &CancellationToken,
|
||||
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
|
||||
) -> IdeResult<Vec<ObjectId>> {
|
||||
let guard = lock(shared);
|
||||
let empty = HashMap::new();
|
||||
let nodes = if &guard.shallow == shallow { &guard.nodes } else { &empty };
|
||||
sort_subset(repo, ids, q.order, q.first_parent, shallow, cancel, nodes)
|
||||
}
|
||||
|
||||
/// A ready-node stack gives incoming merge parents priority, while child counts
|
||||
/// prevent an ancestor shared with another branch from moving ahead of its children.
|
||||
fn sort_subset(
|
||||
|
||||
@@ -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,79 @@
|
||||
//! A long file history walk must not hold the log index while Git runs: commit details and
|
||||
//! one-commit queries (inline blame, the blame popup) share that index.
|
||||
#![cfg(unix)]
|
||||
|
||||
use ide_vcs::{LogQuery, Repo};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args([
|
||||
"-c",
|
||||
"init.defaultBranch=main",
|
||||
"-c",
|
||||
"user.name=T",
|
||||
"-c",
|
||||
"user.email=t@e",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn details_and_one_commit_queries_do_not_wait_for_a_file_history_walk() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("repo");
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
git(&dir, &["init", "-q"]);
|
||||
for i in 0..3 {
|
||||
std::fs::write(dir.join("file"), format!("{i}")).unwrap();
|
||||
git(&dir, &["add", "-A"]);
|
||||
git(&dir, &["commit", "-qm", &format!("c{i}")]);
|
||||
}
|
||||
// A git whose path-limited history walks take seconds.
|
||||
let real = String::from_utf8(Command::new("sh").args(["-c", "command -v git"]).output().unwrap().stdout).unwrap();
|
||||
let started = tmp.path().join("walk-started");
|
||||
let wrapper = tmp.path().join("slow-git");
|
||||
std::fs::write(
|
||||
&wrapper,
|
||||
format!(
|
||||
"#!/bin/sh\ncase \" $* \" in *\" --full-history \"*) : > '{}'; sleep 3;; esac\nexec '{}' \"$@\"\n",
|
||||
started.display(),
|
||||
real.trim()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let repo = Repo::discover(&dir).unwrap().unwrap();
|
||||
repo.set_execution_allowed(true);
|
||||
repo.set_git_executable(Some(&wrapper));
|
||||
std::thread::scope(|scope| {
|
||||
let walk = scope.spawn(|| {
|
||||
repo.log(&LogQuery { path: Some("file".into()), follow: true, ..Default::default() }).unwrap().len()
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
while !started.exists() {
|
||||
assert!(Instant::now() < deadline, "the history walk never started");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let asked = Instant::now();
|
||||
let details = repo.log_details("HEAD").unwrap();
|
||||
let head = repo.log(&LogQuery { branch: Some("HEAD".into()), limit: 1, ..Default::default() }).unwrap();
|
||||
let waited = asked.elapsed();
|
||||
println!("queries waited {waited:?}");
|
||||
assert_eq!(details.message, "c2");
|
||||
assert_eq!(head.len(), 1);
|
||||
assert!(!walk.is_finished(), "the walk ended before the queries ran; the test proves nothing");
|
||||
assert!(waited < Duration::from_secs(2), "queries waited {waited:?} for the walk");
|
||||
assert_eq!(walk.join().unwrap(), 3);
|
||||
});
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -57,6 +57,16 @@ Open the folder that contains `buildServer.json` (or `.bsp/`) as the project, or
|
||||
|
||||
<Tip>`buildServer.json` holds absolute paths for your machine. Add it to `.gitignore` instead of committing it.</Tip>
|
||||
|
||||
**Clean Build Folder** (**Build › Xcode**, Find Action, or right-click the `.xcodeproj` / `.xcworkspace`) runs `xcodebuild clean` for the selected Xcode scheme in the Run tool window, with the same flags a run uses. **Delete DerivedData** moves this project's DerivedData folder (the one `xcodebuild -showBuildSettings` reports, plus the IDE's own run builds) to the Trash after asking, then restarts sourcekit-lsp. Other projects' DerivedData is left alone.
|
||||
|
||||
### New files in Xcode projects
|
||||
|
||||
`xcodebuild` compiles only the files a target lists, and the IDE does not edit `project.pbxproj`. What happens to a source file you create, rename or delete depends on how the project lists its files:
|
||||
|
||||
- **Synchronized folders** (Xcode 16 and newer): files in a folder shown with a blue folder icon in Xcode's navigator belong to the folder's targets as soon as they are on disk. To turn a classic group into one, right-click it in Xcode and choose **Convert to Folder**. New Xcode 16 projects use synchronized folders.
|
||||
- **Classic groups**: a new file must be added to a target in Xcode (**File › Add Files to…**, or drag it into the group). When a new `.swift`, `.m`, `.h` or other source file isn't named in `project.pbxproj`, the IDE says so, with **Open in Xcode**.
|
||||
- **[XcodeGen](https://github.com/yonaskolb/XcodeGen) (`project.yml`) and [Tuist](https://tuist.dev) (`Project.swift`)**: the project is generated from the spec, so after files change the IDE offers to regenerate it (`xcodegen generate` or `tuist generate --no-open`) in the Run tool window. **Regenerate Xcode Project** in **Find Action** (`⌘⇧A` / `Ctrl+Shift+A`), or in the context menu of `project.yml` and `Project.swift`, runs it any time.
|
||||
|
||||
### Several Xcode versions
|
||||
|
||||
To run sourcekit-lsp from a specific Xcode, set `DEVELOPER_DIR` in the server's environment: in **Settings › Languages & Frameworks › Language Servers**, select sourcekit-lsp and add it under **Startup › Environment variables**, or in `settings.toml`:
|
||||
@@ -80,30 +90,27 @@ A `.swift` file can be run with **Run Context Configuration** (`⌃⇧R` / `Ctrl
|
||||
|
||||
### SwiftPM packages
|
||||
|
||||
There are no SwiftPM run or test configurations yet. Run `swift build`, `swift run` and `swift test` in the terminal, or create a **Shell Script** configuration for them (see [Run configurations](/en/guide/run)).
|
||||
Each executable product in `Package.swift` gets a **swift run <product>** run configuration. Its before launch task runs `swift build --product <product>`, then **Run** starts `swift run --skip-build <product>` in the package folder. Tests under `Tests/` get gutter icons that run `swift test --filter`.
|
||||
|
||||
### Xcode schemes
|
||||
|
||||
Each scheme of a `.xcodeproj` or `.xcworkspace` in the project root gets an **Xcode App** run configuration, with the scheme's launch arguments and environment variables. Run builds the scheme with `xcodebuild` and then:
|
||||
|
||||
- **iOS apps** are installed and launched on the simulator chosen in the toolbar, or on the one the configuration's **Simulator** field pins.
|
||||
- **macOS apps** are built with `-destination 'platform=macOS'`, and the app's executable (`<App>.app/Contents/MacOS/<App>`) runs directly: its output shows in the Run console, and **Stop** quits it. No simulator is booted.
|
||||
- **Apps that support both** run on the simulator. Set **Simulator** to `macos` to run them on the Mac instead.
|
||||
|
||||
### Debugging
|
||||
|
||||
Debugging uses lldb-dap. On macOS the IDE finds Xcode's copy through `xcrun -f lldb-dap`; elsewhere it comes with the Swift toolchain on `PATH`. To debug a SwiftPM executable:
|
||||
Debugging uses lldb-dap. On macOS the IDE finds Xcode's copy through `xcrun -f lldb-dap`; elsewhere it comes with the Swift toolchain on `PATH`.
|
||||
|
||||
<Steps>
|
||||
<Step title="Build it">
|
||||
Run `swift build`. The executable is written to `.build/debug/<product>`.
|
||||
</Step>
|
||||
<Step title="Create a Program configuration">
|
||||
In **Run › Edit Configurations…**, add a **Program** configuration with **Executable** set to
|
||||
`.build/debug/<product>` and **Debug adapter** set to **lldb-dap (C, C++, Swift)**.
|
||||
</Step>
|
||||
<Step title="Debug">
|
||||
Start it with **Debug** (`⌃D` / `Shift+F9`).
|
||||
</Step>
|
||||
</Steps>
|
||||
Start a **swift run <product>** configuration with **Debug** (`⌃D` / `Shift+F9`). The before launch task builds the product as for **Run**, the IDE asks `swift build --show-bin-path` where it was written (with the configuration's build options, such as `-c release`), and lldb-dap launches it with the configuration's arguments, environment and working folder. Program output goes to the **Debug** console. Debugging `swift test` runs is not supported yet.
|
||||
|
||||
Rebuild with `swift build` after editing, as the configuration does not build first. **Attach to Process…** also attaches to a running Swift program with lldb-dap when CodeLLDB is not installed. See [Debugging](/en/guide/debugging) for breakpoints, stepping and the variables view.
|
||||
To debug another Swift executable, add a **Program** configuration with **Executable** set to its path and **Debug adapter** set to **lldb-dap (C, C++, Swift)**. **Attach to Process…** also attaches to a running Swift program with lldb-dap when CodeLLDB is not installed. See [Debugging](/en/guide/debugging) for breakpoints, stepping and the variables view.
|
||||
|
||||
## Limitations
|
||||
|
||||
- There are no run, test or debug configurations for SwiftPM targets or Xcode schemes, and no test tree for XCTest or Swift Testing.
|
||||
- `swift test` runs cannot be debugged yet.
|
||||
- Xcode projects need a `buildServer.json` that you generate yourself (see [Xcode projects](#xcode-projects)).
|
||||
- **Expand Macro** does nothing: sourcekit-lsp shows the expansion in a new document, which the IDE does not open yet.
|
||||
- There is no SwiftUI Preview, Interface Builder, asset catalog editor or simulator integration. Use Xcode for those.
|
||||
|
||||
@@ -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 对应的文件夹,默认为项目根目录。
|
||||
|
||||
@@ -57,6 +57,16 @@ sourcekit-lsp 读不了 `.xcodeproj` 和 `.xcworkspace`。没有构建服务器
|
||||
|
||||
<Tip>`buildServer.json` 里是本机的绝对路径。把它加入 `.gitignore`,不要提交。</Tip>
|
||||
|
||||
**清理构建文件夹**(**构建 › Xcode**、Find Action,或在 `.xcodeproj` / `.xcworkspace` 上右键)会在 Run 工具窗口中对所选 Xcode scheme 运行 `xcodebuild clean`,参数与运行时相同。**删除 DerivedData** 会先询问,再把本项目的 DerivedData 文件夹(`xcodebuild -showBuildSettings` 报告的那个,以及 IDE 自己运行时的构建)移到废纸篓,然后重启 sourcekit-lsp。其他项目的 DerivedData 不受影响。
|
||||
|
||||
### Xcode 项目中的新文件
|
||||
|
||||
`xcodebuild` 只编译 target 中列出的文件,而 IDE 不会修改 `project.pbxproj`。新建、重命名或删除的源文件会怎样,取决于项目如何列出文件:
|
||||
|
||||
- **同步文件夹**(Xcode 16 及以上):在 Xcode 导航器中显示为蓝色文件夹图标的文件夹,其中的文件一写入磁盘就属于该文件夹的 target。要把传统的组转换成同步文件夹,在 Xcode 中右键点击它并选择 **Convert to Folder**。Xcode 16 新建的项目默认使用同步文件夹。
|
||||
- **传统的组**:新文件需要在 Xcode 中加入 target(**File › Add Files to…**,或拖进对应的组)。新建的 `.swift`、`.m`、`.h` 等源文件没有出现在 `project.pbxproj` 中时,IDE 会提示,并提供 **在 Xcode 中打开**。
|
||||
- **[XcodeGen](https://github.com/yonaskolb/XcodeGen)(`project.yml`)和 [Tuist](https://tuist.dev)(`Project.swift`)**:项目由配置文件生成,所以文件变更后 IDE 会提示重新生成(`xcodegen generate` 或 `tuist generate --no-open`),在运行工具窗口中执行。也可以随时通过 **查找操作**(`⌘⇧A` / `Ctrl+Shift+A`)或 `project.yml`、`Project.swift` 的右键菜单中的 **重新生成 Xcode 项目** 来运行。
|
||||
|
||||
### 多个 Xcode 版本
|
||||
|
||||
要让 sourcekit-lsp 使用某个特定的 Xcode,在服务器的环境中设置 `DEVELOPER_DIR`:在 **设置 › 语言和框架 › 语言服务器** 中选中 sourcekit-lsp,在 **启动 › 环境变量** 中添加;或者写在 `settings.toml` 中:
|
||||
@@ -80,30 +90,27 @@ env = { DEVELOPER_DIR = "/Applications/Xcode-beta.app/Contents/Developer" }
|
||||
|
||||
### SwiftPM 包
|
||||
|
||||
目前还没有 SwiftPM 的运行或测试配置。在终端里执行 `swift build`、`swift run` 和 `swift test`,或者为它们新建 **Shell 脚本** 配置(见[运行配置](/zh/guide/run))。
|
||||
`Package.swift` 中的每个可执行产品都有一个 **swift run <product>** 运行配置。它的启动前任务执行 `swift build --product <product>`,然后 **运行** 在包所在文件夹中启动 `swift run --skip-build <product>`。`Tests/` 下的测试有装订区图标,点击执行 `swift test --filter`。
|
||||
|
||||
### Xcode scheme
|
||||
|
||||
项目根目录下 `.xcodeproj` 或 `.xcworkspace` 的每个 scheme 都会生成一个 **Xcode App** 运行配置,带上 scheme 的启动参数和环境变量。运行时先用 `xcodebuild` 构建 scheme,然后:
|
||||
|
||||
- **iOS App** 安装到工具栏选中的模拟器上启动,或者装到配置的 **模拟器** 字段固定的模拟器上。
|
||||
- **macOS App** 用 `-destination 'platform=macOS'` 构建,然后直接运行 App 的可执行文件(`<App>.app/Contents/MacOS/<App>`):输出显示在运行控制台里,**停止** 会退出 App。不会启动模拟器。
|
||||
- **同时支持两者的 App** 在模拟器上运行。把 **模拟器** 设为 `macos` 就改在 Mac 上运行。
|
||||
|
||||
### 调试
|
||||
|
||||
调试使用 lldb-dap。在 macOS 上,IDE 通过 `xcrun -f lldb-dap` 找到 Xcode 中的副本;其他平台使用 `PATH` 上 Swift 工具链自带的副本。调试一个 SwiftPM 可执行程序:
|
||||
调试使用 lldb-dap。在 macOS 上,IDE 通过 `xcrun -f lldb-dap` 找到 Xcode 中的副本;其他平台使用 `PATH` 上 Swift 工具链自带的副本。
|
||||
|
||||
<Steps>
|
||||
<Step title="构建">
|
||||
执行 `swift build`,可执行文件会写到 `.build/debug/<product>`。
|
||||
</Step>
|
||||
<Step title="新建程序配置">
|
||||
在 **运行 › 编辑配置…** 中添加一个 **程序** 配置,把 **可执行文件** 设为 `.build/debug/<product>`,**调试适配器** 设为
|
||||
**lldb-dap (C, C++, Swift)**。
|
||||
</Step>
|
||||
<Step title="调试">
|
||||
用 **调试**(`⌃D` / `Shift+F9`)启动。
|
||||
</Step>
|
||||
</Steps>
|
||||
用 **调试**(`⌃D` / `Shift+F9`)启动 **swift run <product>** 配置。启动前任务像 **运行** 一样构建产品,IDE 用 `swift build --show-bin-path`(带上配置中的构建选项,例如 `-c release`)找到产物所在位置,再由 lldb-dap 按配置的参数、环境变量和工作目录启动它。程序输出显示在 **调试** 控制台中。目前还不能调试 `swift test`。
|
||||
|
||||
这个配置不会先构建,修改代码后要重新执行 `swift build`。未安装 CodeLLDB 时,**附加到进程…** 也会用 lldb-dap 附加到正在运行的 Swift 程序。断点、单步和变量视图见[调试](/zh/guide/debugging)。
|
||||
要调试其他 Swift 可执行文件,添加一个 **程序** 配置,把 **可执行文件** 设为它的路径,**调试适配器** 设为 **lldb-dap (C, C++, Swift)**。未安装 CodeLLDB 时,**附加到进程…** 也会用 lldb-dap 附加到正在运行的 Swift 程序。断点、单步和变量视图见[调试](/zh/guide/debugging)。
|
||||
|
||||
## 限制
|
||||
|
||||
- 还没有针对 SwiftPM 目标或 Xcode scheme 的运行、测试和调试配置,也没有 XCTest 或 Swift Testing 的测试树。
|
||||
- 还不能调试 `swift test`。
|
||||
- Xcode 项目需要你自己生成 `buildServer.json`(见 [Xcode 项目](#xcode-项目))。
|
||||
- **Expand Macro** 不起作用:sourcekit-lsp 会在新文档中显示展开结果,而 IDE 目前还不会打开它。
|
||||
- 没有 SwiftUI 预览、Interface Builder、资源目录编辑器和模拟器集成,这些请使用 Xcode。
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Loaded 100 of 215 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача