дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 05:22:23 +02:00
Порівняти коміти
43
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
2e5d7c0c79 | ||
|
|
3beadbcf63 | ||
|
|
ac58b3380b | ||
|
|
c9bf8a3502 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a | ||
|
|
3240164840 | ||
|
|
f70f362a3d | ||
|
|
806bb4c78d | ||
|
|
57094bc285 | ||
|
|
a5e0c41663 | ||
|
|
77071238a0 | ||
|
|
64097d3c20 | ||
|
|
cf0e57e5df | ||
|
|
703cf23296 | ||
|
|
a88073d6fb | ||
|
|
4b5745c1b6 | ||
|
|
4667c81e6b | ||
|
|
cea9d863f9 | ||
|
|
5fa953eddd | ||
|
|
031f1acd07 | ||
|
|
add23fe97f | ||
|
|
3d2b0946de | ||
|
|
6c7282b442 | ||
|
|
1f79a7f805 | ||
|
|
3d1eaf71e4 | ||
|
|
138209c627 | ||
|
|
b283d352b7 | ||
|
|
f7f9dabe2b | ||
|
|
787d4fbcfa |
No files matched your search
@@ -30,7 +30,7 @@ jobs:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
@@ -111,9 +111,10 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-latest, windows-latest]
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
# Self-hosted runners (scripts/selfhost-runner for Linux, a Mac with the macOS/ARM64 labels) only
|
||||
# for trusted events, and only while the SELFHOSTED_RUNNERS repository variable is 'true':
|
||||
# runs-on cannot fall back when none is online. Windows always runs GitHub-hosted.
|
||||
runs-on: ${{ matrix.os != 'windows-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && (matrix.os == 'macos-latest' && fromJSON('["self-hosted", "macOS", "ARM64"]') || fromJSON('["self-hosted", "openidea-selfhosted"]')) || matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
@@ -137,6 +138,12 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
# The Linux runner containers set CARGO_TARGET_DIR; elsewhere keep it next to the checkout,
|
||||
# which actions/checkout cleans on every run.
|
||||
if [ -z "${CARGO_TARGET_DIR:-}" ]; then
|
||||
CARGO_TARGET_DIR="$(dirname "$RUNNER_WORKSPACE")/cargo-target"
|
||||
echo "CARGO_TARGET_DIR=$CARGO_TARGET_DIR" >> "$GITHUB_ENV"
|
||||
fi
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
@@ -216,7 +223,7 @@ jobs:
|
||||
name: Rust checks
|
||||
needs: [changes, rust]
|
||||
if: always()
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- env:
|
||||
@@ -327,7 +334,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.deny == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
@@ -339,7 +346,8 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.frontend == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
# Chromium and vitest need more CPU than the light runners have; GitHub-hosted runners are faster here.
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
|
||||
@@ -366,7 +374,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.catalog == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
@@ -384,7 +392,8 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
timeout-minutes: 45
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
# Chromium and vitest need more CPU than the light runners have; GitHub-hosted runners are faster here.
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
|
||||
@@ -3,7 +3,8 @@ name: Homebrew
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
|
||||
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
|
||||
# l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -27,17 +28,17 @@ jobs:
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and token
|
||||
- name: Check tag and deploy key
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
|
||||
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
@@ -47,7 +48,7 @@ jobs:
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
|
||||
@@ -179,7 +179,7 @@ jobs:
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
|
||||
Створено
+48
-49
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4182,7 +4182,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4205,7 +4205,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4223,7 +4223,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4248,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4259,7 +4259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4281,7 +4281,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4294,7 +4294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4323,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4362,7 +4362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4375,7 +4375,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4389,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4409,7 +4409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4420,7 +4420,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4432,7 +4432,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4440,12 +4440,11 @@ dependencies = [
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tracing",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4464,7 +4463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4545,7 +4544,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4564,7 +4563,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4587,7 +4586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4599,7 +4598,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4615,7 +4614,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4624,7 +4623,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4635,7 +4634,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4694,7 +4693,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4723,7 +4722,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4742,7 +4741,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4763,7 +4762,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4785,7 +4784,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4799,7 +4798,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4819,7 +4818,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4844,7 +4843,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4860,7 +4859,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4886,7 +4885,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4907,7 +4906,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4920,7 +4919,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4945,7 +4944,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4958,7 +4957,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4973,7 +4972,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4987,7 +4986,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -5000,7 +4999,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -5023,7 +5022,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5045,7 +5044,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5072,7 +5071,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5088,7 +5087,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6727,7 +6726,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
let retry = run_once(shared, spec, true, model).await;
|
||||
|
||||
@@ -283,6 +283,20 @@ impl AgentCatalogs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
|
||||
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
|
||||
let key = Self::key(shared, provider);
|
||||
let mut state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get_mut(&key)
|
||||
&& entry.flight.is_none()
|
||||
&& entry.error.is_some()
|
||||
{
|
||||
entry.completed = None;
|
||||
entry.retry_at_ms = None;
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
|
||||
@@ -33,6 +33,7 @@ pub use catalogs::AgentCatalogs;
|
||||
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
|
||||
pub use external::ExternalSession;
|
||||
pub use model::*;
|
||||
pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch};
|
||||
pub use skill_installer::{
|
||||
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
|
||||
SkillScanWarning, SkillScanWarningKind,
|
||||
@@ -53,6 +54,49 @@ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Resolves agent `id`'s interactive sign-in command without an open project.
|
||||
pub fn login_launch_without_project(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
cwd: &Path,
|
||||
id: &str,
|
||||
) -> IdeResult<LoginLaunch> {
|
||||
let spec = provider::load(custom_agents_dir, secrets)
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
spec.login_launch(cwd, None)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status_with(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
cwd: &Path,
|
||||
) -> CopilotAuthStatus {
|
||||
let copilot_spec = provider::load(custom_agents_dir, secrets).into_iter().find(|p| p.id == "copilot");
|
||||
let cwd_buf = cwd.to_path_buf();
|
||||
let cli_fut = async move {
|
||||
let spec = copilot_spec?;
|
||||
native::copilot::probe_auth_status(spec, cwd_buf).await
|
||||
};
|
||||
let gh_fut = tokio::task::spawn_blocking(provider::gh_authenticated_accounts);
|
||||
let (cli, gh) = tokio::join!(cli_fut, gh_fut);
|
||||
let (gh_installed, gh_accounts) = gh.unwrap_or((false, Vec::new()));
|
||||
match cli {
|
||||
Some(cli) => CopilotAuthStatus {
|
||||
authenticated: cli.authenticated,
|
||||
login: cli.login,
|
||||
auth_type: cli.auth_type,
|
||||
status_message: cli.status_message,
|
||||
gh_installed,
|
||||
gh_accounts,
|
||||
},
|
||||
None => CopilotAuthStatus { gh_installed, gh_accounts, ..CopilotAuthStatus::default() },
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives the events of one project's tasks.
|
||||
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
|
||||
|
||||
@@ -201,6 +245,8 @@ struct Shared {
|
||||
providers: RwLock<Vec<provider::ProviderSpec>>,
|
||||
/// Last probe of each provider.
|
||||
probes: Mutex<HashMap<String, AgentProbe>>,
|
||||
/// `type: "terminal"` login arguments reported during `initialize`, by provider id.
|
||||
terminal_auth_args: RwLock<HashMap<String, Vec<String>>>,
|
||||
/// Copilot CLI installs where `--headless` failed and fell back to `--acp`.
|
||||
copilot_acp_fallback: Mutex<HashSet<CopilotBinaryKey>>,
|
||||
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
|
||||
@@ -706,6 +752,7 @@ impl AgentManager {
|
||||
known,
|
||||
providers,
|
||||
probes: Mutex::new(HashMap::new()),
|
||||
terminal_auth_args: RwLock::new(HashMap::new()),
|
||||
copilot_acp_fallback: Mutex::new(HashSet::new()),
|
||||
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
|
||||
mcp_servers_hook: RwLock::new(None),
|
||||
@@ -785,16 +832,24 @@ impl AgentManager {
|
||||
*self.shared.git_executable.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// Directory holding linked Git worktrees created for agent tasks of this project.
|
||||
pub fn worktrees_dir(&self) -> &Path {
|
||||
&self.shared.paths.worktrees_dir
|
||||
}
|
||||
|
||||
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
|
||||
pub fn providers(&self) -> Vec<AgentProvider> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let in_use: std::collections::HashSet<String> =
|
||||
self.tasks.read().values().map(|t| t.state.lock().task.provider.clone()).collect();
|
||||
let terminal_auth = self.shared.terminal_auth_args.read();
|
||||
let list = specs
|
||||
.iter()
|
||||
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
|
||||
.map(|p| {
|
||||
let mut info = provider::describe(p);
|
||||
info.can_sign_in =
|
||||
p.can_sign_in(&self.shared.paths.project_root, terminal_auth.get(&p.id).map(Vec::as_slice));
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
|
||||
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
|
||||
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
|
||||
@@ -802,6 +857,7 @@ impl AgentManager {
|
||||
info
|
||||
})
|
||||
.collect();
|
||||
drop(terminal_auth);
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
@@ -815,6 +871,35 @@ impl AgentManager {
|
||||
list
|
||||
}
|
||||
|
||||
/// Resolves the interactive sign-in command for agent `id`.
|
||||
pub fn login_launch(&self, id: &str) -> IdeResult<LoginLaunch> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let spec = specs
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
let terminal_args = self.shared.terminal_auth_args.read().get(id).cloned();
|
||||
let launch = spec.login_launch(&self.shared.paths.project_root, terminal_args.as_deref()).ok_or_else(|| {
|
||||
IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))
|
||||
})?;
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, id);
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status(&self) -> CopilotAuthStatus {
|
||||
let status = copilot_auth_status_with(
|
||||
self.shared.paths.custom_agents_dir.as_deref(),
|
||||
self.shared.env_secrets(),
|
||||
&self.shared.paths.project_root,
|
||||
)
|
||||
.await;
|
||||
if status.authenticated || !status.gh_accounts.is_empty() {
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, "copilot");
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
|
||||
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
|
||||
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
|
||||
@@ -837,7 +922,9 @@ impl AgentManager {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)?;
|
||||
self.shared.paths.catalogs.evict_if_idle(&self.shared, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
@@ -3509,6 +3596,14 @@ impl Task {
|
||||
let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message));
|
||||
SessionOpenError { message: self.describe(e), allow_acp_fallback: !is_auth }
|
||||
})?;
|
||||
if let Some(args) = init.auth_methods.iter().find_map(|method| {
|
||||
if method.get("type").and_then(Value::as_str) != Some("terminal") {
|
||||
return None;
|
||||
}
|
||||
method.get("args")?.as_array()?.iter().map(|v| v.as_str().map(str::to_owned)).collect::<Option<Vec<_>>>()
|
||||
}) {
|
||||
self.shared.terminal_auth_args.write().insert(provider_id.to_owned(), args);
|
||||
}
|
||||
let sign_in_message = spec.sign_in_message(&init.auth_methods);
|
||||
let can_load = init.load_session();
|
||||
let (capabilities, embedded) = capabilities_of(&init);
|
||||
|
||||
@@ -623,6 +623,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
@@ -647,6 +650,34 @@ pub enum AgentCommandReadOnlyReason {
|
||||
CustomAgent,
|
||||
}
|
||||
|
||||
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhAuthAccount {
|
||||
pub login: String,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CopilotAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
pub gh_installed: bool,
|
||||
pub gh_accounts: Vec<GhAuthAccount>,
|
||||
}
|
||||
|
||||
/// Output and completion of an interactive sign-in PTY started by the IDE.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum AgentLoginEvent {
|
||||
Output { data: String },
|
||||
Exited { code: Option<i32> },
|
||||
}
|
||||
|
||||
/// Where an agent comes from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
|
||||
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
|
||||
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
@@ -185,6 +185,78 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
|
||||
res
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct CliAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
}
|
||||
|
||||
/// Queries `auth.getStatus` on Copilot's headless server (ignoring any IDE-selected `gh`
|
||||
/// account override so the UI can show what the "Default" account resolves to).
|
||||
pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> Option<CliAuthStatus> {
|
||||
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
|
||||
if !prefer_stored
|
||||
&& has_ambient
|
||||
&& first.as_ref().is_none_or(|s| !s.authenticated)
|
||||
&& let Some(retry) = probe_auth_once(spec, cwd, true).await
|
||||
{
|
||||
if retry.authenticated {
|
||||
crate::provider::mark_prefer_stored_copilot_auth();
|
||||
}
|
||||
return Some(retry);
|
||||
}
|
||||
first
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn probe_auth_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> Option<CliAuthStatus> {
|
||||
let launch = tokio::task::spawn_blocking({
|
||||
let cwd = cwd.clone();
|
||||
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
&launch.command,
|
||||
&args,
|
||||
&cwd,
|
||||
&launch.env,
|
||||
Arc::new(ide_jsonrpc::NoopHandler),
|
||||
Box::new(|_| {}),
|
||||
Framing::ContentLength,
|
||||
)
|
||||
.ok()?;
|
||||
let res = async {
|
||||
handshake(&peer).await.ok()?;
|
||||
let auth: Value = peer.request("auth.getStatus", json!({}), None).await.ok()?;
|
||||
let authenticated = auth.get("isAuthenticated").and_then(Value::as_bool).unwrap_or(false);
|
||||
let str_field = |key: &str| {
|
||||
auth.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
|
||||
};
|
||||
Some(CliAuthStatus {
|
||||
authenticated,
|
||||
login: str_field("login"),
|
||||
auth_type: str_field("authType"),
|
||||
status_message: str_field("statusMessage"),
|
||||
})
|
||||
}
|
||||
.await;
|
||||
peer.kill();
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn attach(
|
||||
client: Arc<dyn Handler>,
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
|
||||
//! Registry, see `registry`).
|
||||
|
||||
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
|
||||
use crate::{
|
||||
AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets,
|
||||
GhAuthAccount,
|
||||
};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -73,7 +76,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
"GitHub Copilot",
|
||||
Driver::Copilot,
|
||||
&["copilot", "--headless", "--no-auto-update", "--stdio"],
|
||||
"Run `copilot` in a terminal and sign in.",
|
||||
"Run `copilot login` in a terminal.",
|
||||
),
|
||||
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
|
||||
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
|
||||
@@ -151,12 +154,26 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
|
||||
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
} else if is_copilot
|
||||
&& !strip_ambient_tokens
|
||||
&& !explicit_copilot_token
|
||||
&& ide_core::project_env::github_token(cwd).is_some()
|
||||
&& let Some(default_token) = default_github_token()
|
||||
{
|
||||
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
|
||||
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
@@ -166,7 +183,7 @@ impl ProviderSpec {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
@@ -176,6 +193,80 @@ impl ProviderSpec {
|
||||
.into_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolves the executable, arguments, and environment to run this agent's interactive
|
||||
/// sign-in flow directly in an IDE PTY without shell quoting.
|
||||
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
|
||||
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
|
||||
let candidate =
|
||||
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
|
||||
if candidate.is_absolute() && is_executable(&candidate) {
|
||||
return Some(candidate);
|
||||
}
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
_ => None,
|
||||
} {
|
||||
let program = resolve_exe(separate_cmd, &self.env)?;
|
||||
return Some(LoginLaunch {
|
||||
program,
|
||||
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
|
||||
env: self.env.iter().cloned().collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
.or_else(|| builtin_login_args(&builtin))?;
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
}
|
||||
return Some(LoginLaunch { program, args, env });
|
||||
}
|
||||
|
||||
let args = terminal_auth_args?.to_vec();
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
|
||||
}
|
||||
|
||||
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
|
||||
self.login_launch(cwd, terminal_auth_args).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoginLaunch {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
|
||||
match rest {
|
||||
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
|
||||
let (args, _) = after_space.split_once('`')?;
|
||||
Some(args.split_whitespace().map(str::to_owned).collect())
|
||||
}
|
||||
Some(_) => Some(Vec::new()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
@@ -194,16 +285,15 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
let path = ide_core::process::shell_env()
|
||||
.find(|(name, _)| name == "PATH")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"));
|
||||
let program = path
|
||||
.as_deref()
|
||||
.and_then(|path| ide_core::process::find_executable("gh", path))
|
||||
let program = find_gh_executable()
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
@@ -229,6 +319,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE,
|
||||
/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run.
|
||||
pub fn gh_login_launch() -> IdeResult<LoginLaunch> {
|
||||
let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?;
|
||||
let mut env = BTreeMap::new();
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
Ok(LoginLaunch {
|
||||
program,
|
||||
args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()],
|
||||
env,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`,
|
||||
/// ignoring ambient token environment variables so keyring accounts remain visible.
|
||||
pub fn gh_authenticated_accounts() -> (bool, Vec<GhAuthAccount>) {
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return (false, Vec::new());
|
||||
};
|
||||
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
|
||||
let mut command = std::process::Command::new(&program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command
|
||||
.args(args)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1");
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
command.output().ok()
|
||||
};
|
||||
if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if let Some(accounts) = parse_gh_auth_status_json(&stdout) {
|
||||
return (true, accounts);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.contains("unknown flag: --json") {
|
||||
return (true, Vec::new());
|
||||
}
|
||||
}
|
||||
let fallback = run_gh(&["auth", "status", "--hostname", "github.com"])
|
||||
.map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
|
||||
.map(|text| parse_gh_auth_status_text(&text))
|
||||
.unwrap_or_default();
|
||||
(true, fallback)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
#[serde(default)]
|
||||
state: Option<String>,
|
||||
#[serde(default)]
|
||||
active: bool,
|
||||
#[serde(default)]
|
||||
login: String,
|
||||
#[serde(default)]
|
||||
token_source: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
#[serde(default)]
|
||||
hosts: BTreeMap<String, Vec<Entry>>,
|
||||
}
|
||||
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
if let Some(entries) = parsed.hosts.get("github.com") {
|
||||
for entry in entries {
|
||||
let login = entry.login.trim();
|
||||
if login.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if entry.state.as_deref().is_some_and(|s| s != "success") {
|
||||
continue;
|
||||
}
|
||||
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
|
||||
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
|
||||
existing.active |= entry.active;
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(accounts)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
let mut current: Option<usize> = None;
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
|
||||
let login = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
current = None;
|
||||
if !login.is_empty() && !rest.contains("_TOKEN") {
|
||||
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
|
||||
current = Some(idx);
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
|
||||
current = Some(accounts.len() - 1);
|
||||
}
|
||||
}
|
||||
} else if trimmed.starts_with("- Active account: true")
|
||||
&& let Some(idx) = current
|
||||
{
|
||||
accounts[idx].active = true;
|
||||
}
|
||||
}
|
||||
accounts
|
||||
}
|
||||
|
||||
fn default_github_token() -> Option<String> {
|
||||
let program = find_gh_executable()?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command.output().ok().filter(|out| out.status.success())?;
|
||||
let token = String::from_utf8(output.stdout).ok()?;
|
||||
let token = token.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -237,18 +461,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
|
||||
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
|
||||
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
|
||||
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
|
||||
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
|
||||
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
ide_core::process::shell_env()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
|
||||
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
|
||||
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
|
||||
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds child environment overrides for `copilot`:
|
||||
@@ -259,9 +482,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
|
||||
pub(crate) fn sanitized_copilot_env(
|
||||
spec_env: &[(String, String)],
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Vec<(String, String)> {
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_copilot_env_with(
|
||||
@@ -389,6 +613,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
@@ -901,6 +1126,22 @@ mod tests {
|
||||
assert_eq!(reset.env, custom.env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
|
||||
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
|
||||
for spec in builtins() {
|
||||
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
|
||||
continue;
|
||||
}
|
||||
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
|
||||
}
|
||||
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
|
||||
for spec in builtins() {
|
||||
@@ -1160,12 +1401,12 @@ mod tests {
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
@@ -1174,7 +1415,7 @@ mod tests {
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
@@ -1458,4 +1699,68 @@ mod tests {
|
||||
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
|
||||
let raw = r#"{
|
||||
"hosts": {
|
||||
"github.com": [
|
||||
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
|
||||
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
|
||||
],
|
||||
"ghe.example.com": [
|
||||
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_json(raw),
|
||||
Some(vec![
|
||||
GhAuthAccount { login: "alice".into(), active: true },
|
||||
GhAuthAccount { login: "alice-work".into(), active: false },
|
||||
])
|
||||
);
|
||||
|
||||
let text = "\
|
||||
github.com
|
||||
✓ Logged in to github.com account env_user (GH_TOKEN)
|
||||
- Active account: true
|
||||
✓ Logged in to github.com account alice (keyring)
|
||||
- Active account: false
|
||||
✓ Logged in to github.com account alice-work (keyring)
|
||||
- Active account: true
|
||||
";
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_text(text),
|
||||
vec![
|
||||
GhAuthAccount { login: "alice".into(), active: false },
|
||||
GhAuthAccount { login: "alice-work".into(), active: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app_support = dir.path().join("Application Support/copilot");
|
||||
std::fs::create_dir_all(&app_support).unwrap();
|
||||
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.command = bin.to_string_lossy().into_owned();
|
||||
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.args, ["login"]);
|
||||
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
}
|
||||
@@ -1212,7 +1212,7 @@ esac
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(spec.name, "GitHub Copilot");
|
||||
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
|
||||
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
|
||||
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
|
||||
|
||||
let mut providers = vec![provider::describe(&spec)];
|
||||
|
||||
@@ -486,6 +486,16 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// Java: organize imports switches to a wildcard import once this many
|
||||
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
/// 5; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub class_count_to_use_import_with_star: Option<u32>,
|
||||
/// Java: organize imports switches to a wildcard static import once this
|
||||
/// many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
/// IDEA's default 3; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub names_count_to_use_static_import_with_star: Option<u32>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
@@ -552,6 +562,25 @@ pub struct EncodingSettings {
|
||||
pub native_to_ascii: bool,
|
||||
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
|
||||
pub utf8_bom: String,
|
||||
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
/// relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
#[serde(deserialize_with = "labels")]
|
||||
#[specta(type = BTreeMap<String, String>)]
|
||||
pub mappings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
|
||||
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter_map(|(path, label)| match label {
|
||||
serde_json::Value::String(label) => Some((path, label)),
|
||||
_ => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Default for EncodingSettings {
|
||||
@@ -562,10 +591,30 @@ impl Default for EncodingSettings {
|
||||
properties: "iso-8859-1".into(),
|
||||
native_to_ascii: false,
|
||||
utf8_bom: "never".into(),
|
||||
mappings: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod encoding_mappings_tests {
|
||||
use super::EncodingSettings;
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_keep_the_entries_that_are_labels() {
|
||||
let json = serde_json::json!({
|
||||
"project": "gbk",
|
||||
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
|
||||
});
|
||||
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(settings.project, "gbk");
|
||||
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
|
||||
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
|
||||
assert!(not_a_table.mappings.is_empty());
|
||||
assert!(EncodingSettings::default().mappings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod auto_import_tests {
|
||||
use super::{AutoImportSettings, ImportsOnPaste};
|
||||
|
||||
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
|
||||
|
||||
struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
changes: Changes,
|
||||
loading: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(root: PathBuf) -> Self {
|
||||
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
|
||||
if let Some(token) = &self.github_token {
|
||||
combined.push(("GH_TOKEN".into(), Some(token.clone())));
|
||||
}
|
||||
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
|
||||
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
|
||||
combined.extend(self.direnv.iter().cloned());
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
|
||||
static SETTLED: Condvar = Condvar::new();
|
||||
|
||||
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
|
||||
let mut entries = entries();
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => entry.loading = true,
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
|
||||
None => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.loading = true;
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What children started in `root` (or below it) get on top of the IDE's own environment
|
||||
/// (`None`: removed). Ends a [`begin_loading`].
|
||||
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
|
||||
/// environment (`None`: removed). Ends a [`begin_loading`].
|
||||
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
|
||||
let mut entries = entries();
|
||||
let changes = Arc::new(changes);
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => {
|
||||
entry.changes = changes;
|
||||
match entries.iter_mut().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv = changes;
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
|
||||
None if !changes.is_empty() => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.direnv = changes;
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
|
||||
pub fn settle(root: &Path) {
|
||||
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
|
||||
entry.loading = false;
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
entries[idx].loading = false;
|
||||
if entries[idx].is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// `root` has no environment of its own any more (closed, or not trusted).
|
||||
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
|
||||
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
|
||||
pub fn remove(root: &Path) {
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv.clear();
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
|
||||
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
|
||||
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
let token = token.filter(|t| !t.is_empty());
|
||||
let mut entries = entries();
|
||||
match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
if entries[idx].github_token == token {
|
||||
return false;
|
||||
}
|
||||
let entry = &mut entries[idx];
|
||||
entry.github_token = token;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let Some(token) = token else { return false };
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.github_token = Some(token);
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
|
||||
pub fn github_token(dir: &Path) -> Option<OsString> {
|
||||
find(&entries(), dir).and_then(|e| e.github_token.clone())
|
||||
}
|
||||
|
||||
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
|
||||
pub fn remove_all(root: &Path) {
|
||||
entries().retain(|e| e.root != root);
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
@@ -135,4 +226,26 @@ mod tests {
|
||||
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
|
||||
remove(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
|
||||
let root = Path::new("/openidea-test-env/gh-project");
|
||||
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
|
||||
assert!(set_github_token(root, Some("gho_work".into())));
|
||||
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
|
||||
assert!(set_github_token(worktrees, Some("gho_work".into())));
|
||||
remove(root); // no `.envrc` in `root`
|
||||
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
|
||||
|
||||
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
|
||||
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
|
||||
remove_all(root);
|
||||
remove_all(worktrees);
|
||||
assert!(for_dir(root).is_empty());
|
||||
assert!(for_dir(worktrees).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
|
||||
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
|
||||
/// only when installed, then the user's `PATH`), and standard OS install locations.
|
||||
pub fn find_gh_executable() -> Option<PathBuf> {
|
||||
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
|
||||
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
|
||||
}
|
||||
|
||||
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
|
||||
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
|
||||
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
|
||||
return Some(explicit);
|
||||
}
|
||||
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
|
||||
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
|
||||
return Some(explicit.to_path_buf());
|
||||
}
|
||||
if let Some(found) = find_command("gh", search, Path::new("")) {
|
||||
return Some(found);
|
||||
}
|
||||
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else { return false };
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -25,6 +25,17 @@ pub struct VcsSettings {
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GithubSettings {
|
||||
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
|
||||
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
|
||||
pub account: String,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,4 +12,3 @@ serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
@@ -16,30 +16,15 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
/// API calls normally answer within a few seconds.
|
||||
const QUICK: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
|
||||
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
|
||||
/// install or remove a managed copy in its tools directory at runtime).
|
||||
pub fn gh_executable() -> Option<PathBuf> {
|
||||
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
GH.get_or_init(|| {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
if let Ok(found) = which::which("gh") {
|
||||
return Some(found);
|
||||
}
|
||||
let candidates: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
|
||||
})
|
||||
.clone()
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
|
||||
@@ -386,3 +371,37 @@ pub fn prepare_diff(
|
||||
let files = repo.diff_files(&base, head_oid)?;
|
||||
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let search = std::env::join_paths([&dir]).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
|
||||
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
|
||||
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
|
||||
|
||||
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
|
||||
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
|
||||
|
||||
std::fs::remove_file(&gh).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
//! Project-scoped GitHub CLI (`gh`) account selection and opt-in `GH_TOKEN` injection.
|
||||
//!
|
||||
//! Each project may pin a GitHub login in `vcs.github.account` (`.openidea/settings.toml`) or
|
||||
//! leave it empty (`Automatic`). `Automatic` leaves `gh`'s own behaviour untouched—no `GH_TOKEN`
|
||||
//! is injected into [`ide_core::project_env`] and opening a project makes no GitHub API calls.
|
||||
//! When the user inspects GitHub settings or Pull Requests with multiple `gh` keyring accounts,
|
||||
//! OpenIDEA probes the repository remote (`owner/repo`) to suggest a matching non-active account
|
||||
//! ("Use <login> for this project"). Only when an account is explicitly chosen does OpenIDEA
|
||||
//! resolve its token into [`ide_core::project_env`] (for both `project.root` and `.worktrees`).
|
||||
|
||||
use crate::Project;
|
||||
use ide_agent::GhAuthAccount;
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::LazyLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const AMBIENT_GH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
const GH_TOOL: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
|
||||
const LOCAL_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
|
||||
const CACHE_TTL: Duration = Duration::from_secs(10 * 60);
|
||||
|
||||
/// GitHub CLI accounts available on this machine and which one applies to the project.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhProjectAccountStatus {
|
||||
pub gh_installed: bool,
|
||||
pub accounts: Vec<GhAuthAccount>,
|
||||
/// Value of `vcs.github.account` (`""` = Automatic).
|
||||
pub configured_account: String,
|
||||
/// Account login currently used (`configured_account` if signed in, else `gh`'s active account).
|
||||
pub effective_account: Option<String>,
|
||||
/// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty.
|
||||
pub suggested_account: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedAutoAccount {
|
||||
login: Option<String>,
|
||||
at: Instant,
|
||||
}
|
||||
|
||||
type AutoCacheMap = HashMap<(String, Vec<String>), CachedAutoAccount>;
|
||||
static AUTO_CACHE: LazyLock<Mutex<AutoCacheMap>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub(crate) fn is_valid_github_login(login: &str) -> bool {
|
||||
let bytes = login.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn clean_gh_command(program: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.current_dir(std::env::temp_dir())
|
||||
.args(args)
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1")
|
||||
.env("CLICOLOR", "0");
|
||||
// Strip ambient tokens by setting empty then removing after `prepare`: `CliTool::run` calls
|
||||
// `ide_core::process::prepare`, which skips keys already present in `cmd.get_envs()`.
|
||||
for key in AMBIENT_GH_VARS {
|
||||
cmd.env_remove(key);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
fn gh_token_for_account(program: &Path, login: &str) -> Option<String> {
|
||||
if !is_valid_github_login(login) {
|
||||
return None;
|
||||
}
|
||||
let cmd = clean_gh_command(program, &["auth", "token", "--hostname", "github.com", "--user", login]);
|
||||
let out = GH_TOOL.run(cmd, LOCAL_TIMEOUT, None).ok().filter(|o| o.success)?;
|
||||
let token = out.stdout.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
/// Access level of an account for a specific `owner/repo` on `github.com`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum RepoAccess {
|
||||
None = 0,
|
||||
Read = 1,
|
||||
Push = 2,
|
||||
}
|
||||
|
||||
fn probe_repo_access(program: &Path, token: &str, owner: &str, name: &str) -> RepoAccess {
|
||||
let endpoint = format!("repos/{owner}/{name}");
|
||||
let mut cmd =
|
||||
clean_gh_command(program, &["api", "--hostname", "github.com", &endpoint, "--jq", ".permissions.push"]);
|
||||
cmd.env("GH_TOKEN", token);
|
||||
let Ok(out) = GH_TOOL.run(cmd, PROBE_TIMEOUT, None) else {
|
||||
return RepoAccess::None;
|
||||
};
|
||||
if !out.success {
|
||||
return RepoAccess::None;
|
||||
}
|
||||
if out.stdout.trim() == "true" { RepoAccess::Push } else { RepoAccess::Read }
|
||||
}
|
||||
|
||||
fn pick_best_account(candidates: &[(GhAuthAccount, RepoAccess)]) -> Option<(&GhAuthAccount, bool)> {
|
||||
let active_access =
|
||||
candidates.iter().find(|(a, _)| a.active).map(|(_, access)| *access).unwrap_or(RepoAccess::None);
|
||||
// Prefer higher RepoAccess; break ties in favor of the globally active account.
|
||||
let (best, best_access) = candidates.iter().max_by_key(|(acc, access)| (*access, acc.active))?;
|
||||
if *best_access == RepoAccess::None {
|
||||
// Nobody could reach the repo (offline or SSO required): keep the active account.
|
||||
return candidates.iter().find(|(a, _)| a.active).or_else(|| candidates.first()).map(|(a, _)| (a, false));
|
||||
}
|
||||
let auto_detected = !best.active && *best_access > active_access;
|
||||
Some((best, auto_detected))
|
||||
}
|
||||
|
||||
/// Parses `github.com` `(owner, repo)` from HTTPS, SSH, or SCP-style remote URLs.
|
||||
pub(crate) fn parse_github_owner_repo(url: &str) -> Option<(String, String)> {
|
||||
let url = url.trim();
|
||||
let path = if let Some(rest) =
|
||||
url.strip_prefix("https://github.com/").or_else(|| url.strip_prefix("http://github.com/"))
|
||||
{
|
||||
rest
|
||||
} else if let Some(rest) = url.strip_prefix("ssh://") {
|
||||
rest.strip_prefix("[email protected]/").or_else(|| rest.strip_prefix("github.com/"))?
|
||||
} else {
|
||||
url.strip_prefix("[email protected]:")?
|
||||
};
|
||||
let path = path.trim_matches('/');
|
||||
let (owner, rest) = path.split_once('/')?;
|
||||
let repo = rest.split('/').next()?;
|
||||
let repo = repo.strip_suffix(".git").unwrap_or(repo);
|
||||
if owner.is_empty() || repo.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((owner.to_owned(), repo.to_owned()))
|
||||
}
|
||||
|
||||
fn primary_github_repo(project: &Project) -> Option<(String, String)> {
|
||||
let repos = project.repos();
|
||||
let mut ordered = Vec::new();
|
||||
if let Some(primary) = repos.primary() {
|
||||
ordered.push(primary);
|
||||
}
|
||||
for repo in repos.all() {
|
||||
if ordered.first().is_none_or(|p| p.root() != repo.root()) {
|
||||
ordered.push(repo);
|
||||
}
|
||||
}
|
||||
for repo in ordered {
|
||||
let Ok(mut remotes) = repo.remotes() else { continue };
|
||||
remotes.sort_by_key(|r| r.name != "origin");
|
||||
for remote in remotes {
|
||||
let url = remote.resolved_url.as_deref().unwrap_or(&remote.url);
|
||||
if let Some(coords) = parse_github_owner_repo(url) {
|
||||
return Some(coords);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn auto_detect_account(program: &Path, accounts: &[GhAuthAccount], owner: &str, repo: &str) -> Option<(String, bool)> {
|
||||
// Fast path: the repository owner matches one of the signed-in accounts directly.
|
||||
if let Some(matched) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(owner)) {
|
||||
return Some((matched.login.clone(), !matched.active));
|
||||
}
|
||||
let key_repo = format!("{}/{}", owner.to_ascii_lowercase(), repo.to_ascii_lowercase());
|
||||
let key_logins: Vec<String> = accounts.iter().map(|a| format!("{}:{}", a.login, a.active)).collect();
|
||||
let cache_key = (key_repo, key_logins);
|
||||
if let Some(cached) = AUTO_CACHE.lock().get(&cache_key).cloned()
|
||||
&& cached.at.elapsed() < CACHE_TTL
|
||||
{
|
||||
if let Some(login) = cached.login {
|
||||
let is_active = accounts.iter().any(|a| a.login == login && a.active);
|
||||
return Some((login, !is_active));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let tokens: Vec<(GhAuthAccount, Option<String>)> =
|
||||
accounts.iter().map(|acc| (acc.clone(), gh_token_for_account(program, &acc.login))).collect();
|
||||
let results: Vec<(GhAuthAccount, RepoAccess)> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = tokens
|
||||
.into_iter()
|
||||
.map(|(acc, token)| {
|
||||
s.spawn(move || {
|
||||
let access = match token {
|
||||
Some(tok) => probe_repo_access(program, &tok, owner, repo),
|
||||
None => RepoAccess::None,
|
||||
};
|
||||
(acc, access)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().filter_map(|h| h.join().ok()).collect()
|
||||
});
|
||||
let picked = pick_best_account(&results).map(|(acc, auto)| (acc.login.clone(), auto));
|
||||
AUTO_CACHE
|
||||
.lock()
|
||||
.insert(cache_key, CachedAutoAccount { login: picked.as_ref().map(|(l, _)| l.clone()), at: Instant::now() });
|
||||
picked
|
||||
}
|
||||
|
||||
/// Resolves global status when no project is open.
|
||||
pub fn global_status(configured_account: String) -> GhProjectAccountStatus {
|
||||
let configured_account = configured_account.trim().to_owned();
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone())
|
||||
};
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account: None }
|
||||
}
|
||||
|
||||
/// Applies the project's explicit `vcs.github.account` setting to [`ide_core::project_env`]
|
||||
/// without making any network requests. `Automatic` (`""`) clears any injected `GH_TOKEN` so
|
||||
/// processes use `gh`'s own behaviour.
|
||||
pub fn apply_to_project(project: &Project) {
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return;
|
||||
}
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if configured_account.is_empty() {
|
||||
set_project_token(project, None);
|
||||
return;
|
||||
}
|
||||
let token = find_gh_executable().and_then(|program| gh_token_for_account(&program, &configured_account));
|
||||
set_project_token(project, token);
|
||||
}
|
||||
|
||||
/// Applies the project's explicit account setting and returns the full account status,
|
||||
/// probing the project's GitHub remote to suggest a matching non-active `gh` account when
|
||||
/// `vcs.github.account` is `Automatic` (`""`) and multiple `gh` accounts are signed in.
|
||||
pub fn project_status(project: &Project) -> GhProjectAccountStatus {
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
}
|
||||
apply_to_project(project);
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
};
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let active_login = accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone());
|
||||
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
active_login
|
||||
};
|
||||
|
||||
let suggested_account = if configured_account.is_empty() && accounts.len() >= 2 {
|
||||
primary_github_repo(project)
|
||||
.and_then(|(owner, repo)| auto_detect_account(&program, &accounts, &owner, &repo))
|
||||
.and_then(|(login, non_active_match)| non_active_match.then_some(login))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account }
|
||||
}
|
||||
|
||||
fn set_project_token(project: &Project, token: Option<String>) {
|
||||
let os_tok = token.map(std::ffi::OsString::from);
|
||||
let changed_root = ide_core::project_env::set_github_token(&project.root, os_tok.clone());
|
||||
let changed_wt = ide_core::project_env::set_github_token(project.agents.worktrees_dir(), os_tok);
|
||||
if changed_root || changed_wt {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_project_env(project: &Project) {
|
||||
ide_core::project_env::remove_all(&project.root);
|
||||
ide_core::project_env::remove_all(project.agents.worktrees_dir());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_github_owner_repo_across_https_ssh_and_scp_remotes() {
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("https://github.com/l0ng-ai/openidea.git"),
|
||||
Some(("l0ng-ai".into(), "openidea".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("[email protected]:acme-corp/payments.git"),
|
||||
Some(("acme-corp".into(), "payments".into()))
|
||||
);
|
||||
assert_eq!(parse_github_owner_repo("ssh://[email protected]/alice/demo/"), Some(("alice".into(), "demo".into())));
|
||||
assert_eq!(parse_github_owner_repo("https://gitlab.com/foo/bar.git"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_github_logins_against_flag_injection() {
|
||||
assert!(is_valid_github_login("alice"));
|
||||
assert!(is_valid_github_login("alice-work"));
|
||||
assert!(is_valid_github_login("l0ng-ai"));
|
||||
assert!(!is_valid_github_login(""));
|
||||
assert!(!is_valid_github_login("--hostname"));
|
||||
assert!(!is_valid_github_login("bad space"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_account_with_push_or_private_access_and_preserves_active_on_ties() {
|
||||
let personal = GhAuthAccount { login: "alice".into(), active: true };
|
||||
let work = GhAuthAccount { login: "alice-work".into(), active: false };
|
||||
|
||||
// Private org repo: personal gets 404 (None), work gets Push -> auto-detects work.
|
||||
let private_org = vec![(personal.clone(), RepoAccess::None), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&private_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Public org repo: personal gets Read, work gets Push -> auto-detects work.
|
||||
let public_org = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&public_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Third-party public repo: both get Read -> keeps active personal account without auto flag.
|
||||
let oss = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Read)];
|
||||
let (picked, auto) = pick_best_account(&oss).unwrap();
|
||||
assert_eq!(picked.login, "alice");
|
||||
assert!(!auto);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
pub mod environment;
|
||||
mod formatter;
|
||||
pub mod github_auth;
|
||||
mod java_runtime;
|
||||
mod kotlin_bridge;
|
||||
pub mod mcp;
|
||||
@@ -419,6 +420,7 @@ impl Host {
|
||||
self.environment.project_closed();
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
}
|
||||
}
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
|
||||
@@ -6,11 +6,11 @@ use crate::agent_secrets::{AgentSecrets, Kept};
|
||||
use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
|
||||
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
|
||||
RemoteSkillPreview, SkillsPolicy,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -108,6 +108,106 @@ pub fn agent_set_env(
|
||||
host.project(window)?.agents.set_builtin_env(&id, env)
|
||||
}
|
||||
|
||||
/// Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult<CopilotAuthStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
match host.project(window) {
|
||||
Ok(project) => Ok(project.agents.copilot_auth_status().await),
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
Ok(ide_agent::copilot_auth_status_with(Some(&custom_dir), None, &cwd).await)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_login_pty(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: std::path::PathBuf,
|
||||
launch: LoginLaunch,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
crate::ops::term::apply_output_rate(host, window);
|
||||
let cwd = if cwd.is_dir() { cwd } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
|
||||
let options = ide_terminal::TerminalOptions {
|
||||
cwd: cwd.into(),
|
||||
shell: Some(launch.program.to_string_lossy().into_owned()),
|
||||
args: launch.args,
|
||||
env: launch.env,
|
||||
cols: if cols == 0 { 80 } else { cols },
|
||||
rows: if rows == 0 { 20 } else { rows },
|
||||
shell_integration: false,
|
||||
};
|
||||
let exit_channel = on_event.clone();
|
||||
host.terminals.spawn_program(
|
||||
options,
|
||||
format!("agent-login:{window}"),
|
||||
host.window_sink(window),
|
||||
Box::new(move |data| {
|
||||
let _ = on_event.send(AgentLoginEvent::Output { data });
|
||||
}),
|
||||
Some(std::sync::Arc::new(move |code| {
|
||||
let _ = exit_channel.send(AgentLoginEvent::Exited { code });
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_login_spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let (cwd, launch) = match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let launch = host.blocking(move || agents.login_launch(&id)).await?;
|
||||
(root, launch)
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let launch = host
|
||||
.blocking(move || {
|
||||
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &id)
|
||||
})
|
||||
.await?;
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Starts `gh auth login --hostname github.com` in an IDE-managed PTY (with ambient token
|
||||
/// variables cleared) and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_gh_login_spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cwd = host
|
||||
.project(window)
|
||||
.map(|p| p.root.clone())
|
||||
.unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir));
|
||||
let launch = host.blocking(ide_agent::gh_login_launch).await?;
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
pub fn save_custom_agent(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
@@ -1463,15 +1563,18 @@ ide_command::domain!(
|
||||
agent_cli_update,
|
||||
agent_cli_update_check,
|
||||
agent_commands,
|
||||
agent_copilot_auth_status,
|
||||
agent_create,
|
||||
agent_delete,
|
||||
agent_entries,
|
||||
agent_external_sessions,
|
||||
agent_fork,
|
||||
agent_fork_session,
|
||||
agent_gh_login_spawn,
|
||||
agent_grouped_changes,
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
agent_login_spawn,
|
||||
agent_mcp_discover_sources,
|
||||
agent_mcp_import,
|
||||
agent_mcp_import_selected,
|
||||
|
||||
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save(doc)).await?;
|
||||
host.blocking(move || {
|
||||
project.documents.save(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
|
||||
let saved = host
|
||||
.blocking(move || {
|
||||
let saved = project.documents.autosave(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(saved)
|
||||
})
|
||||
.await?;
|
||||
if saved {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
|
||||
}
|
||||
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save_all()).await?;
|
||||
host.blocking(move || {
|
||||
let saved = project.documents.save_all();
|
||||
remember_saved_encodings(&project);
|
||||
saved
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use crate::project::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
|
||||
/// editor buffer, so syntax features and language-server requests work in it.
|
||||
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
|
||||
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
|
||||
}
|
||||
|
||||
/// Keeps the encoding the user chose for a project file in the project's File Encodings
|
||||
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
|
||||
/// until then its file is still in the old encoding. Nothing is kept for a document without
|
||||
/// a file in the project.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let info = project.documents.snapshot(doc)?;
|
||||
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
|
||||
return Ok(());
|
||||
}
|
||||
remember_encoding(&project, &info.path, &info.encoding)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Keeps the encodings of the converted documents a save has just written.
|
||||
pub(super) fn remember_saved_encodings(project: &Project) {
|
||||
for (path, encoding) in project.documents.take_saved_encodings() {
|
||||
if let Err(e) = remember_encoding(project, &path, &encoding) {
|
||||
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
|
||||
const MAPPINGS: &str = "editor.encodings.mappings";
|
||||
if project.light {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
|
||||
return Ok(());
|
||||
};
|
||||
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
|
||||
return Ok(());
|
||||
}
|
||||
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
|
||||
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
|
||||
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
|
||||
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
|
||||
@@ -263,6 +308,7 @@ ide_command::domain!(
|
||||
doc_outline,
|
||||
doc_python_facts,
|
||||
doc_rearrange,
|
||||
doc_remember_encoding,
|
||||
doc_selection_ranges,
|
||||
doc_set_bom,
|
||||
doc_set_encoding,
|
||||
|
||||
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
|
||||
f.sync().await;
|
||||
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
|
||||
|
||||
impl Fixture {
|
||||
fn project_settings(&self) -> PathBuf {
|
||||
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
|
||||
}
|
||||
|
||||
fn mappings_changed(&self) -> usize {
|
||||
let events = self.events.lock();
|
||||
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
assert!(!settings.exists());
|
||||
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
let written = std::fs::read_to_string(&settings).unwrap();
|
||||
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
// The same choice again leaves the file alone.
|
||||
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
|
||||
// A file outside the project has no place in the project's settings.
|
||||
let outside = f.open(&f.outside).await;
|
||||
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
|
||||
assert!(!settings.exists());
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
|
||||
|
||||
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&settings).unwrap(),
|
||||
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
|
||||
);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
// Later saves keep nothing more.
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", reopened.id).await.unwrap();
|
||||
let again = f.open(&f.path).await;
|
||||
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
|
||||
std::fs::write(&settings, "[editor\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
|
||||
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
|
||||
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
|
||||
assert_eq!(f.mappings_changed(), 0);
|
||||
}
|
||||
@@ -110,6 +110,22 @@ pub fn settings_removed_theme(host: &Host, window: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a changed setting `key` starts or stops right away. Both `settings_set` commands (this
|
||||
/// crate's and the desktop's) call it after writing the value.
|
||||
pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
|
||||
/// value: that project's windows) is told (`IdeEvent::SettingsChanged`) so it
|
||||
/// re-reads its effective settings.
|
||||
@@ -122,17 +138,7 @@ pub fn settings_set(
|
||||
value: String,
|
||||
) -> IdeResult<Settings> {
|
||||
let applied = set_settings(host, window, scope, &key, &value)?;
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(&key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
apply_setting(host, window, &key);
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key });
|
||||
if let Some(root) = applied.roots_changed {
|
||||
@@ -448,6 +454,14 @@ pub fn set_settings(
|
||||
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
|
||||
host.apply_git_executable();
|
||||
}
|
||||
if key == "vcs" || key == "vcs.github" || key.starts_with("vcs.github.") {
|
||||
let affected = affected();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
for project in affected {
|
||||
crate::github_auth::apply_to_project(&project);
|
||||
}
|
||||
});
|
||||
}
|
||||
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
|
||||
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
|
||||
for project in affected() {
|
||||
@@ -524,11 +538,56 @@ pub fn set_settings(
|
||||
Ok(SettingsApplied { settings: host.with_proxy_password(settings), project_scope, roots_changed })
|
||||
}
|
||||
|
||||
/// Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_project_account_status(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let current = host.project(window).ok().filter(|p| !p.light);
|
||||
let global_account = host.global_settings.effective().vcs.github.account;
|
||||
host.blocking(move || match current {
|
||||
Some(project) => Ok(crate::github_auth::project_status(&project)),
|
||||
None => Ok(crate::github_auth::global_status(global_account)),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Sets `vcs.github.account` for `window`'s project (or globally when no project is open),
|
||||
/// updates the project's `GH_TOKEN` environment immediately, and returns the updated status.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_set_project_account(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
account: String,
|
||||
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let trimmed = account.trim().to_owned();
|
||||
if !trimmed.is_empty() && !crate::github_auth::is_valid_github_login(&trimmed) {
|
||||
return Err(ide_core::IdeError::invalid(format!("invalid GitHub account login: {trimmed}")));
|
||||
}
|
||||
let current = host.project(window).ok().filter(|p| !p.light);
|
||||
let scope = if current.is_some() { SettingsScope::Project } else { SettingsScope::Global };
|
||||
let json = serde_json::to_string(&trimmed).map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
|
||||
set_settings(host, window, scope, "vcs.github.account", &json)?;
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key: "vcs.github.account".into() });
|
||||
let global_account = host.global_settings.effective().vcs.github.account;
|
||||
host.blocking(move || match current {
|
||||
Some(project) => Ok(crate::github_auth::project_status(&project)),
|
||||
None => Ok(crate::github_auth::global_status(global_account)),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
project:
|
||||
cancel_request,
|
||||
cancel_task,
|
||||
close_project,
|
||||
gh_project_account_status,
|
||||
gh_set_project_account,
|
||||
open_project,
|
||||
project_current,
|
||||
project_roots,
|
||||
|
||||
@@ -110,8 +110,8 @@ pub(crate) fn search_project(
|
||||
_ => true,
|
||||
};
|
||||
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
let defaults = project.documents.file_defaults();
|
||||
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
|
||||
// Search's UTF-8 fast path does not need to resolve the configured encoding.
|
||||
let fallback = |path: &Path| project.documents.configured_encoding_for(path);
|
||||
let mut total = SearchSummary::default();
|
||||
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
|
||||
let mut remaining = query.clone();
|
||||
|
||||
@@ -29,15 +29,19 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
|
||||
&root,
|
||||
&settings,
|
||||
));
|
||||
// Godot is usually an app bundle / Flatpak outside the search path.
|
||||
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
|
||||
// Godot and GitHub CLI can live in app bundles / MSI / Snap folders outside the search path.
|
||||
let mut found: std::collections::BTreeMap<_, _> =
|
||||
ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p)).into_iter().collect();
|
||||
if let Some(gh) = ide_core::tool_path::find_gh_outside_search_path() {
|
||||
found.insert("gh".to_owned(), gh);
|
||||
}
|
||||
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
|
||||
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
|
||||
Ok(Tools::new(&data)
|
||||
.with_downloads(settings.tool_downloads.clone())
|
||||
.with_runtime(runtime.commands, runtime.env)
|
||||
.with_custom_paths(custom)
|
||||
.with_found_paths(found.into_iter().collect())
|
||||
.with_found_paths(found)
|
||||
.with_work_dir(work_dir))
|
||||
}
|
||||
|
||||
|
||||
@@ -762,6 +762,12 @@ impl Host {
|
||||
if let Some(cmd) = post_start {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
if project.is_trusted() {
|
||||
let p = project.clone();
|
||||
self.runtime.spawn_blocking(move || {
|
||||
crate::github_auth::apply_to_project(&p);
|
||||
});
|
||||
}
|
||||
crate::ops::sdk::container_python::ensure(self, &project);
|
||||
Ok(project)
|
||||
}
|
||||
@@ -1524,8 +1530,7 @@ impl Project {
|
||||
}
|
||||
|
||||
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
|
||||
let defaults = self.documents.file_defaults();
|
||||
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
|
||||
let charset = self.documents.detect_encoding(path, bytes);
|
||||
self.vcs_text_encoding(path, charset)
|
||||
}
|
||||
|
||||
@@ -2015,7 +2020,9 @@ fn independent_eclipse_projects(root: &Path) -> Vec<PathBuf> {
|
||||
|
||||
/// The detected roots with the last Gradle sync's source sets first: Gradle evaluated what
|
||||
/// static detection guesses. Folders outside the project keep their absolute path, which
|
||||
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`).
|
||||
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`);
|
||||
/// their `detected_from` owner keeps its leading `/` or drive (`<project>/Gradle`) so
|
||||
/// module lists still address them as absolute paths.
|
||||
fn with_gradle_roots(
|
||||
root: &Path,
|
||||
build_cache: &Path,
|
||||
@@ -2039,12 +2046,22 @@ fn with_gradle_roots(
|
||||
};
|
||||
if !out.iter().any(|f| f.path == path) {
|
||||
// `<module>/Gradle`, like the `<module>/build.gradle` static detection reports, so the
|
||||
// UI still finds the module after a sync. Projects outside the root stay `Gradle`:
|
||||
// the UI reads the folder as project-relative.
|
||||
// UI still finds the module after a sync. Projects outside the root keep their
|
||||
// absolute owner (without `normalize`, which strips a leading `/`), except an ancestor
|
||||
// of the root (opened from a subproject) or a filesystem/drive root, which stay
|
||||
// `Gradle` so they cannot shadow in-project modules or collapse to a bare drive `D:`.
|
||||
let project = dunce::canonicalize(&project).unwrap_or(project);
|
||||
let detected_from = match project.strip_prefix(root) {
|
||||
Ok(rel) if !rel.as_os_str().is_empty() => {
|
||||
format!("{}/Gradle", ide_workspace::roots::normalize(&rel.to_string_lossy()))
|
||||
}
|
||||
Err(_) if !root.starts_with(&project) && project.parent().is_some() => {
|
||||
let raw = project.to_string_lossy().replace('\\', "/");
|
||||
let owner = raw.trim_end_matches('/');
|
||||
let drive_root =
|
||||
owner.len() == 2 && owner.as_bytes()[0].is_ascii_alphabetic() && owner.as_bytes()[1] == b':';
|
||||
if owner.is_empty() || drive_root { "Gradle".into() } else { format!("{owner}/Gradle") }
|
||||
}
|
||||
_ => "Gradle".into(),
|
||||
};
|
||||
out.push(SourceFolder { path, kind, detected_from: Some(detected_from) });
|
||||
@@ -2492,18 +2509,109 @@ mod gradle_roots_tests {
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&root, &cache, &Default::default(), &[guessed, other.clone()]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let owner = format!("{}/Gradle", svc.to_string_lossy().replace('\\', "/"));
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.kind, f.detected_from.as_deref())).collect();
|
||||
// A project outside the root is not a module the UI could address.
|
||||
// A project outside the root keeps its absolute owner so module lists still address it.
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
("src/it/java".into(), RootKind::Test, Some("Gradle")),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source, Some("Gradle")),
|
||||
(abs(svc.join("build")), RootKind::Excluded, Some("Gradle")),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source, Some(owner.as_str())),
|
||||
(abs(svc.join("build")), RootKind::Excluded, Some(owner.as_str())),
|
||||
("web".into(), RootKind::Source, None),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_sync_roots_keep_plain_gradle_for_ancestors_and_fs_roots() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let composite = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let app = composite.join("app");
|
||||
let lib = app.join("lib");
|
||||
let cache = composite.join("cache");
|
||||
let ext_posix = composite.join("ext-posix/src/main/java");
|
||||
let ext_win = composite.join("ext-win/src/main/java");
|
||||
for d in [
|
||||
composite.join("src/main/java"),
|
||||
app.join("src/main/java"),
|
||||
lib.join("src/main/java"),
|
||||
ext_posix.clone(),
|
||||
ext_win.clone(),
|
||||
cache.clone(),
|
||||
] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
let s = |p: PathBuf| p.to_string_lossy().into_owned();
|
||||
// Opened at `composite/app` while Gradle discovers parent `composite/settings.gradle`
|
||||
// (so `composite` is an ancestor of `root`), plus external roots owned by `/` or `D:/`.
|
||||
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
|
||||
{ "path": ":", "dir": s(composite.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(composite.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app", "dir": s(app.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app:lib", "dir": s(lib.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":posix-root", "dir": "/", "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(ext_posix.clone())], "res": [] } ] },
|
||||
{ "path": ":win-drive", "dir": "D:/", "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(ext_win.clone())], "res": [] } ] },
|
||||
]});
|
||||
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
|
||||
std::fs::write(app.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(abs(composite.join("src/main/java")), Some("Gradle")),
|
||||
("src/main/java".into(), Some("Gradle")),
|
||||
("lib/src/main/java".into(), Some("lib/Gradle")),
|
||||
(abs(ext_posix), Some("Gradle")),
|
||||
(abs(ext_win), Some("Gradle")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn gradle_sync_roots_canonicalize_symlinked_project_dirs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let real = ws.join("real");
|
||||
let link = ws.join("link");
|
||||
let app = real.join("app");
|
||||
let lib = app.join("lib");
|
||||
let cache = ws.join("cache");
|
||||
for d in [real.join("src/main/java"), app.join("src/main/java"), lib.join("src/main/java"), cache.clone()] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
std::os::unix::fs::symlink(&real, &link).unwrap();
|
||||
let s = |p: PathBuf| p.to_string_lossy().into_owned();
|
||||
// Opened at canonical `real/app`, while Gradle reports projects through the symlink `link`.
|
||||
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
|
||||
{ "path": ":", "dir": s(link.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(real.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app", "dir": s(link.join("app")), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app:lib", "dir": s(link.join("app/lib")), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
|
||||
]});
|
||||
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
|
||||
std::fs::write(app.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(abs(real.join("src/main/java")), Some("Gradle")),
|
||||
("src/main/java".into(), Some("Gradle")),
|
||||
("lib/src/main/java".into(), Some("lib/Gradle")),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -282,11 +282,18 @@ impl crate::Host {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
self.environment.direnv_opened(&project.root, &project.sink);
|
||||
{
|
||||
let p = project.clone();
|
||||
self.runtime.spawn_blocking(move || {
|
||||
crate::github_auth::apply_to_project(&p);
|
||||
});
|
||||
}
|
||||
project.lsp.set_execution_allowed(true);
|
||||
project.lsp.prewarm_java_configuration();
|
||||
} else {
|
||||
self.environment.project_closed();
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
project.agents.shutdown();
|
||||
project.flutter.stop();
|
||||
project.devtools.stop();
|
||||
|
||||
@@ -697,6 +697,7 @@ async fn typescript() {
|
||||
}
|
||||
|
||||
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
|
||||
#[cfg(unix)]
|
||||
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
|
||||
events.lock().unwrap().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path: p, source, items } if source == "tsc" && **p == *path => {
|
||||
|
||||
@@ -6,7 +6,6 @@ use ide_host::{Host, HostConfig};
|
||||
use ide_plugin::TextQuery;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
struct Harness {
|
||||
host: Arc<Host>,
|
||||
@@ -510,6 +509,7 @@ async fn plugin_run_output_mode_executes_pty_and_pipes_with_input_exit_and_stop(
|
||||
use ide_host::plugins::{Consent, PluginEvent, PluginHost, WindowRequest};
|
||||
use ide_plugin::{Invocation, Limits};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Duration;
|
||||
|
||||
let f = Harness::new();
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
|
||||
@@ -50,3 +50,25 @@ async fn find_in_files_decodes_closed_files_with_the_project_encoding() {
|
||||
project.documents.set_file_defaults(defaults);
|
||||
assert!(find(&host, "中文搜索验证").await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn find_in_files_decodes_closed_files_with_the_editorconfig_charset() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
std::fs::write(root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
|
||||
std::fs::write(root.join("A.java"), b"// a\xe7\xe3o \xa4 needle\n").unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
let mut defaults = project.documents.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
project.documents.set_file_defaults(defaults);
|
||||
|
||||
let files = find(&host, "ação €").await;
|
||||
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(files[0].matches[0].text, "// ação € needle", "the text the editor shows");
|
||||
assert_eq!(find(&host, "needle").await[0].matches[0].text, "// ação € needle");
|
||||
}
|
||||
@@ -34,6 +34,20 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin
|
||||
Some(settings)
|
||||
}
|
||||
|
||||
/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with
|
||||
/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3:
|
||||
/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes.
|
||||
/// A threshold the server configuration sets explicitly is kept.
|
||||
fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value {
|
||||
let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned();
|
||||
let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5);
|
||||
let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3);
|
||||
json!({
|
||||
"starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)),
|
||||
"staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)),
|
||||
})
|
||||
}
|
||||
|
||||
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
|
||||
for (id, value) in settings {
|
||||
let marker = format!(r#"<setting id="{id}" value=""#);
|
||||
@@ -84,6 +98,7 @@ pub fn configure_formatter(
|
||||
});
|
||||
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
|
||||
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
|
||||
settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited);
|
||||
cfg.settings = Some(settings);
|
||||
let Some(style) = style else { return Ok(()) };
|
||||
let indent = indent_settings(style);
|
||||
@@ -300,6 +315,44 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let imports = |cfg: &LanguageServerConfig| {
|
||||
crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone()
|
||||
};
|
||||
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle {
|
||||
class_count_to_use_import_with_star: Some(7),
|
||||
names_count_to_use_static_import_with_star: Some(4),
|
||||
..Default::default()
|
||||
};
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4}));
|
||||
|
||||
// Unset: IDEA's 5 and 3, not jdtls' 99 (#6026).
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() };
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2}));
|
||||
let mut cfg = config("jdtls");
|
||||
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3}));
|
||||
|
||||
// A threshold set in the server configuration wins.
|
||||
let mut cfg = config("jdtls");
|
||||
cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}}));
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2}));
|
||||
|
||||
let mut cfg = config("rust-analyzer");
|
||||
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
|
||||
assert!(crate::handler::all_settings(&cfg)["java"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -152,6 +152,8 @@ impl SshManager {
|
||||
let config = self.config(id)?;
|
||||
let secret = self.secret(&config);
|
||||
let session = Arc::new(self.connect(id, &SshTarget::from(&config), secret.as_deref()).await?);
|
||||
// The shared session carries the config's port forwards, restarted on every reconnect.
|
||||
session.start_forwards().await;
|
||||
self.sessions.lock().insert(id.to_owned(), session.clone());
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
//! (or is recorded silently under `StrictHostKeyChecking accept-new`), and a
|
||||
//! changed key is refused unless host key checking is off.
|
||||
|
||||
use crate::target::{Hop, HostKeyPolicy, SshFiles, SshTarget, expand, home, resolve_hops};
|
||||
use crate::target::{
|
||||
ForwardDirection, Hop, HostKeyPolicy, PortForward, SshFiles, SshTarget, expand, home, resolve_hops,
|
||||
};
|
||||
use ide_core::remote_settings::SshAuth;
|
||||
use ide_core::{IdeError, IdeResult, error::ErrorKind};
|
||||
use parking_lot::Mutex;
|
||||
@@ -113,6 +115,18 @@ pub struct Session {
|
||||
/// Sessions of the `ProxyJump` hosts, kept alive under `handle`.
|
||||
_jumps: Vec<Handle<Client>>,
|
||||
label: String,
|
||||
/// The config's `LocalForward` / `RemoteForward`s, started by [`Session::start_forwards`].
|
||||
forwards: Vec<PortForward>,
|
||||
/// `LocalForward` listeners, stopped with the session.
|
||||
listeners: Mutex<Vec<tokio::task::AbortHandle>>,
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
for listener in self.listeners.lock().drain(..) {
|
||||
listener.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -158,8 +172,50 @@ impl Session {
|
||||
sessions.push(handle);
|
||||
}
|
||||
let handle = sessions.pop().expect("at least one hop");
|
||||
let label = hops.last().expect("at least one hop").label();
|
||||
Ok(Session { handle, _jumps: sessions, label })
|
||||
let last = hops.last().expect("at least one hop");
|
||||
Ok(Session {
|
||||
handle,
|
||||
_jumps: sessions,
|
||||
label: last.label(),
|
||||
forwards: last.forwards.clone(),
|
||||
listeners: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts the config's `LocalForward` / `RemoteForward`s, as `ssh` does on connecting: the
|
||||
/// SSH host listens for each `RemoteForward` (`tcpip-forward`), this machine for each
|
||||
/// `LocalForward`, until the session closes. A port that cannot be forwarded (in use, refused
|
||||
/// by the server) is skipped with a warning, as `ssh` goes on without it.
|
||||
pub async fn start_forwards(self: &Arc<Self>) {
|
||||
for f in &self.forwards {
|
||||
let what = format!("{}:{} → {}:{}", f.bind, f.port, f.host, f.host_port);
|
||||
match f.direction {
|
||||
ForwardDirection::Remote => match self.handle.tcpip_forward(f.bind.clone(), u32::from(f.port)).await {
|
||||
Ok(_) => tracing::info!("{}: RemoteForward {what}", self.label),
|
||||
Err(e) => tracing::warn!("{}: RemoteForward {what} failed: {e}", self.label),
|
||||
},
|
||||
ForwardDirection::Local => {
|
||||
let bind = match f.bind.as_str() {
|
||||
"localhost" => "127.0.0.1",
|
||||
"" => "0.0.0.0",
|
||||
b => b,
|
||||
};
|
||||
match tokio::net::TcpListener::bind((bind, f.port)).await {
|
||||
Ok(listener) => {
|
||||
let task = tokio::spawn(local_forward(
|
||||
listener,
|
||||
Arc::downgrade(self),
|
||||
f.host.clone(),
|
||||
f.host_port,
|
||||
));
|
||||
self.listeners.lock().push(task.abort_handle());
|
||||
tracing::info!("{}: LocalForward {what}", self.label);
|
||||
}
|
||||
Err(e) => tracing::warn!("{}: LocalForward {what} failed: {e}", self.label),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `user@host:port` of the target.
|
||||
@@ -404,6 +460,39 @@ fn io(message: impl Into<String>) -> IdeError {
|
||||
IdeError::new(ErrorKind::Io, message)
|
||||
}
|
||||
|
||||
/// A `LocalForward` listener: each connection goes through a `direct-tcpip` channel to
|
||||
/// `host:port` from the SSH host, while the session lives.
|
||||
async fn local_forward(listener: tokio::net::TcpListener, session: std::sync::Weak<Session>, host: String, port: u16) {
|
||||
while let Ok((mut socket, _)) = listener.accept().await {
|
||||
let Some(session) = session.upgrade().filter(|s| !s.is_closed()) else { return };
|
||||
let host = host.clone();
|
||||
tokio::spawn(async move {
|
||||
match session.direct_tcpip(&host, port).await {
|
||||
Ok(mut stream) => {
|
||||
drop(session);
|
||||
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
|
||||
}
|
||||
Err(e) => tracing::warn!("LocalForward: cannot open a channel to {host}:{port}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A `RemoteForward` connection: accepted once `host:port` here answers, then copied both ways.
|
||||
async fn remote_forward(channel: russh::Channel<Msg>, reply: client::ChannelOpenHandle, host: String, port: u16) {
|
||||
match tokio::net::TcpStream::connect((host.as_str(), port)).await {
|
||||
Ok(mut socket) => {
|
||||
reply.accept().await;
|
||||
let mut stream = channel.into_stream();
|
||||
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("RemoteForward: cannot connect to {host}:{port}: {e}");
|
||||
reply.reject(russh::ChannelOpenFailure::ConnectFailed).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- connection ----------------------------------------------------------------
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -418,6 +507,8 @@ pub struct Client {
|
||||
known_hosts: PathBuf,
|
||||
host_key_policy: HostKeyPolicy,
|
||||
issue: Arc<Mutex<Option<HostKeyIssue>>>,
|
||||
/// The `RemoteForward`s whose connections this client accepts.
|
||||
remote_forwards: Vec<PortForward>,
|
||||
}
|
||||
|
||||
impl client::Handler for Client {
|
||||
@@ -442,6 +533,26 @@ impl client::Handler for Client {
|
||||
*self.issue.lock() = Some(issue);
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
async fn server_channel_open_forwarded_tcpip(
|
||||
&mut self,
|
||||
channel: russh::Channel<Msg>,
|
||||
_connected_address: &str,
|
||||
connected_port: u32,
|
||||
_originator_address: &str,
|
||||
_originator_port: u32,
|
||||
reply: client::ChannelOpenHandle,
|
||||
_session: &mut client::Session,
|
||||
) -> Result<(), Self::Error> {
|
||||
// Only a port this client asked the server to forward is accepted.
|
||||
match self.remote_forwards.iter().find(|f| u32::from(f.port) == connected_port) {
|
||||
Some(f) => {
|
||||
tokio::spawn(remote_forward(channel, reply, f.host.clone(), f.host_port));
|
||||
}
|
||||
None => reply.reject(russh::ChannelOpenFailure::AdministrativelyProhibited).await,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@@ -600,6 +711,7 @@ where
|
||||
known_hosts: effective_known_hosts,
|
||||
host_key_policy: hop.host_key_policy,
|
||||
issue: issue.clone(),
|
||||
remote_forwards: hop.forwards.iter().filter(|f| f.direction == ForwardDirection::Remote).cloned().collect(),
|
||||
};
|
||||
let result = match stream {
|
||||
None => client::connect(config, (hop.host.as_str(), hop.port), handler).await,
|
||||
|
||||
@@ -54,6 +54,63 @@ pub(crate) struct Hop {
|
||||
pub host_key_policy: HostKeyPolicy,
|
||||
pub known_hosts: Option<PathBuf>,
|
||||
pub agent: Agent,
|
||||
/// `LocalForward` / `RemoteForward` of the config (the target's; jump hosts forward nothing).
|
||||
pub forwards: Vec<PortForward>,
|
||||
}
|
||||
|
||||
/// A `LocalForward` or `RemoteForward` of `~/.ssh/config`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PortForward {
|
||||
pub direction: ForwardDirection,
|
||||
/// Address the listening side binds: empty for every address, `localhost` by default.
|
||||
pub bind: String,
|
||||
pub port: u16,
|
||||
/// Where each connection goes, as the other side sees it.
|
||||
pub host: String,
|
||||
pub host_port: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ForwardDirection {
|
||||
/// `LocalForward`: this machine listens, connections go to `host:host_port` from the SSH host.
|
||||
Local,
|
||||
/// `RemoteForward`: the SSH host listens, connections go to `host:host_port` from this machine.
|
||||
Remote,
|
||||
}
|
||||
|
||||
/// `[bind_address:]port host:hostport` (or the one-argument `-L` / `-R` form with colons); IPv6
|
||||
/// addresses in brackets. `None` for what isn't a TCP forward: a Unix socket, or `RemoteForward`'s
|
||||
/// dynamic (SOCKS) form.
|
||||
pub(crate) fn parse_forward(direction: ForwardDirection, value: &str) -> Option<PortForward> {
|
||||
let spec = split_args(value).join(":");
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut bracket = false;
|
||||
for ch in spec.chars() {
|
||||
match ch {
|
||||
'[' if cur.is_empty() => bracket = true,
|
||||
']' if bracket => bracket = false,
|
||||
':' if !bracket => parts.push(std::mem::take(&mut cur)),
|
||||
'/' => return None,
|
||||
_ => cur.push(ch),
|
||||
}
|
||||
}
|
||||
parts.push(cur);
|
||||
let (bind, port, host, host_port) = match parts.as_slice() {
|
||||
[port, host, host_port] => (None, port, host, host_port),
|
||||
[bind, port, host, host_port] => (Some(bind.as_str()), port, host, host_port),
|
||||
_ => return None,
|
||||
};
|
||||
let bind = match bind {
|
||||
None => "localhost".to_owned(),
|
||||
Some("*") | Some("") => String::new(),
|
||||
Some(b) => b.to_owned(),
|
||||
};
|
||||
let (port, host_port) = (port.parse().ok()?, host_port.parse().ok()?);
|
||||
if host.is_empty() || host_port == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(PortForward { direction, bind, port, host: host.clone(), host_port })
|
||||
}
|
||||
|
||||
/// Where the SSH agent of a hop listens (`IdentityAgent`).
|
||||
@@ -158,6 +215,8 @@ struct RawConfig {
|
||||
host_key_policy: Option<HostKeyPolicy>,
|
||||
user_known_hosts_file: Option<String>,
|
||||
identity_agent: Option<String>,
|
||||
forwards: Vec<PortForward>,
|
||||
clear_forwardings: bool,
|
||||
}
|
||||
|
||||
fn strip_quotes(s: &str) -> &str {
|
||||
@@ -516,6 +575,23 @@ fn parse_config_file(
|
||||
out.user_known_hosts_file = Some(first);
|
||||
}
|
||||
}
|
||||
"localforward" | "remoteforward" => {
|
||||
let direction = if key.eq_ignore_ascii_case("localforward") {
|
||||
ForwardDirection::Local
|
||||
} else {
|
||||
ForwardDirection::Remote
|
||||
};
|
||||
match parse_forward(direction, value) {
|
||||
Some(f) if !out.forwards.contains(&f) => out.forwards.push(f),
|
||||
Some(_) => {}
|
||||
None => tracing::debug!("ssh config: {key} {value} is not a TCP port forward; skipped"),
|
||||
}
|
||||
}
|
||||
"clearallforwardings" => {
|
||||
if matches!(strip_quotes(value).to_ascii_lowercase().as_str(), "yes" | "true") {
|
||||
out.clear_forwardings = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -559,7 +635,8 @@ fn config_hop(
|
||||
if null_known_hosts { HostKeyPolicy::Off } else { raw.host_key_policy.unwrap_or(HostKeyPolicy::Ask) };
|
||||
let agent =
|
||||
identity_agent(raw.identity_agent.as_deref(), |p| expand(&expand_tokens(p, alias, &host, port, &user, &local)));
|
||||
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent };
|
||||
let forwards = if raw.clear_forwardings { Vec::new() } else { raw.forwards };
|
||||
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent, forwards };
|
||||
(hop, proxy_jump)
|
||||
}
|
||||
|
||||
@@ -574,7 +651,7 @@ fn jump_hop(config: Option<&Path>, spec: &str) -> Hop {
|
||||
_ => (rest, None),
|
||||
};
|
||||
let (hop, _) = config_hop(config, host, port, user);
|
||||
hop
|
||||
Hop { forwards: Vec::new(), ..hop }
|
||||
}
|
||||
|
||||
/// The SSH hosts to go through, the target last.
|
||||
@@ -597,6 +674,7 @@ pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResu
|
||||
host_key_policy: HostKeyPolicy::Ask,
|
||||
known_hosts: None,
|
||||
agent: Agent::Default,
|
||||
forwards: Vec::new(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
@@ -636,6 +714,40 @@ pub fn openssh_args(target: &SshTarget) -> Vec<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_port_forwards_like_openssh() {
|
||||
let f = |d, v: &str| parse_forward(d, v).map(|f| (f.bind, f.port, f.host, f.host_port));
|
||||
let remote = ForwardDirection::Remote;
|
||||
assert_eq!(f(remote, "9222 127.0.0.1:9222"), Some(("localhost".into(), 9222, "127.0.0.1".into(), 9222)));
|
||||
assert_eq!(f(remote, "0.0.0.0:8080 web:80"), Some(("0.0.0.0".into(), 8080, "web".into(), 80)));
|
||||
assert_eq!(f(remote, "*:8080 web:80"), Some((String::new(), 8080, "web".into(), 80)));
|
||||
assert_eq!(f(remote, "[::1]:8080 [::1]:80"), Some(("::1".into(), 8080, "::1".into(), 80)));
|
||||
assert_eq!(f(ForwardDirection::Local, "5432:db:5432"), Some(("localhost".into(), 5432, "db".into(), 5432)));
|
||||
// Dynamic (SOCKS) and Unix socket forwards aren't TCP port forwards.
|
||||
assert_eq!(f(remote, "1080"), None);
|
||||
assert_eq!(f(remote, "/tmp/a.sock /tmp/b.sock"), None);
|
||||
assert_eq!(f(remote, "8080 web:http"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_forwards_belong_to_the_target_and_clear_all_forwardings_drops_them() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = dir.path().join("config");
|
||||
std::fs::write(
|
||||
&config,
|
||||
"Host box\n RemoteForward 9222 127.0.0.1:9222\n LocalForward 5432 db:5432\n ProxyJump gate\n\
|
||||
Host gate\n LocalForward 1 a:1\nHost quiet\n RemoteForward 9222 127.0.0.1:9222\n ClearAllForwardings yes\n",
|
||||
)
|
||||
.unwrap();
|
||||
let target = |host: &str| SshTarget { host: host.into(), auth: SshAuth::OpenSsh, ..Default::default() };
|
||||
let hops = resolve_hops(&target("box"), Some(&config)).unwrap();
|
||||
assert_eq!(hops.len(), 2);
|
||||
assert!(hops[0].forwards.is_empty(), "jump hosts forward nothing");
|
||||
let dirs: Vec<_> = hops[1].forwards.iter().map(|f| (f.direction, f.port)).collect();
|
||||
assert_eq!(dirs, [(ForwardDirection::Remote, 9222), (ForwardDirection::Local, 5432)]);
|
||||
assert!(resolve_hops(&target("quiet"), Some(&config)).unwrap()[0].forwards.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_aliases_and_proxy_jumps_from_ssh_config() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -98,6 +98,32 @@ impl server::Handler for Sshd {
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `RemoteForward`: listens on 127.0.0.1:`port` and forwards each connection back to the client.
|
||||
async fn tcpip_forward(
|
||||
&mut self,
|
||||
address: &str,
|
||||
port: &mut u32,
|
||||
session: &mut ServerSession,
|
||||
) -> Result<bool, Self::Error> {
|
||||
let Ok(listener) = TcpListener::bind(("127.0.0.1", *port as u16)).await else { return Ok(false) };
|
||||
let (handle, address, port) = (session.handle(), address.to_owned(), *port);
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut socket, peer)) = listener.accept().await {
|
||||
let Ok(channel) = handle
|
||||
.channel_open_forwarded_tcpip(address.clone(), port, "127.0.0.1", u32::from(peer.port()))
|
||||
.await
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
let mut stream = channel.into_stream();
|
||||
let _ = tokio::io::copy_bidirectional(&mut stream, &mut socket).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Echo server standing in for a remote service.
|
||||
@@ -443,3 +469,50 @@ async fn accept_new_records_an_unknown_key_and_still_refuses_a_changed_one() {
|
||||
let msg = denied(env.connect(&target, None).await);
|
||||
assert!(msg.contains("has changed"), "{msg}");
|
||||
}
|
||||
|
||||
/// A free local port (bound and released).
|
||||
fn free_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
async fn echoes(port: u16) {
|
||||
let mut s = TcpStream::connect(("127.0.0.1", port)).await.expect("forwarded port listens");
|
||||
s.write_all(b"ping").await.unwrap();
|
||||
let mut buf = [0u8; 4];
|
||||
s.read_exact(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf, b"ping");
|
||||
}
|
||||
|
||||
/// `RemoteForward` and `LocalForward` of `~/.ssh/config` are forwarded while the session lives (#6031).
|
||||
#[tokio::test]
|
||||
async fn config_port_forwards_follow_the_session() {
|
||||
let mut env = env().await;
|
||||
let (remote, local) = (free_port(), free_port());
|
||||
let config = env._tmp.path().join("ssh_config");
|
||||
std::fs::write(
|
||||
&config,
|
||||
format!(
|
||||
"Host box\n\tHostName 127.0.0.1\n\tStrictHostKeyChecking=no\n\tUserKnownHostsFile=/dev/null\n\
|
||||
\tRemoteForward {remote} 127.0.0.1:{echo}\n\tLocalForward 127.0.0.1:{local} localhost:{echo}\n\
|
||||
\tRemoteForward /tmp/remote.sock /tmp/local.sock\n",
|
||||
echo = env.echo_port
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
env.files.config = Some(config);
|
||||
let target = SshTarget {
|
||||
host: "box".into(),
|
||||
port: Some(env.ssh_port),
|
||||
user: "coder".into(),
|
||||
auth: SshAuth::OpenSsh,
|
||||
..Default::default()
|
||||
};
|
||||
let session = Arc::new(env.connect(&target, None).await.expect("connects"));
|
||||
session.start_forwards().await;
|
||||
// The SSH host's port reaches the echo server here; the local port reaches it from the SSH host.
|
||||
echoes(remote).await;
|
||||
echoes(local).await;
|
||||
drop(session);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
assert!(TcpStream::connect(("127.0.0.1", local)).await.is_err(), "a closed session stops its LocalForward");
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
//! without network.
|
||||
|
||||
use crate::platform::{Arch, Os, Platform};
|
||||
use crate::process::{Emit, Http};
|
||||
use crate::process::Emit;
|
||||
use crate::sources::Download;
|
||||
use crate::{InstallEvent, InstallGuard, Tools, archive, clear_quarantine, fetch_verified};
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -240,10 +240,6 @@ fn unpacked_root(pkg: &Path, home: &Path) -> PathBuf {
|
||||
}
|
||||
|
||||
impl Tools {
|
||||
fn http(&self) -> IdeResult<Http> {
|
||||
Http::new(&self.system_path)
|
||||
}
|
||||
|
||||
/// Java versions `vendor` publishes.
|
||||
pub fn jdk_releases(&self, vendor: &str, cancel: &CancellationToken) -> IdeResult<JdkReleases> {
|
||||
vendor_or_err(vendor)?;
|
||||
|
||||
@@ -557,6 +557,10 @@ impl Tools {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub(crate) fn http(&self) -> IdeResult<Http> {
|
||||
Ok(Http::new(&self.system_path)?.with_gh_from(&self.child_path))
|
||||
}
|
||||
|
||||
/// [`Tools::command`] in the project directory.
|
||||
fn command_in_project(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
|
||||
let mut cmd = self.command(program);
|
||||
@@ -902,7 +906,7 @@ impl Tools {
|
||||
_ => (ToolStatus::Missing, None, None),
|
||||
}
|
||||
}
|
||||
_ => match self.which(main) {
|
||||
_ => match self.which(main).or_else(|| self.found.get(main).cloned()) {
|
||||
Some(path) => {
|
||||
let version = self.query_version(spec, &path);
|
||||
(ToolStatus::OnPath, Some(path), version)
|
||||
@@ -1250,7 +1254,8 @@ impl Tools {
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
};
|
||||
let pick = Http::new(&self.system_path)
|
||||
let pick = self
|
||||
.http()
|
||||
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
|
||||
match pick {
|
||||
Ok(dotnet::ToolPick::Latest) => Ok(None),
|
||||
@@ -1542,7 +1547,7 @@ impl Tools {
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let http = Http::new(&self.system_path)?;
|
||||
let http = self.http()?;
|
||||
let message = match source {
|
||||
ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"),
|
||||
_ => "Resolving the latest release…".into(),
|
||||
@@ -1683,7 +1688,7 @@ impl Tools {
|
||||
fn latest_version(&self, method: Method, cancel: &CancellationToken) -> IdeResult<Option<String>> {
|
||||
match method {
|
||||
Method::Release { source, assets, .. } => {
|
||||
let http = Http::new(&self.system_path)?;
|
||||
let http = self.http()?;
|
||||
Ok(Some(self.resolve_release(&http, source, assets, cancel)?.version))
|
||||
}
|
||||
Method::Npm { packages } => {
|
||||
|
||||
@@ -441,6 +441,17 @@ impl Http {
|
||||
self
|
||||
}
|
||||
|
||||
/// Looks up `gh` on `search_path` (e.g. a path that includes IDE-managed tools).
|
||||
pub(crate) fn with_gh_from(mut self, search_path: &std::ffi::OsStr) -> Self {
|
||||
self.gh = which::which_in("gh", Some(search_path), ".").ok();
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
pub(crate) fn gh_path(&self) -> Option<&Path> {
|
||||
self.gh.as_deref()
|
||||
}
|
||||
|
||||
/// Skips `GITHUB_TOKEN` / `GH_TOKEN` / `gh auth token` (e.g. retrying a public GitHub endpoint after HTTP 401).
|
||||
pub fn without_github_auth(mut self) -> Self {
|
||||
self.gh = None;
|
||||
|
||||
@@ -181,6 +181,28 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
needs: NODE,
|
||||
homepage: "https://github.com/devcontainers/cli",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "gh",
|
||||
display: "GitHub CLI",
|
||||
kind: Cli,
|
||||
commands: &["gh"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "cli/cli" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "gh_*_macOS_arm64.zip"),
|
||||
rule(Mac, X64, "gh_*_macOS_amd64.zip"),
|
||||
rule(Linux, Arm64, "gh_*_linux_arm64.tar.gz"),
|
||||
rule(Linux, X64, "gh_*_linux_amd64.tar.gz"),
|
||||
rule(Windows, Arm64, "gh_*_windows_arm64.zip"),
|
||||
rule(Windows, X64, "gh_*_windows_amd64.zip"),
|
||||
],
|
||||
locate: &["gh"],
|
||||
},
|
||||
fallback: None,
|
||||
version: ver("gh"),
|
||||
needs: &[],
|
||||
homepage: "https://cli.github.com",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "oxfmt",
|
||||
display: "oxfmt",
|
||||
@@ -1483,4 +1505,56 @@ mod tests {
|
||||
let win_arm = Platform { os: Windows, arch: Arm64 };
|
||||
assert_eq!(select_asset(&names, rules, win_arm), Some("kotlin-server-263.7084.0-aarch64.win.zip"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gh_release_picks_portable_archive_for_every_supported_platform() {
|
||||
use crate::platform::{Platform, select_asset};
|
||||
let names = [
|
||||
"gh_2.106.0_checksums.txt",
|
||||
"gh_2.106.0_linux_386.deb",
|
||||
"gh_2.106.0_linux_386.tar.gz",
|
||||
"gh_2.106.0_linux_amd64.deb",
|
||||
"gh_2.106.0_linux_amd64.rpm",
|
||||
"gh_2.106.0_linux_amd64.tar.gz",
|
||||
"gh_2.106.0_linux_arm64.deb",
|
||||
"gh_2.106.0_linux_arm64.tar.gz",
|
||||
"gh_2.106.0_linux_armv6.tar.gz",
|
||||
"gh_2.106.0_macOS_amd64.zip",
|
||||
"gh_2.106.0_macOS_arm64.zip",
|
||||
"gh_2.106.0_macOS_universal.pkg",
|
||||
"gh_2.106.0_windows_386.zip",
|
||||
"gh_2.106.0_windows_amd64.msi",
|
||||
"gh_2.106.0_windows_amd64.zip",
|
||||
"gh_2.106.0_windows_arm64.msi",
|
||||
"gh_2.106.0_windows_arm64.zip",
|
||||
];
|
||||
let spec = find("gh").unwrap();
|
||||
assert_eq!(spec.kind, Cli);
|
||||
let rules = spec.asset_rules();
|
||||
for (os, arch, expected) in [
|
||||
(Mac, Arm64, "gh_2.106.0_macOS_arm64.zip"),
|
||||
(Mac, X64, "gh_2.106.0_macOS_amd64.zip"),
|
||||
(Linux, Arm64, "gh_2.106.0_linux_arm64.tar.gz"),
|
||||
(Linux, X64, "gh_2.106.0_linux_amd64.tar.gz"),
|
||||
(Windows, Arm64, "gh_2.106.0_windows_arm64.zip"),
|
||||
(Windows, X64, "gh_2.106.0_windows_amd64.zip"),
|
||||
] {
|
||||
assert_eq!(select_asset(&names, rules, Platform { os, arch }), Some(expected));
|
||||
}
|
||||
|
||||
let Method::Release { locate, .. } = &spec.method else { unreachable!() };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let unix_bin = tmp.path().join("gh_2.106.0_macOS_arm64/bin/gh");
|
||||
std::fs::create_dir_all(unix_bin.parent().unwrap()).unwrap();
|
||||
std::fs::write(&unix_bin, "").unwrap();
|
||||
let unix_names: Vec<String> = locate.iter().map(|n| (*n).to_owned()).collect();
|
||||
assert_eq!(crate::archive::locate(tmp.path(), &unix_names), Some(unix_bin));
|
||||
|
||||
let win_dir = tempfile::tempdir().unwrap();
|
||||
let win_bin = win_dir.path().join("bin/gh.exe");
|
||||
std::fs::create_dir_all(win_bin.parent().unwrap()).unwrap();
|
||||
std::fs::write(&win_bin, "").unwrap();
|
||||
let win_names: Vec<String> = locate.iter().map(|n| format!("{n}.exe")).collect();
|
||||
assert_eq!(crate::archive::locate(win_dir.path(), &win_names), Some(win_bin));
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,11 @@ fn pick_release(
|
||||
let checksum_url = assets
|
||||
.iter()
|
||||
.find(|c| c.name == format!("{name}.sha256") || c.name == format!("{name}.sha256sum"))
|
||||
.or_else(|| {
|
||||
assets
|
||||
.iter()
|
||||
.find(|c| c.name.eq_ignore_ascii_case("checksums.txt") || c.name.ends_with("_checksums.txt"))
|
||||
})
|
||||
.map(|c| c.url.clone());
|
||||
return Ok(Download {
|
||||
version,
|
||||
@@ -622,6 +627,28 @@ mod tests {
|
||||
let sums = format!("{} other.zip\n{} *wanted.zip\n", "b".repeat(64), "C".repeat(64));
|
||||
assert_eq!(parse_checksum(&sums, "wanted.zip"), Some("c".repeat(64)));
|
||||
assert_eq!(parse_checksum(&sums, "missing.zip"), None);
|
||||
|
||||
let gh = serde_json::json!({
|
||||
"tag_name": "v2.106.0",
|
||||
"assets": [
|
||||
{
|
||||
"name": "gh_2.106.0_macOS_arm64.zip",
|
||||
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_macOS_arm64.zip"
|
||||
},
|
||||
{
|
||||
"name": "gh_2.106.0_checksums.txt",
|
||||
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt"
|
||||
}
|
||||
]
|
||||
})
|
||||
.to_string();
|
||||
let dl = github_pick(&gh, find("gh").unwrap().asset_rules(), MAC_ARM).unwrap();
|
||||
assert_eq!(dl.version, "2.106.0");
|
||||
assert_eq!(dl.name, "gh_2.106.0_macOS_arm64.zip");
|
||||
assert_eq!(
|
||||
dl.checksum_url.as_deref(),
|
||||
Some("https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1428,3 +1428,27 @@ fn a_mirror_never_installs_what_it_alone_vouches_for() {
|
||||
let err = check_sha256(&archive, &dl(Some(&digest)), Some(&"0".repeat(64)), true, &emit).unwrap_err();
|
||||
assert!(err.message.contains("checksum mismatch"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn managed_gh_is_detected_on_tools_bin_dirs_and_available_to_http() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "curl", "exit 0");
|
||||
let app_data = env.root.parent().unwrap();
|
||||
let gh_bin = env.root.join("gh/bin");
|
||||
assert!(tools_bin_dirs(app_data).contains(&gh_bin));
|
||||
|
||||
let missing = env.tools().info("gh", &[]).unwrap();
|
||||
assert_eq!(missing.kind, ToolKind::Cli);
|
||||
assert_eq!(missing.status, ToolStatus::Missing);
|
||||
assert!(missing.can_install);
|
||||
|
||||
env.script(&gh_bin, "gh", "echo 'gh version 2.106.0 (2026-11-20)'");
|
||||
let installed = env.tools().info("gh", &[]).unwrap();
|
||||
assert_eq!(installed.status, ToolStatus::Installed);
|
||||
assert_eq!(installed.version.as_deref(), Some("2.106.0"));
|
||||
assert!(installed.can_uninstall);
|
||||
|
||||
let http = env.tools().http().unwrap();
|
||||
assert_eq!(http.gh_path(), Some(gh_bin.join("gh").as_path()));
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::editorconfig::{EditorConfig, EditorConfigProps};
|
||||
use crate::file_defaults::FileDefaults;
|
||||
use crate::file_defaults::{EncodingSource, FileDefaults};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink, TextEdit};
|
||||
use ide_text::{AppliedChange, ByteEdit, Document, LineEnding};
|
||||
@@ -168,12 +168,17 @@ struct DocState {
|
||||
can_reload_encoding: bool,
|
||||
/// The user picked `encoding`; reloads keep it instead of detecting again.
|
||||
encoding_chosen: bool,
|
||||
/// The user converted the text to `encoding`; it is theirs to keep once a save writes it.
|
||||
encoding_unsaved: bool,
|
||||
/// Disk state we last loaded or wrote; changes matching it are our own.
|
||||
disk_mtime: f64,
|
||||
disk_len: u64,
|
||||
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
|
||||
/// alone until the user saves explicitly or the buffer is reloaded.
|
||||
disk_conflict: bool,
|
||||
/// External changes seen while the buffer had unsaved changes (each `disk_conflict`), so an
|
||||
/// undo of a refactoring can tell a write by another program from the IDE's own saves.
|
||||
external_writes: u64,
|
||||
/// Text as of that disk state: an edit that returns to it (undo) leaves the document clean.
|
||||
/// `None` for large files (no second copy), virtual documents, and once a pending encoding,
|
||||
/// line-ending or BOM change makes the buffer differ from the file whatever the text.
|
||||
@@ -191,6 +196,35 @@ impl DocState {
|
||||
self.disk_conflict = false;
|
||||
self.clean_text = (!self.large).then(|| self.doc.clone());
|
||||
}
|
||||
|
||||
/// The bytes saving `doc` with this document's encoding, BOM and conversion would write.
|
||||
fn bytes_for_save(&self, doc: &Document) -> IdeResult<Vec<u8>> {
|
||||
let text = doc.text_for_save();
|
||||
Ok(if self.native_to_ascii {
|
||||
ide_vfs::encode_properties_ascii(&text).into_bytes()
|
||||
} else {
|
||||
ide_vfs::encode(&text, &self.encoding, self.has_bom)?
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the file changed on disk since the buffer last matched it. A moved stamp with the
|
||||
/// same bytes (touch, a tool rewriting the file unchanged) is no change and its stamp is adopted. Reads the file
|
||||
/// only when the mtime moved but the length did not; without a clean text to compare (large
|
||||
/// files, a pending encoding, line-ending or BOM change, a reported conflict) a moved stamp counts.
|
||||
fn changed_on_disk(&mut self, meta: &std::fs::Metadata) -> bool {
|
||||
let mtime = ide_vfs::mtime_ms(meta);
|
||||
if mtime == self.disk_mtime && meta.len() == self.disk_len {
|
||||
return false;
|
||||
}
|
||||
let same_bytes = meta.len() == self.disk_len
|
||||
&& self.clean_text.as_ref().is_some_and(|clean| {
|
||||
self.bytes_for_save(clean).is_ok_and(|bytes| std::fs::read(&self.path).is_ok_and(|disk| disk == bytes))
|
||||
});
|
||||
if same_bytes {
|
||||
self.disk_mtime = mtime;
|
||||
}
|
||||
!same_bytes
|
||||
}
|
||||
}
|
||||
|
||||
fn keys_for(path: &Path) -> Vec<PathBuf> {
|
||||
@@ -215,19 +249,25 @@ fn disk_len(path: &Path) -> u64 {
|
||||
std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn editorconfig_label(editorconfig: Option<&EditorConfigProps>, detected: &str, ascii: bool) -> Option<&'static str> {
|
||||
let (charset, _) = editorconfig?.encoding()?;
|
||||
let compatible = encoding_rs::Encoding::for_label(detected.as_bytes()).is_some_and(|e| e.is_ascii_compatible());
|
||||
(ascii && compatible && !charset.starts_with("utf-16")).then_some(charset)
|
||||
}
|
||||
|
||||
fn apply_editorconfig_charset(loaded: &mut ide_vfs::LoadedText, editorconfig: Option<&EditorConfigProps>) {
|
||||
if loaded.binary {
|
||||
return;
|
||||
}
|
||||
if let Some(charset) = editorconfig_label(editorconfig, &loaded.encoding, !loaded.has_bom && loaded.text.is_ascii())
|
||||
{
|
||||
loaded.encoding = charset.to_owned();
|
||||
/// EditorConfig takes precedence over File Encodings for legacy text and ASCII labels.
|
||||
/// UTF-16 is detected, not assumed; invalid UTF-8 still uses the File Encodings fallback.
|
||||
fn configured_fallback<'a>(
|
||||
defaults: &'a FileDefaults,
|
||||
path: &Path,
|
||||
editorconfig: Option<&EditorConfigProps>,
|
||||
) -> Option<ide_vfs::Fallback<'a>> {
|
||||
let path = absolute(path);
|
||||
let charset = editorconfig.filter(|_| defaults.editorconfig).and_then(EditorConfigProps::encoding);
|
||||
let inherited = defaults.inherited_encoding_for(&path);
|
||||
let fallback = if inherited.source == EncodingSource::Folder && charset.is_some() {
|
||||
defaults.project_encoding_for(&path).fallback()
|
||||
} else {
|
||||
inherited.fallback()
|
||||
};
|
||||
match charset {
|
||||
Some(("utf-8", _)) => fallback.map(|f| ide_vfs::Fallback { ascii: false, ..f }),
|
||||
Some((encoding, _)) if !encoding.starts_with("utf-16") => Some(ide_vfs::Fallback { encoding, ascii: true }),
|
||||
_ => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,17 +373,21 @@ impl Documents {
|
||||
/// Closed-file readers use the same decoding as document opening.
|
||||
pub fn load_file(&self, path: &Path) -> IdeResult<ide_vfs::LoadedText> {
|
||||
let defaults = self.file_defaults();
|
||||
Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())
|
||||
Ok(Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())?.0)
|
||||
}
|
||||
|
||||
/// Encoding of `bytes`, a revision of `path`, with the same rules as opening the file.
|
||||
pub fn detect_encoding(&self, path: &Path, bytes: &[u8]) -> &'static encoding_rs::Encoding {
|
||||
let defaults = self.file_defaults();
|
||||
let detected = ide_vfs::detect_encoding(bytes, defaults.fallback_for(&absolute(path)));
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
editorconfig_label(editorconfig.as_ref(), detected.name(), bytes.is_ascii())
|
||||
.and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes()))
|
||||
.unwrap_or(detected)
|
||||
let configured = defaults.configured_encoding_for(&absolute(path));
|
||||
if configured.source == EncodingSource::File
|
||||
&& let Some(enc) = encoding_rs::Encoding::for_label(configured.label.as_bytes())
|
||||
&& !enc.decode_with_bom_removal(bytes).0.contains(char::REPLACEMENT_CHARACTER)
|
||||
{
|
||||
return enc;
|
||||
}
|
||||
ide_vfs::detect_encoding(bytes, configured_fallback(&defaults, path, editorconfig.as_ref()))
|
||||
}
|
||||
|
||||
fn editorconfig_for(&self, path: &Path, defaults: &FileDefaults) -> Option<EditorConfigProps> {
|
||||
@@ -353,11 +397,23 @@ impl Documents {
|
||||
self.editorconfig.resolve(&absolute(path))
|
||||
}
|
||||
|
||||
/// Fallback encoding for closed-file search; ASCII relabelling does not affect its text.
|
||||
pub fn configured_encoding_for(&self, path: &Path) -> Option<String> {
|
||||
let defaults = self.file_defaults();
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
let configured = defaults.configured_encoding_for(&absolute(path));
|
||||
if configured.source == EncodingSource::File {
|
||||
return Some(configured.label.to_owned());
|
||||
}
|
||||
configured_fallback(&defaults, path, editorconfig.as_ref()).map(|f| f.encoding.to_owned())
|
||||
}
|
||||
|
||||
/// Bounded closed-file snapshots use the same project defaults as open documents.
|
||||
pub fn load_file_bounded(&self, path: &Path, max_bytes: usize) -> IdeResult<ide_vfs::LoadedText> {
|
||||
let defaults = self.file_defaults();
|
||||
let mut loaded = ide_vfs::load_text_bounded(path, defaults.fallback_for(&absolute(path)), max_bytes)?;
|
||||
apply_editorconfig_charset(&mut loaded, self.editorconfig_for(path, &defaults).as_ref());
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
let mut loaded =
|
||||
ide_vfs::load_text_bounded(path, configured_fallback(&defaults, path, editorconfig.as_ref()), max_bytes)?;
|
||||
if !loaded.binary && defaults.native_to_ascii_for(path) {
|
||||
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
|
||||
}
|
||||
@@ -368,17 +424,30 @@ impl Documents {
|
||||
Self::load_as(path, encoding, self.native_to_ascii_for(path))
|
||||
}
|
||||
|
||||
/// Loads `path` as the settings say. `true`: decoded in the encoding chosen for this
|
||||
/// very file, as "Reload with Encoding" does, instead of detecting it.
|
||||
fn load_with_defaults(
|
||||
path: &Path,
|
||||
defaults: &FileDefaults,
|
||||
editorconfig: Option<&EditorConfigProps>,
|
||||
) -> IdeResult<ide_vfs::LoadedText> {
|
||||
let mut loaded = ide_vfs::load_text_with_fallback(path, defaults.fallback_for(&absolute(path)))?;
|
||||
apply_editorconfig_charset(&mut loaded, editorconfig);
|
||||
) -> IdeResult<(ide_vfs::LoadedText, bool)> {
|
||||
let path_abs = absolute(path);
|
||||
let configured = defaults.configured_encoding_for(&path_abs);
|
||||
if configured.source == EncodingSource::File {
|
||||
let loaded = Self::load_as(path, configured.label, defaults.native_to_ascii_for(path))?;
|
||||
// The bytes are not text in that encoding (the file changed outside the IDE):
|
||||
// open it as if nothing was chosen, rather than show and save broken characters.
|
||||
// A single-byte encoding decodes any bytes, so this only catches the others.
|
||||
if !loaded.text.contains(char::REPLACEMENT_CHARACTER) {
|
||||
return Ok((loaded, true));
|
||||
}
|
||||
}
|
||||
let fallback = configured_fallback(defaults, path, editorconfig);
|
||||
let mut loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
|
||||
if !loaded.binary && defaults.native_to_ascii_for(path) {
|
||||
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
|
||||
}
|
||||
Ok(loaded)
|
||||
Ok((loaded, false))
|
||||
}
|
||||
|
||||
pub fn file_defaults(&self) -> FileDefaults {
|
||||
@@ -460,7 +529,7 @@ impl Documents {
|
||||
}
|
||||
let defaults = self.file_defaults();
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
let loaded = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?;
|
||||
let (loaded, encoding_chosen) = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?;
|
||||
let editorconfig = editorconfig.filter(|_| !loaded.binary);
|
||||
let language = (self.detect_language)(path, loaded.text.lines().next());
|
||||
let ui_mode = (self.detect_ui_mode)(path, &language);
|
||||
@@ -476,8 +545,14 @@ impl Documents {
|
||||
// An empty file has nothing to detect: Code Style / File Encodings defaults apply.
|
||||
if empty_file && !loaded.binary {
|
||||
doc.set_line_ending(defaults.line_ending);
|
||||
encoding = defaults.encoding.clone();
|
||||
has_bom = defaults.encoding == "utf-8" && defaults.utf8_bom;
|
||||
if !encoding_chosen {
|
||||
let configured = defaults.configured_encoding_for(&absolute(path));
|
||||
encoding = match configured.source {
|
||||
EncodingSource::Folder => configured.label.to_owned(),
|
||||
_ => defaults.encoding.clone(),
|
||||
};
|
||||
has_bom = encoding == "utf-8" && defaults.utf8_bom;
|
||||
}
|
||||
}
|
||||
if let Some(ec) = &editorconfig {
|
||||
if let Some(le) = ec.end_of_line {
|
||||
@@ -485,6 +560,7 @@ impl Documents {
|
||||
}
|
||||
if let Some((enc, bom)) = ec.encoding()
|
||||
&& empty_file
|
||||
&& !encoding_chosen
|
||||
{
|
||||
(encoding, has_bom) = (enc.to_owned(), bom);
|
||||
}
|
||||
@@ -507,10 +583,12 @@ impl Documents {
|
||||
binary: loaded.binary,
|
||||
dirty: false,
|
||||
can_reload_encoding: true,
|
||||
encoding_chosen: false,
|
||||
encoding_chosen,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: loaded.mtime_ms,
|
||||
disk_len: disk_len(path),
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: None,
|
||||
@@ -584,9 +662,11 @@ impl Documents {
|
||||
dirty: false,
|
||||
can_reload_encoding,
|
||||
encoding_chosen: false,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: Some(uri.to_owned()),
|
||||
@@ -644,9 +724,11 @@ impl Documents {
|
||||
dirty: false,
|
||||
can_reload_encoding: false,
|
||||
encoding_chosen: false,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: Some(key.to_string_lossy().into_owned()),
|
||||
@@ -919,20 +1001,7 @@ impl Documents {
|
||||
/// on disk after this buffer was edited, which only an explicit save may overwrite.
|
||||
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
|
||||
self.with_doc(doc, |st| {
|
||||
// The watcher event for an external write may not have arrived yet: check the stamp now.
|
||||
if st.dirty
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& (ide_vfs::mtime_ms(&meta) != st.disk_mtime || meta.len() != st.disk_len)
|
||||
{
|
||||
st.disk_mtime = ide_vfs::mtime_ms(&meta);
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
|
||||
}
|
||||
self.check_disk_conflict(doc, st);
|
||||
if st.dirty && st.disk_conflict {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -940,6 +1009,29 @@ impl Documents {
|
||||
})
|
||||
}
|
||||
|
||||
/// An unsaved buffer whose file another program wrote: the watcher event may not have arrived
|
||||
/// yet, so check the stamp now.
|
||||
fn check_disk_conflict(&self, doc: DocId, st: &mut DocState) {
|
||||
if st.dirty
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& st.changed_on_disk(&meta)
|
||||
{
|
||||
self.disk_conflict(doc, st, &meta);
|
||||
}
|
||||
}
|
||||
|
||||
fn disk_conflict(&self, doc: DocId, st: &mut DocState, meta: &std::fs::Metadata) {
|
||||
st.disk_mtime = ide_vfs::mtime_ms(meta);
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
st.external_writes += 1;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
|
||||
}
|
||||
|
||||
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
|
||||
{
|
||||
if !st.dirty || st.uri.is_some() {
|
||||
@@ -1246,6 +1338,30 @@ impl Documents {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the encoding the user chose for `doc` is still to reach its file: the text was
|
||||
/// converted and not saved. It is then reported by [`Documents::take_saved_encodings`]
|
||||
/// once a save has written it.
|
||||
pub fn keep_encoding_when_saved(&self, doc: DocId) -> IdeResult<bool> {
|
||||
self.with_doc(doc, |st| {
|
||||
st.encoding_unsaved = st.dirty;
|
||||
Ok(st.dirty)
|
||||
})
|
||||
}
|
||||
|
||||
/// The files saved in the encoding their text was converted to since
|
||||
/// [`Documents::keep_encoding_when_saved`], with that encoding. Each is reported once.
|
||||
pub fn take_saved_encodings(&self) -> Vec<(PathBuf, String)> {
|
||||
let ids: Vec<DocId> = self.registry.lock().docs.keys().copied().collect();
|
||||
let saved = |id| {
|
||||
self.with_doc(id, |st| {
|
||||
let saved = st.encoding_unsaved && !st.dirty;
|
||||
st.encoding_unsaved &= st.dirty;
|
||||
Ok(saved.then(|| (st.path.clone(), st.encoding.clone())))
|
||||
})
|
||||
};
|
||||
ids.into_iter().filter_map(|id| saved(id).ok().flatten()).collect()
|
||||
}
|
||||
|
||||
/// Load Changes from Disk: drops the buffer's unsaved changes and reads its file again in
|
||||
/// the buffer's encoding, after the file changed on disk (`IdeEvent::DocDiskConflict`).
|
||||
pub fn discard_and_reload(&self, doc: DocId) -> IdeResult<()> {
|
||||
@@ -1255,6 +1371,7 @@ impl Documents {
|
||||
}
|
||||
let loaded = Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?;
|
||||
st.has_bom = loaded.has_bom;
|
||||
st.encoding_unsaved = false;
|
||||
self.replace_locked(doc, st, &loaded.text)?;
|
||||
st.synced(loaded.mtime_ms);
|
||||
self.set_dirty(doc, st, false);
|
||||
@@ -1411,12 +1528,10 @@ impl Documents {
|
||||
return Ok(());
|
||||
}
|
||||
if st.dirty {
|
||||
st.disk_mtime = mtime;
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc: id, path: st.path.to_string_lossy().into_owned() });
|
||||
if !st.changed_on_disk(&meta) {
|
||||
return Ok(());
|
||||
}
|
||||
self.disk_conflict(id, st, &meta);
|
||||
return Ok(());
|
||||
}
|
||||
let loaded = if force_clean {
|
||||
@@ -1427,7 +1542,7 @@ impl Documents {
|
||||
let loaded = if st.encoding_chosen {
|
||||
Self::load_as(&st.path, &st.encoding, native_to_ascii)?
|
||||
} else {
|
||||
Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())?
|
||||
Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())?.0
|
||||
};
|
||||
st.native_to_ascii = native_to_ascii;
|
||||
loaded
|
||||
|
||||
@@ -100,6 +100,8 @@ struct Record {
|
||||
paths: Vec<SavedPath>,
|
||||
documents: Vec<(DocId, DocState)>,
|
||||
after: Vec<WorkspaceEditPrecondition>,
|
||||
/// External writes seen by each open document as of `after` (see [`Documents::external_writes`]).
|
||||
writes: Vec<(DocId, u64)>,
|
||||
}
|
||||
|
||||
fn stale(path: &Path) -> IdeError {
|
||||
@@ -314,12 +316,7 @@ fn hash_disk(hash: &mut blake3::Hasher, path: &Path, unsaved: &HashMap<PathBuf,
|
||||
|
||||
/// The bytes saving `state` would write.
|
||||
fn saved_bytes(state: &DocState) -> IdeResult<Vec<u8>> {
|
||||
let text = state.doc.text_for_save();
|
||||
Ok(if state.native_to_ascii {
|
||||
ide_vfs::encode_properties_ascii(&text).into_bytes()
|
||||
} else {
|
||||
ide_vfs::encode(&text, &state.encoding, state.has_bom)?
|
||||
})
|
||||
state.bytes_for_save(&state.doc)
|
||||
}
|
||||
|
||||
/// A reverted edit may leave the dirty flag set even when all saved bytes match.
|
||||
@@ -374,6 +371,35 @@ impl Documents {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How many external writes each open document under `roots` has seen, with its path. An
|
||||
/// unsaved buffer's file is checked first, for a write the watcher hasn't reported yet.
|
||||
fn external_writes(&self, roots: &[PathBuf]) -> IdeResult<Vec<(DocId, u64, PathBuf)>> {
|
||||
let mut writes = Vec::new();
|
||||
for id in self.open_documents() {
|
||||
self.with_doc(id, |state| {
|
||||
if roots.iter().any(|p| text_path(&state.path).is_ok_and(|file| file.starts_with(p))) {
|
||||
self.check_disk_conflict(id, state);
|
||||
writes.push((id, state.external_writes, state.path.clone()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(writes)
|
||||
}
|
||||
|
||||
/// Fingerprints see an unsaved buffer in place of its file, so another program writing that
|
||||
/// file since the record was made shows only as a disk conflict. The IDE's own saves don't count.
|
||||
fn validate_external_writes(&self, record: &Record, roots: &[PathBuf]) -> IdeResult<()> {
|
||||
for (id, writes, path) in self.external_writes(roots)? {
|
||||
// A document opened since then starts at zero.
|
||||
let before = record.writes.iter().find(|(doc, _)| *doc == id).map_or(0, |(_, writes)| *writes);
|
||||
if writes != before {
|
||||
return Err(stale(&path));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_preconditions(&self, expected: &[WorkspaceEditPrecondition]) -> IdeResult<()> {
|
||||
let current = self.fingerprints(&expected.iter().map(|p| p.path.to_path_buf()).collect::<Vec<_>>())?;
|
||||
for (before, after) in expected.iter().zip(current) {
|
||||
@@ -474,6 +500,10 @@ impl Documents {
|
||||
Ok(after) => after,
|
||||
Err(error) => return Err(self.recover(record, error)),
|
||||
};
|
||||
record.writes = match self.external_writes(&roots) {
|
||||
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
|
||||
Err(error) => return Err(self.recover(record, error)),
|
||||
};
|
||||
if let Err(error) = fs::remove_file(record.directory.path().join("recovery")) {
|
||||
return Err(self.recover(record, error.into()));
|
||||
}
|
||||
@@ -573,6 +603,7 @@ impl Documents {
|
||||
paths,
|
||||
documents,
|
||||
after: Vec::new(),
|
||||
writes: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -819,7 +850,7 @@ impl Documents {
|
||||
let loaded = if state.encoding_chosen {
|
||||
Self::load_as(path, &state.encoding, native_to_ascii)?
|
||||
} else {
|
||||
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?
|
||||
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?.0
|
||||
};
|
||||
state.native_to_ascii = native_to_ascii;
|
||||
self.replace_locked(id, state, &loaded.text)?;
|
||||
@@ -874,8 +905,9 @@ impl Documents {
|
||||
if record.undone != redo {
|
||||
return Err(IdeError::invalid("the refactoring is already in the requested history state"));
|
||||
}
|
||||
self.validate_preconditions(&record.after)?;
|
||||
let roots = record.paths.iter().map(|p| p.path.clone()).collect::<Vec<_>>();
|
||||
self.validate_external_writes(record, &roots)?;
|
||||
self.validate_preconditions(&record.after)?;
|
||||
let mut current = self.backup(&roots)?;
|
||||
fs::write(current.directory.path().join("recovery"), b"history restore in progress")?;
|
||||
let _active = ActiveEdit::new(&self.workspace_edit_active);
|
||||
@@ -886,6 +918,10 @@ impl Documents {
|
||||
Ok(after) => after,
|
||||
Err(error) => return Err(self.recover(current, error)),
|
||||
};
|
||||
current.writes = match self.external_writes(&roots) {
|
||||
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
|
||||
Err(error) => return Err(self.recover(current, error)),
|
||||
};
|
||||
current.undone = !redo;
|
||||
current.created = record.created;
|
||||
if let Err(error) = fs::remove_file(current.directory.path().join("recovery")) {
|
||||
|
||||
@@ -34,7 +34,8 @@ pub struct EditorConfigProps {
|
||||
pub indent_size: Option<u32>,
|
||||
pub tab_width: Option<u32>,
|
||||
pub end_of_line: Option<LineEnding>,
|
||||
/// `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be` or `latin1`.
|
||||
/// `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be`, `latin1` or an encoding
|
||||
/// Settings › Editor › File Encodings lists (`iso-8859-15`, `windows-1252`, `gbk`, …).
|
||||
pub charset: Option<String>,
|
||||
pub trim_trailing_whitespace: Option<bool>,
|
||||
pub insert_final_newline: Option<bool>,
|
||||
@@ -48,17 +49,31 @@ impl EditorConfigProps {
|
||||
|
||||
/// WHATWG encoding label and BOM flag for `charset`.
|
||||
pub fn encoding(&self) -> Option<(&'static str, bool)> {
|
||||
Some(match self.charset.as_deref()? {
|
||||
"utf-8" => ("utf-8", false),
|
||||
"utf-8-bom" => ("utf-8", true),
|
||||
"utf-16le" => ("utf-16le", true),
|
||||
"utf-16be" => ("utf-16be", true),
|
||||
"latin1" => ("windows-1252", false),
|
||||
_ => return None,
|
||||
})
|
||||
charset_encoding(self.charset.as_deref()?)
|
||||
}
|
||||
}
|
||||
|
||||
/// WHATWG label and BOM flag of a lower-cased `charset` value: the five the spec
|
||||
/// defines and the other encodings Settings › Editor › File Encodings lists.
|
||||
fn charset_encoding(charset: &str) -> Option<(&'static str, bool)> {
|
||||
Some(match charset {
|
||||
"utf-8" => ("utf-8", false),
|
||||
"utf-8-bom" => ("utf-8", true),
|
||||
"utf-16le" => ("utf-16le", true),
|
||||
"utf-16be" => ("utf-16be", true),
|
||||
// WHATWG decodes ISO-8859-1 as windows-1252.
|
||||
"latin1" | "iso-8859-1" | "windows-1252" => ("windows-1252", false),
|
||||
"iso-8859-15" => ("iso-8859-15", false),
|
||||
"gbk" => ("gbk", false),
|
||||
"gb18030" => ("gb18030", false),
|
||||
"big5" => ("big5", false),
|
||||
"shift_jis" => ("shift_jis", false),
|
||||
"euc-kr" => ("euc-kr", false),
|
||||
"koi8-r" => ("koi8-r", false),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raw `key = value` pairs (keys lower-cased) in application order.
|
||||
type Pairs = Vec<(String, String)>;
|
||||
|
||||
@@ -200,8 +215,7 @@ fn props_from(map: &HashMap<String, String>) -> EditorConfigProps {
|
||||
Some("cr") => Some(LineEnding::Cr),
|
||||
_ => None,
|
||||
};
|
||||
let charset =
|
||||
get("charset").filter(|c| matches!(c.as_str(), "utf-8" | "utf-8-bom" | "utf-16le" | "utf-16be" | "latin1"));
|
||||
let charset = get("charset").filter(|c| charset_encoding(c).is_some());
|
||||
let max_line_length = get("max_line_length").and_then(|v| v.parse::<u32>().ok());
|
||||
EditorConfigProps {
|
||||
indent_style,
|
||||
@@ -406,4 +420,34 @@ mod tests {
|
||||
assert!(std::fs::read(r.join("new.l1")).unwrap().is_empty());
|
||||
assert!(create_file(&ec, &r.join("new.txt")).is_err(), "never truncates");
|
||||
}
|
||||
|
||||
/// The labels of `ENCODING_CHOICES` in `src/platform/editorSettings.ts`, copied by hand.
|
||||
#[test]
|
||||
fn charset_maps_the_listed_encodings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let r = tmp.path().canonicalize().unwrap();
|
||||
let listed = [
|
||||
("utf-8", "utf-8"),
|
||||
("utf-16le", "utf-16le"),
|
||||
("utf-16be", "utf-16be"),
|
||||
("gbk", "gbk"),
|
||||
("gb18030", "gb18030"),
|
||||
("big5", "big5"),
|
||||
("shift_jis", "shift_jis"),
|
||||
("euc-kr", "euc-kr"),
|
||||
("windows-1252", "windows-1252"),
|
||||
("iso-8859-1", "windows-1252"),
|
||||
("ISO-8859-15", "iso-8859-15"),
|
||||
("koi8-r", "koi8-r"),
|
||||
];
|
||||
let sections: String =
|
||||
listed.iter().enumerate().map(|(i, (c, _))| format!("[*.e{i}]\ncharset = {c}\n")).collect();
|
||||
write(&r.join(".editorconfig"), &format!("root = true\n{sections}"));
|
||||
let ec = EditorConfig::new();
|
||||
for (i, (charset, label)) in listed.iter().enumerate() {
|
||||
let encoding = ec.resolve(&r.join(format!("a.e{i}"))).and_then(|p| p.encoding());
|
||||
assert_eq!(encoding.map(|(label, _)| label), Some(*label), "charset = {charset}");
|
||||
assert!(encoding_rs::Encoding::for_label(label.as_bytes()).is_some(), "{label} is a WHATWG label");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
use ide_core::settings::Settings;
|
||||
use ide_text::LineEnding;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FileDefaults {
|
||||
@@ -21,6 +22,34 @@ pub struct FileDefaults {
|
||||
pub native_to_ascii: bool,
|
||||
pub editorconfig: bool,
|
||||
pub root: Option<PathBuf>,
|
||||
/// File Encodings mappings: a file's or a folder's path with its encoding. An entry
|
||||
/// naming the file itself is the user's choice for it; one naming a folder above it
|
||||
/// covers the files inside.
|
||||
pub mappings: Vec<(PathBuf, String)>,
|
||||
}
|
||||
|
||||
/// Where the encoding configured for a file comes from, strongest first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EncodingSource {
|
||||
File,
|
||||
Properties,
|
||||
Folder,
|
||||
Project,
|
||||
Global,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ConfiguredEncoding<'a> {
|
||||
pub label: &'a str,
|
||||
pub source: EncodingSource,
|
||||
}
|
||||
|
||||
impl<'a> ConfiguredEncoding<'a> {
|
||||
/// The label for files that are not valid UTF-8 or are plain ASCII (`None`: detect).
|
||||
pub fn fallback(self) -> Option<ide_vfs::Fallback<'a>> {
|
||||
(self.label != "utf-8")
|
||||
.then_some(ide_vfs::Fallback { encoding: self.label, ascii: self.source != EncodingSource::Properties })
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FileDefaults {
|
||||
@@ -51,20 +80,47 @@ impl FileDefaults {
|
||||
native_to_ascii: enc.native_to_ascii,
|
||||
editorconfig: style.editorconfig,
|
||||
root: root.map(Path::to_path_buf),
|
||||
mappings: root.map(|root| mappings(root, &enc.mappings)).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoding for `path` when it is not valid UTF-8 (`None`: detect). The project and
|
||||
/// global encodings also label plain ASCII; the properties encoding only decodes.
|
||||
pub fn fallback_for(&self, path: &Path) -> Option<ide_vfs::Fallback<'_>> {
|
||||
let (label, ascii) = if path.extension().is_some_and(|e| e == "properties") {
|
||||
(&self.properties_fallback, false)
|
||||
} else if self.root.as_ref().is_none_or(|r| path.starts_with(r)) {
|
||||
(&self.project_fallback, true)
|
||||
} else {
|
||||
(&self.global_fallback, true)
|
||||
/// The encoding the settings give `path`: the one chosen for the file itself, else the
|
||||
/// one it [inherits](Self::inherited_encoding_for).
|
||||
pub fn configured_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
|
||||
match self.mappings.iter().find(|(mapped, _)| path == mapped) {
|
||||
Some((_, label)) => ConfiguredEncoding { label, source: EncodingSource::File },
|
||||
None => self.inherited_encoding_for(path),
|
||||
}
|
||||
}
|
||||
|
||||
/// The encoding of `path` without a choice for the file itself: the `.properties`
|
||||
/// default, the nearest mapped folder above it, then the project's or the global one.
|
||||
pub fn inherited_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
|
||||
let folder = || {
|
||||
let above = self.mappings.iter().filter(|(mapped, _)| path != mapped && path.starts_with(mapped));
|
||||
above.max_by_key(|(mapped, _)| mapped.components().count())
|
||||
};
|
||||
(label != "utf-8").then_some(ide_vfs::Fallback { encoding: label, ascii })
|
||||
if path.extension().is_some_and(|e| e == "properties") {
|
||||
ConfiguredEncoding { label: &self.properties_fallback, source: EncodingSource::Properties }
|
||||
} else if let Some((_, label)) = folder() {
|
||||
ConfiguredEncoding { label, source: EncodingSource::Folder }
|
||||
} else {
|
||||
self.project_encoding_for(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's encoding for a file inside it, the global one for any other.
|
||||
pub fn project_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
|
||||
if self.root.as_ref().is_none_or(|r| path.starts_with(r)) {
|
||||
ConfiguredEncoding { label: &self.project_fallback, source: EncodingSource::Project }
|
||||
} else {
|
||||
ConfiguredEncoding { label: &self.global_fallback, source: EncodingSource::Global }
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoding for `path` when it is not valid UTF-8 or is plain ASCII (`None`: detect).
|
||||
pub fn fallback_for(&self, path: &Path) -> Option<ide_vfs::Fallback<'_>> {
|
||||
self.configured_encoding_for(path).fallback()
|
||||
}
|
||||
|
||||
pub fn native_to_ascii_for(&self, path: &Path) -> bool {
|
||||
@@ -81,6 +137,49 @@ impl FileDefaults {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `[editor.encodings.mappings]` key of `path`: its path inside the project `root`,
|
||||
/// with `/` separators. `None` for anything else.
|
||||
pub fn mapping_key(root: &Path, path: &Path) -> Option<String> {
|
||||
let segments: Option<Vec<&str>> = path
|
||||
.strip_prefix(root)
|
||||
.ok()?
|
||||
.components()
|
||||
.map(|c| match c {
|
||||
Component::Normal(name) => name.to_str(),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
segments.filter(|s| !s.is_empty()).map(|s| s.join("/"))
|
||||
}
|
||||
|
||||
/// The mapped paths under `root`. An entry whose key is not such a path, or whose value is
|
||||
/// not an encoding label, is left out.
|
||||
fn mappings(root: &Path, entries: &BTreeMap<String, String>) -> Vec<(PathBuf, String)> {
|
||||
let path_of = |key: &str| {
|
||||
let mut path = root.to_path_buf();
|
||||
for segment in key.strip_suffix('/').unwrap_or(key).split('/') {
|
||||
let mut components = Path::new(segment).components();
|
||||
let plain = matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none();
|
||||
if !plain || segment.contains('\\') {
|
||||
return None;
|
||||
}
|
||||
path.push(segment);
|
||||
}
|
||||
Some(path)
|
||||
};
|
||||
let mapping = |(key, label): (&String, &String)| {
|
||||
let label = normalize(label);
|
||||
match (path_of(key), ide_vfs::encode("", &label, false)) {
|
||||
(Some(path), Ok(_)) => Some((path, label)),
|
||||
_ => {
|
||||
tracing::warn!("ignoring the encoding mapping {key:?} = {label:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
entries.iter().filter_map(mapping).collect()
|
||||
}
|
||||
|
||||
fn normalize(label: &str) -> String {
|
||||
let l = label.trim().to_ascii_lowercase();
|
||||
match l.as_str() {
|
||||
@@ -108,4 +207,106 @@ mod tests {
|
||||
assert_eq!(d.fallback_for(Path::new("/p/a.properties")), fallback("iso-8859-1", false));
|
||||
assert!(d.new_file_bytes().is_empty(), "BOM only for UTF-8 new files");
|
||||
}
|
||||
|
||||
fn mapped(entries: &[(&str, &str)], root: &Path) -> FileDefaults {
|
||||
let mut s = Settings::default();
|
||||
s.editor.encodings.project = "gbk".into();
|
||||
s.editor.encodings.mappings = entries.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
FileDefaults::from_settings(&s, Some(root))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_resolve_a_file_before_its_folders_and_the_project() {
|
||||
let root = Path::new("/p");
|
||||
let d = mapped(
|
||||
&[
|
||||
("src", "ISO-8859-15"),
|
||||
("src/legacy", "koi8-r"),
|
||||
("src/legacy/A.java", "windows-1252"),
|
||||
("src/utf", "utf-8"),
|
||||
("src/app.properties", "big5"),
|
||||
],
|
||||
root,
|
||||
);
|
||||
let fallback = |rel: &str| d.fallback_for(&root.join(rel));
|
||||
assert_eq!(fallback("src/legacy/A.java"), Some(ide_vfs::Fallback { encoding: "windows-1252", ascii: true }));
|
||||
assert_eq!(
|
||||
fallback("src/legacy/B.java"),
|
||||
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true }),
|
||||
"the longest folder wins"
|
||||
);
|
||||
assert_eq!(fallback("src/main/C.java"), Some(ide_vfs::Fallback { encoding: "iso-8859-15", ascii: true }));
|
||||
assert_eq!(
|
||||
fallback("srcs/C.java"),
|
||||
Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }),
|
||||
"a folder is matched by whole path segments"
|
||||
);
|
||||
assert_eq!(fallback("other/C.java"), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
|
||||
assert_eq!(fallback("src/utf/D.java"), None, "a UTF-8 mapping does not fall through to the project");
|
||||
// `.properties` keep their own default inside a mapped folder; only their own entry overrides it.
|
||||
assert_eq!(
|
||||
fallback("src/legacy/b.properties"),
|
||||
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
|
||||
);
|
||||
assert_eq!(fallback("src/app.properties"), Some(ide_vfs::Fallback { encoding: "big5", ascii: true }));
|
||||
assert_eq!(d.fallback_for(Path::new("/elsewhere/src/C.java")), None);
|
||||
|
||||
let source = |rel: &str| d.configured_encoding_for(&root.join(rel)).source;
|
||||
assert_eq!(source("src/legacy/A.java"), EncodingSource::File);
|
||||
assert_eq!(source("src/legacy/B.java"), EncodingSource::Folder);
|
||||
assert_eq!(source("src/legacy/b.properties"), EncodingSource::Properties);
|
||||
assert_eq!(source("other/C.java"), EncodingSource::Project);
|
||||
assert_eq!(d.configured_encoding_for(Path::new("/elsewhere/C.java")).source, EncodingSource::Global);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_encoding_mappings_are_dropped() {
|
||||
let root = Path::new("/p");
|
||||
let d = mapped(
|
||||
&[
|
||||
("ok", "iso-8859-15"),
|
||||
("unknown", "klingon-1"),
|
||||
("", "koi8-r"),
|
||||
("/abs", "koi8-r"),
|
||||
("../up", "koi8-r"),
|
||||
("a/./b", "koi8-r"),
|
||||
("a//b", "koi8-r"),
|
||||
("back\\slash", "koi8-r"),
|
||||
],
|
||||
root,
|
||||
);
|
||||
assert_eq!(d.mappings, [(root.join("ok"), "iso-8859-15".to_owned())]);
|
||||
assert_eq!(d.fallback_for(&root.join("up/A.java")), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
|
||||
assert!(mapped(&[("ok", "iso-8859-15")], root).mappings.len() == 1);
|
||||
// Without a project there is nothing the paths are relative to.
|
||||
let mut s = Settings::default();
|
||||
s.editor.encodings.mappings.insert("ok".into(), "gbk".into());
|
||||
assert!(FileDefaults::from_settings(&s, None).mappings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_key_is_the_path_inside_the_project_with_slashes() {
|
||||
let root = Path::new("/p");
|
||||
assert_eq!(mapping_key(root, &root.join("src").join("a.b").join("A.java")).as_deref(), Some("src/a.b/A.java"));
|
||||
assert_eq!(mapping_key(root, Path::new("/elsewhere/A.java")), None);
|
||||
assert_eq!(mapping_key(root, root), None);
|
||||
assert_eq!(mapping_key(root, Path::new("untitled:Untitled-1")), None);
|
||||
let d = mapped(&[("src/a.b/A.java", "koi8-r")], root);
|
||||
assert_eq!(
|
||||
d.fallback_for(&root.join("src/a.b/A.java")),
|
||||
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_mapped_resolves_as_before() {
|
||||
let d = FileDefaults::from_settings(&Settings::default(), Some(Path::new("/p")));
|
||||
assert!(d.mappings.is_empty());
|
||||
assert_eq!(d.fallback_for(Path::new("/p/src/A.java")), None);
|
||||
assert_eq!(
|
||||
d.fallback_for(Path::new("/p/a.properties")),
|
||||
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
|
||||
);
|
||||
assert_eq!(d.configured_encoding_for(Path::new("/p/src/A.java")).label, "utf-8");
|
||||
}
|
||||
}
|
||||
@@ -392,8 +392,35 @@ impl SettingsStore {
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
|
||||
}
|
||||
self.set_segments(scope, key, &key.split('.').collect::<Vec<_>>(), value)
|
||||
}
|
||||
|
||||
/// Sets (`null`: removes) the `entry` of the map setting `map`, e.g. `editor.encodings.mappings`.
|
||||
/// Unlike a dotted key of [`set`](Self::set), `entry` may hold dots: a file path.
|
||||
pub fn set_map_entry(
|
||||
&self,
|
||||
scope: SettingsScope,
|
||||
map: &str,
|
||||
entry: &str,
|
||||
value: serde_json::Value,
|
||||
) -> IdeResult<Settings> {
|
||||
if scope == SettingsScope::Project
|
||||
&& let Some(setting) = user_only_setting(map, &serde_json::json!({ entry: value }))
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
|
||||
}
|
||||
let segments: Vec<&str> = map.split('.').chain([entry]).collect();
|
||||
self.set_segments(scope, &format!("{map}.{entry}"), &segments, value)
|
||||
}
|
||||
|
||||
fn set_segments(
|
||||
&self,
|
||||
scope: SettingsScope,
|
||||
key: &str,
|
||||
segments: &[&str],
|
||||
value: serde_json::Value,
|
||||
) -> IdeResult<Settings> {
|
||||
let file = self.file(scope).ok_or_else(|| IdeError::invalid("no project is open"))?.to_path_buf();
|
||||
let segments: Vec<&str> = key.split('.').collect();
|
||||
if segments.iter().any(|s| s.is_empty()) {
|
||||
return Err(IdeError::invalid(format!("invalid settings key {key:?}")));
|
||||
}
|
||||
@@ -421,7 +448,7 @@ impl SettingsStore {
|
||||
.parse()
|
||||
.map_err(|e| IdeError::invalid(format!("{} is not valid TOML; fix it first: {e}", file.display())))?;
|
||||
let new_value = if value.is_null() { None } else { Some(json_to_toml(&value)?) };
|
||||
set_in_document(&mut doc, &segments, new_value, map_entry);
|
||||
set_in_document(&mut doc, segments, new_value, map_entry);
|
||||
let new_text = doc.to_string();
|
||||
|
||||
// Validate the resulting stack before touching the disk.
|
||||
@@ -792,6 +819,52 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_entry_named_by_a_path_is_written_under_its_table() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cfg = tmp.path().join("cfg");
|
||||
let proj = tmp.path().join("proj");
|
||||
let file = proj.join(".openidea/settings.toml");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, "[editor]\ntabSize = 8 # wide\n").unwrap();
|
||||
let store = SettingsStore::load(&cfg, Some(&proj));
|
||||
|
||||
let key = "editor.encodings.mappings";
|
||||
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
|
||||
assert_eq!(s.editor.encodings.mappings.get("src/a.b/A.java").map(String::as_str), Some("iso-8859-15"));
|
||||
assert_eq!(s.editor.tab_size, 8);
|
||||
let written =
|
||||
"[editor]\ntabSize = 8 # wide\n\n[editor.encodings.mappings]\n\"src/a.b/A.java\" = \"iso-8859-15\"\n";
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
|
||||
|
||||
// Setting it again changes nothing; another entry joins the table; `null` removes one.
|
||||
store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
|
||||
store.set_map_entry(SettingsScope::Project, key, "web", json!("gbk")).unwrap();
|
||||
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", Json::Null).unwrap();
|
||||
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("web".into(), "gbk".into())]);
|
||||
|
||||
for (map, entry) in [("editor.encodings.nope", "a"), (key, "")] {
|
||||
let err = store.set_map_entry(SettingsScope::Project, map, entry, json!("gbk")).unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_encoding_mapping_that_is_not_a_label_does_not_drop_the_project_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let proj = tmp.path().join("proj");
|
||||
std::fs::create_dir_all(proj.join(".openidea")).unwrap();
|
||||
std::fs::write(
|
||||
proj.join(".openidea/settings.toml"),
|
||||
"[editor]\ntabSize = 8\n[editor.encodings.mappings]\nsrc = \"gbk\"\ncount = 5\n",
|
||||
)
|
||||
.unwrap();
|
||||
let s = SettingsStore::load(&tmp.path().join("cfg"), Some(&proj)).effective();
|
||||
assert_eq!(s.editor.tab_size, 8);
|
||||
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("src".into(), "gbk".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_console_log_colors() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -350,6 +350,61 @@ fn autosave_checks_the_disk_before_the_watcher_reports_a_change() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Writes `bytes` with an mtime clearly after the current one, whatever the filesystem's granularity.
|
||||
fn rewrite_later(path: &Path, bytes: &[u8]) {
|
||||
let mtime = fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
|
||||
fs::write(path, bytes).unwrap();
|
||||
fs::File::options().write(true).open(path).unwrap().set_modified(mtime).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewriting_the_same_bytes_is_no_disk_conflict() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
// A touch, or a tool rewriting the file unchanged: only the mtime moves.
|
||||
rewrite_later(&path, b"alpha\nbeta\n");
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
|
||||
assert!(!f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_ignores_a_rewrite_of_the_same_bytes_before_the_watcher_reports_it() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
rewrite_later(&path, b"alpha\nbeta\n");
|
||||
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
|
||||
}
|
||||
|
||||
/// Opens `bytes`, edits the buffer, then rewrites the file as `external` (same text, other bytes).
|
||||
fn assert_other_bytes_conflict(name: &str, bytes: &[u8], external: &[u8]) {
|
||||
let f = fixture();
|
||||
let path = f.root.join(name);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap();
|
||||
rewrite_later(&path, external);
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert!(!f.docs.autosave(info.id).unwrap(), "{name}: autosave overwrote other bytes of the same text");
|
||||
assert_eq!(fs::read(&path).unwrap(), external);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_text_in_other_bytes_is_still_a_disk_conflict() {
|
||||
assert_other_bytes_conflict("crlf.txt", b"alpha\nbeta\n", b"alpha\r\nbeta\r\n");
|
||||
assert_other_bytes_conflict("bom.txt", b"alpha\n", b"\xEF\xBB\xBFalpha\n");
|
||||
// Same length: only the byte comparison tells them apart.
|
||||
assert_other_bytes_conflict("utf16.txt", b"\xFF\xFEa\x00\n\x00", b"\xFE\xFF\x00a\x00\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
|
||||
let f = fixture();
|
||||
@@ -1512,3 +1567,298 @@ fn undo_back_to_the_disk_text_reloads_on_checkout() {
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert_eq!(f.docs.snapshot(id).unwrap().text, "checked out\n");
|
||||
}
|
||||
|
||||
fn project_encoding(f: &Fixture, label: &str) {
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = label.into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
}
|
||||
|
||||
fn latin9_editorconfig(f: &Fixture) {
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_applies_to_an_existing_ascii_file_over_the_project_encoding() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "iso-8859-15");
|
||||
f.docs.edit(doc.id, doc.version, change(0, 0, "// ação €\n")).unwrap();
|
||||
f.docs.save(doc.id).unwrap();
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), b"// a\xe7\xe3o \xa4\nclass A {}\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_decodes_a_legacy_file_over_the_project_encoding() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
let bytes = b"// a\xe7\xe3o \xa4\n";
|
||||
fs::write(&path, bytes).unwrap();
|
||||
|
||||
assert_eq!(f.docs.detect_encoding(&path, bytes), encoding_rs::ISO_8859_15);
|
||||
for loaded in [f.docs.load_file(&path).unwrap(), f.docs.load_file_bounded(&path, 1024).unwrap()] {
|
||||
assert_eq!((loaded.text.as_str(), loaded.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_survives_a_reload_from_disk() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
fs::write(&path, b"class A { int changed; }\n").unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
|
||||
let reloaded = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_without_a_usable_charset_leaves_the_encoding_alone() {
|
||||
let open = |project: Option<&str>, editorconfig: &str, enabled: bool| {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
if let Some(project) = project {
|
||||
defaults.project_fallback = project.into();
|
||||
}
|
||||
defaults.editorconfig = enabled;
|
||||
f.docs.set_file_defaults(defaults);
|
||||
fs::write(f.root.join(".editorconfig"), format!("root = true\n[*.java]\n{editorconfig}\n")).unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
f.docs.open(&path).unwrap().encoding
|
||||
};
|
||||
|
||||
assert_eq!(open(None, "indent_size = 2", true), "utf-8", "nothing configured");
|
||||
assert_eq!(open(None, "charset = ebcdic", true), "utf-8", "unknown charset");
|
||||
assert_eq!(open(Some("iso-8859-15"), "indent_size = 2", true), "iso-8859-15", "no charset: the project's");
|
||||
assert_eq!(open(Some("iso-8859-15"), "charset = ebcdic", true), "iso-8859-15", "unknown charset: the project's");
|
||||
assert_eq!(open(Some("iso-8859-15"), "charset = gbk", false), "iso-8859-15", "EditorConfig support is off");
|
||||
assert_eq!(open(Some("iso-8859-15"), "charset = utf-16le", true), "iso-8859-15", "UTF-16 is detected, not assumed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_text_without_a_bom_keeps_utf16_under_a_utf8_charset() {
|
||||
let f = fixture();
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, ide_vfs::encode("class A {}\n", "utf-16le", false).unwrap()).unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("class A {}\n", "utf-16le"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_utf8_text_keeps_utf8_under_a_legacy_charset() {
|
||||
let f = fixture();
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, "// ação\n").unwrap();
|
||||
|
||||
assert_eq!(f.docs.open(&path).unwrap().encoding, "utf-8");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_utf8_charset_survives_a_reload_from_disk() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
fs::write(&path, b"class A { int changed; }\n").unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
|
||||
let reloaded = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "utf-8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_wins_over_the_properties_encoding() {
|
||||
let f = fixture();
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.properties]\ncharset = iso-8859-15\n").unwrap();
|
||||
let path = f.root.join("messages.properties");
|
||||
fs::write(&path, b"price=10 \xa4\n").unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("price=10 €\n", "iso-8859-15"));
|
||||
assert_eq!(f.docs.detect_encoding(&path, b"price=10\n"), encoding_rs::ISO_8859_15);
|
||||
assert_eq!(f.docs.detect_encoding(&f.root.join("unmatched.txt"), b"price=10\n"), encoding_rs::UTF_8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_editorconfig_support_off_stops_the_charset_on_reload() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.editorconfig = false;
|
||||
f.docs.set_file_defaults(defaults);
|
||||
|
||||
fs::write(&path, b"class A { int changed; }\n").unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
|
||||
assert_eq!(f.docs.snapshot(doc.id).unwrap().encoding, "gbk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_declared_utf8_that_is_not_utf8_is_decoded_with_the_project_encoding() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
/// `[editor.encodings.mappings]` as the host hands it over: project paths with their labels.
|
||||
fn encoding_mappings(f: &Fixture, entries: &[(&str, &str)]) {
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.mappings = entries.iter().map(|(rel, label)| (in_root(f, rel), (*label).to_owned())).collect();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
}
|
||||
|
||||
fn in_root(f: &Fixture, rel: &str) -> PathBuf {
|
||||
rel.split('/').fold(f.root.clone(), |path, segment| path.join(segment))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_file_survives_closing_and_reopening_it() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, "// ação\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
f.docs.set_encoding(doc.id, "iso-8859-15", true).unwrap();
|
||||
let chosen = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!(chosen.text, "// ação\n");
|
||||
f.docs.close(doc.id);
|
||||
|
||||
encoding_mappings(&f, &[("A.java", "iso-8859-15")]);
|
||||
let reopened = f.docs.open(&path).unwrap();
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", chosen.text.as_str()));
|
||||
// A later change on disk is read in the remembered encoding too.
|
||||
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
let reloaded = f.docs.snapshot(reopened.id).unwrap();
|
||||
assert_eq!((reloaded.encoding.as_str(), reloaded.text.as_str()), ("iso-8859-15", "// ação €\n"));
|
||||
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "iso-8859-15", "closed-file readers agree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_file_to_utf8_holds_in_a_latin_project() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
encoding_mappings(&f, &[("A.java", "utf-8")]);
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
f.docs.edit(doc.id, doc.version, change(0, 0, "// é\n")).unwrap();
|
||||
f.docs.save(doc.id).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), "// é\nclass A {}\n".as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_file_beats_editorconfig_and_a_folder_mapping_loses_to_it() {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\nend_of_line = crlf\n").unwrap();
|
||||
fs::create_dir(f.root.join("src")).unwrap();
|
||||
for name in ["src/A.java", "src/B.java", "src/notes.txt", "other.txt"] {
|
||||
fs::write(in_root(&f, name), b"plain ascii\n").unwrap();
|
||||
}
|
||||
fs::write(in_root(&f, "src/new.txt"), b"").unwrap();
|
||||
fs::write(in_root(&f, "src/latin.txt"), b"a\xe7\xe3o \xa4\n").unwrap();
|
||||
encoding_mappings(&f, &[("src", "iso-8859-15"), ("src/A.java", "koi8-r")]);
|
||||
let open = |name: &str| f.docs.open(&in_root(&f, name)).unwrap();
|
||||
|
||||
let file = open("src/A.java");
|
||||
assert_eq!(file.encoding, "koi8-r", "the file's own mapping beats .editorconfig");
|
||||
assert_eq!(file.line_ending, LineEnding::CrLf, ".editorconfig still sets the rest");
|
||||
assert_eq!(open("src/B.java").encoding, "windows-1252", ".editorconfig beats the folder mapping");
|
||||
assert_eq!(open("src/notes.txt").encoding, "iso-8859-15", "the folder mapping beats the project encoding");
|
||||
assert_eq!(open("src/new.txt").encoding, "iso-8859-15", "a new file takes its folder's encoding");
|
||||
assert_eq!(open("other.txt").encoding, "gbk");
|
||||
let latin = open("src/latin.txt");
|
||||
assert_eq!((latin.encoding.as_str(), latin.text.as_str()), ("iso-8859-15", "ação €\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_folder_is_left_out_where_editorconfig_sets_the_charset() {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\n").unwrap();
|
||||
fs::create_dir(f.root.join("src")).unwrap();
|
||||
let path = in_root(&f, "src/B.java");
|
||||
fs::write(&path, b"// \xd6\xd0\n").unwrap();
|
||||
let unmapped = f.docs.open(&path).unwrap();
|
||||
f.docs.close(unmapped.id);
|
||||
|
||||
encoding_mappings(&f, &[("src", "koi8-r")]);
|
||||
let mapped = f.docs.open(&path).unwrap();
|
||||
assert_eq!((mapped.encoding, mapped.text), (unmapped.encoding, unmapped.text));
|
||||
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "windows-1252", "closed-file readers agree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_a_file_no_longer_decodes_in_falls_back_to_detection() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"// a\xe7\xe3o\n").unwrap();
|
||||
encoding_mappings(&f, &[("A.java", "utf-8")]);
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!((doc.encoding.as_str(), doc.text.as_str()), ("iso-8859-15", "// ação\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_encoding_mappings_files_open_as_before() {
|
||||
let f = fixture();
|
||||
let settings = ide_core::settings::Settings::default();
|
||||
f.docs.set_file_defaults(ide_workspace::FileDefaults::from_settings(&settings, Some(&f.root)));
|
||||
assert!(f.docs.file_defaults().mappings.is_empty());
|
||||
for (name, bytes) in [
|
||||
("ascii.java", &b"class A {}\n"[..]),
|
||||
("utf8.java", "// ação\n".as_bytes()),
|
||||
("latin.java", &b"// a\xe7\xe3o de gra\xe7a, cora\xe7\xe3o\n"[..]),
|
||||
("empty.java", &b""[..]),
|
||||
] {
|
||||
let path = f.root.join(name);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let detected = ide_vfs::load_text(&path).unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!((doc.encoding, doc.text), (detected.encoding, detected.text), "{name}");
|
||||
}
|
||||
}
|
||||
@@ -138,17 +138,18 @@ fn rollback_keeps_a_disk_conflict_of_an_unsaved_buffer() {
|
||||
let info = docs.open(&first).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
|
||||
// An external write the undo record still accepts (same bytes, new mtime) under the unsaved buffer.
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(&first, "old\n").unwrap();
|
||||
// An external write under the unsaved buffer, warned about before the refactoring.
|
||||
let mtime = std::fs::metadata(&first).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
|
||||
std::fs::write(&first, "ext\n").unwrap();
|
||||
std::fs::File::options().write(true).open(&first).unwrap().set_modified(mtime).unwrap();
|
||||
docs.on_disk_changed(std::slice::from_ref(&first));
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
let snap = docs.snapshot(info.id).unwrap();
|
||||
assert_eq!(snap.text, "own\n");
|
||||
assert!(snap.dirty);
|
||||
assert!(!docs.autosave(info.id).unwrap(), "autosave must not overwrite the external change");
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "ext\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -240,6 +241,21 @@ fn undo_keeps_the_encoding_chosen_for_a_file_opened_after_the_edit() {
|
||||
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("abcé", "windows-1252"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_the_editorconfig_charset_of_a_file_opened_after_the_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(tmp.path().join(".editorconfig"), "root = true\n[*.txt]\ncharset = iso-8859-15\n").unwrap();
|
||||
let path = tmp.path().join("legacy.txt");
|
||||
std::fs::write(&path, b"abc\xA4").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
let info = docs.open(&path).unwrap();
|
||||
assert_eq!((info.text.as_str(), info.encoding.as_str()), ("new€", "iso-8859-15"));
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
let snapshot = docs.snapshot(info.id).unwrap();
|
||||
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("abc€", "iso-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_document_version_rejects_the_whole_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -425,6 +441,80 @@ fn undo_refuses_later_changes_and_retains_the_record() {
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
/// An open file with unsaved typing, refactored: its buffer holds `new`, the disk still `old`.
|
||||
fn refactored_unsaved(path: &Path) -> (Documents, Arc<Mutex<Vec<IdeEvent>>>, ide_core::DocId) {
|
||||
std::fs::write(path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(path).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(path, "new")], ..Default::default() }).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "new\n");
|
||||
(docs, events, info.id)
|
||||
}
|
||||
|
||||
fn type_text(docs: &Documents, id: ide_core::DocId, text: &str) {
|
||||
let snapshot = docs.snapshot(id).unwrap();
|
||||
let to = snapshot.text.encode_utf16().count() as u32;
|
||||
docs.edit(id, snapshot.version, ChangeSet { changes: vec![TextChange { from: 0, to, insert: text.into() }] })
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_an_external_write_under_an_unsaved_buffer() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
// Not reported by a watcher: undo itself notices the write.
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert_eq!(docs.undo_workspace_edit(undo_id(&events)).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "new\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_after_saving_and_undoing_the_typing_is_allowed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
type_text(&docs, id, "typed later\n");
|
||||
docs.save(id).unwrap();
|
||||
// The typing undone: the buffer is back to the refactoring's text, the IDE's own save on disk.
|
||||
type_text(&docs, id, "new\n");
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_allows_a_disk_conflict_from_before_the_refactoring() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
type_text(&docs, info.id, "own\n");
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert!(!docs.autosave(info.id).unwrap(), "the external write is a disk conflict");
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redo_keeps_an_external_write_made_after_the_undo() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
let undo = undo_id(&events);
|
||||
docs.undo_workspace_edit(undo).unwrap();
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert_eq!(docs.redo_workspace_edit(undo).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_resource_operations_and_binary_deletion_are_undoable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,7 +16,7 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
|
||||
| Claude Code | `claude` | `claude` |
|
||||
| Codex | `codex app-server` | `codex login` |
|
||||
| Gemini CLI | `gemini --experimental-acp` | `gemini` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot login` |
|
||||
| Cursor | `cursor-agent acp` | `cursor-agent login` |
|
||||
| OpenCode | `opencode acp` | `opencode auth login` |
|
||||
| Qwen Code | `qwen --experimental-acp` | `qwen` |
|
||||
@@ -132,6 +132,8 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
For a built-in ACP agent launched directly, such as OMP, **Launch › Additional arguments** appends arguments to its existing launch command. Separate arguments with spaces and quote values that contain spaces. **Apply** saves the arguments for the next process launch; the command preview shows the saved result. **Reset additional arguments** clears just this field, leaving the executable, environment and any hand-written `args` in the agent file alone.
|
||||
|
||||
For **GitHub Copilot**, **Sign In › GitHub account** selects which GitHub account's Copilot subscription is used for AI model requests—either Copilot CLI's own default login (**Sign In…**) or any account signed into GitHub CLI (**Add account…**). **New Tasks** model options are loaded for the authenticated account after sign-in or **Apply**.
|
||||
|
||||
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
|
||||
### External MCP servers
|
||||
|
||||
@@ -114,6 +114,8 @@ All folding commands are also in **Code › Folding**. Fold regions come from th
|
||||
|
||||
Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too.
|
||||
|
||||
Java has an **Imports** tab for IntelliSort-style options: **Class count to use import with '\*'** switches to a wildcard import once that many classes of one package are used, and **Names count to use static import with '\*'** does the same for statically imported names (999 keeps single imports). Both are passed through to the Java language server, whose defaults are 5 and 3, as in IDEA.
|
||||
|
||||
To format on every save, enable **Reformat code** (and optionally **Optimize imports**) in **Settings › Tools › Actions on Save**. Trailing spaces and the final line break on save are set in **Settings › Editor › General**, section **Save Files**.
|
||||
|
||||
## Tabs
|
||||
@@ -145,17 +147,21 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
|
||||
|
||||
## View options
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
| ---------------------- | ----- | --------------- |
|
||||
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll to Top** | — | — |
|
||||
| **Scroll to Bottom** | — | — |
|
||||
| Action | macOS | Windows / Linux |
|
||||
| ------------------------------------- | ----- | --------------- |
|
||||
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll Up and Move if Necessary** | — | — |
|
||||
| **Scroll Down and Move if Necessary** | — | — |
|
||||
| **Move Up and Scroll** | — | — |
|
||||
| **Move Down and Scroll** | — | — |
|
||||
| **Scroll to Top** | — | — |
|
||||
| **Scroll to Bottom** | — | — |
|
||||
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll Up and Move if Necessary** and **Scroll Down and Move if Necessary** also move the view by one line, but bring a caret the view doesn't show to its first or last line. **Move Up and Scroll** and **Move Down and Scroll** move the caret one line and the view with it, so the caret stays in the same place on screen; their **with Selection** variants select as they go. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
|
||||
|
||||
- **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**.
|
||||
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
|
||||
|
||||
@@ -9,9 +9,11 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
|
||||
|
||||
<Steps>
|
||||
<Step title="Install gh">
|
||||
Install the GitHub CLI. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`, then in
|
||||
`/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux) or `C:\Program Files\GitHub CLI\gh.exe`
|
||||
(Windows).
|
||||
Install the GitHub CLI, either from OpenIDEA's **Install GitHub CLI** button (in the **Pull Requests** tool window,
|
||||
**Clone Repository › GitHub**, **Settings › Agents › GitHub Copilot**, or **Settings › Languages & Frameworks ›
|
||||
Language Servers › Other Tools**) or manually. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`
|
||||
(including IDE-managed tools), then in `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux)
|
||||
or `C:\Program Files\GitHub CLI\gh.exe` (Windows).
|
||||
</Step>
|
||||
<Step title="Sign in">
|
||||
Run `gh auth login` in a terminal. If you open the **Pull Requests** tool window while signed out, it shows **Not
|
||||
@@ -22,6 +24,14 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
|
||||
The project needs a Git remote on `github.com`. With one GitHub remote, OpenIDEA connects to it automatically. With
|
||||
several, the tool window asks you to pick a **Repository**; the choice is remembered per project. To switch later,
|
||||
use **Change Repository or Account…** in the tool window's `⋮` menu.
|
||||
|
||||
When multiple `github.com` accounts are signed into `gh`, **Automatic** uses `gh`'s own active account without
|
||||
setting `GH_TOKEN`. In **Settings › Version Control › GitHub** and in the **Pull Requests** header, OpenIDEA can
|
||||
suggest a matching account for the repository (**Use `<login>` for this project**) or let you choose one
|
||||
explicitly (saved in `.openidea/settings.toml`). Choosing an account passes its `GH_TOKEN` to processes started in
|
||||
that project (terminals, agents, Git, Pull Requests, and run configurations) without changing your global
|
||||
`gh auth switch` selection.
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ Scratch files are saved in a `scratches` folder in OpenIDEA's application data d
|
||||
| Windows | `%APPDATA%\ai.l0ng.openidea\scratches` |
|
||||
| Linux | `~/.local/share/ai.l0ng.openidea/scratches` |
|
||||
|
||||
They are listed under **Scratches** in the Project view, where you can open, rename and delete them like other files.
|
||||
They are listed under **Scratches** in the Project view, where you can open, rename and delete them like other files. To hide that node, turn off **Show Scratches and Consoles** in the Project view's **Options › Appearance** menu; the **Scratches and Consoles** view still lists them.
|
||||
|
||||
Because a scratch file is outside every project, some language servers give it only syntax checks; completion and navigation may be limited. A banner at the top of the editor says so when the server reports it.
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ A test run opens a tab in the **Run** tool window with the test tree next to the
|
||||
- Double-click, `Enter` or `F4` jumps to the test's source (**Jump to Source**).
|
||||
- **Show Passed** and **Show Ignored** filter the tree. Passed tests are hidden by default; the filters are remembered.
|
||||
- **⋯ › Test Runner Options › Select First Failed Test When Finished** selects the first failed test, with its output, when a run ends. It is off by default.
|
||||
- **⋯ › Test Runner Options › Track Running Test** selects each test, with its output, as it starts while the run is in progress. It is on by default.
|
||||
- Right-click a test or a selection for **Run '…'**, **Debug '…'** and **Jump to Source**.
|
||||
- For an assertion failure with expected and actual values, **Show Diff** opens them side by side.
|
||||
- For a Jest or Vitest snapshot mismatch, **Update Snapshot** (on the test or its file or suite, above the failure output, and in the gutter run menu) reruns just those tests with `-u`, so only their snapshots are rewritten.
|
||||
|
||||
@@ -90,7 +90,7 @@ Settings › Appearance & Behavior › System Settings, unless noted.
|
||||
| `dateFormat.overrideSystem` | `false` | **Override system date and time format** (Date Formats page). |
|
||||
| `dateFormat.pattern` | `"dd.MM.yyyy"` | Date pattern with `dd`, `MM`, `MMM`, `yy`, `yyyy`. |
|
||||
| `dateFormat.use24Hour` | `true` | 24-hour time. |
|
||||
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago". |
|
||||
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago" (in lists with time, in the annotate gutter as the day alone). |
|
||||
|
||||
### `[appearance]`
|
||||
|
||||
@@ -140,6 +140,16 @@ Settings › Appearance & Behavior › Appearance, unless noted.
|
||||
|
||||
Sub-tables such as `[editor.general]`, `[editor.appearance]`, `[editor.completion]`, `[editor.tabs]`, `[editor.codeStyle]` and `[editor.encodings]` hold the options of the matching Editor pages.
|
||||
|
||||
`[editor.encodings.mappings]` in a project's `.openidea/settings.toml` gives a file or a folder its own encoding. Keys are paths relative to the project, with `/` separators. Choosing an encoding in the status bar adds the file here; after **Convert**, once the file is saved.
|
||||
|
||||
```toml
|
||||
[editor.encodings.mappings]
|
||||
"src/main/java" = "iso-8859-15" # every file in the folder
|
||||
"web/legacy/index.jsp" = "windows-1252"
|
||||
```
|
||||
|
||||
A file's own entry wins over `.editorconfig`. A folder's entry applies where `.editorconfig` sets no `charset`, and wins over the project encoding; the nearest folder wins. An entry with an unknown encoding or a path outside the project is ignored.
|
||||
|
||||
### `[files]`
|
||||
|
||||
| Key | Default | Description |
|
||||
|
||||
@@ -16,7 +16,7 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
|
||||
| Claude Code | `claude` | `claude` |
|
||||
| Codex | `codex app-server` | `codex login` |
|
||||
| Gemini CLI | `gemini --experimental-acp` | `gemini` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot login` |
|
||||
| Cursor | `cursor-agent acp` | `cursor-agent login` |
|
||||
| OpenCode | `opencode acp` | `opencode auth login` |
|
||||
| Qwen Code | `qwen --experimental-acp` | `qwen` |
|
||||
@@ -132,6 +132,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。
|
||||
|
||||
对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。完成登录或点击**应用**后,**新任务**会加载该已验证账号对应的可用模型列表。
|
||||
|
||||
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
|
||||
### 外部 MCP 服务器
|
||||
|
||||
@@ -145,17 +145,21 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
## 显示选项
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| -------------- | ----- | --------------- |
|
||||
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **滚动到中央** | `⌃L` | `Ctrl+M` |
|
||||
| **向上滚动** | — | `Ctrl+Up` |
|
||||
| **向下滚动** | — | `Ctrl+Down` |
|
||||
| **滚动到顶部** | — | — |
|
||||
| **滚动到底部** | — | — |
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| ------------------------------ | ----- | --------------- |
|
||||
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **滚动到中央** | `⌃L` | `Ctrl+M` |
|
||||
| **向上滚动** | — | `Ctrl+Up` |
|
||||
| **向下滚动** | — | `Ctrl+Down` |
|
||||
| **向上滚动并在必要时移动光标** | — | — |
|
||||
| **向下滚动并在必要时移动光标** | — | — |
|
||||
| **向上移动并滚动** | — | — |
|
||||
| **向下移动并滚动** | — | — |
|
||||
| **滚动到顶部** | — | — |
|
||||
| **滚动到底部** | — | — |
|
||||
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**向上移动并滚动** 和 **向下移动并滚动** 把光标移动一行,视图随之滚动同样的距离,光标在屏幕上的位置保持不变;对应的 **并选择** 版本边移动边选择。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
|
||||
|
||||
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
|
||||
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
|
||||
@@ -9,9 +9,10 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub:
|
||||
|
||||
<Steps>
|
||||
<Step title="安装 gh">
|
||||
安装 GitHub CLI。OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`,以及
|
||||
`/opt/homebrew/bin`、`/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub
|
||||
CLI\gh.exe`(Windows)中查找。
|
||||
安装 GitHub CLI:可以直接点击 OpenIDEA 里的 **安装 GitHub CLI** 按钮(位于 **拉取请求** 工具窗口、**克隆仓库 ›
|
||||
GitHub**、**设置 › 智能体 › GitHub Copilot** 或 **设置 › 语言与框架 › 语言服务器 › 其他工具**),也可以手动安装。
|
||||
OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`(包含 IDE 管理的工具目录),以及 `/opt/homebrew/bin`、
|
||||
`/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub CLI\gh.exe`(Windows)中查找。
|
||||
</Step>
|
||||
<Step title="登录">
|
||||
在终端运行 `gh auth login`。未登录时打开 **拉取请求** 工具窗口,会显示 **未登录 GitHub** 和 **运行 gh auth login**
|
||||
@@ -20,6 +21,9 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub:
|
||||
<Step title="打开带 GitHub 远程的项目">
|
||||
项目需要有一个指向 `github.com` 的 Git 远程。只有一个 GitHub 远程时自动连接;有多个时,工具窗口会让你选择
|
||||
**仓库**,选择按项目记住。之后要切换,可在工具窗口的 `⋮` 菜单中选 **更改仓库或账户…**。
|
||||
|
||||
当 `gh` 中登录了多个 `github.com` 账户时,**自动**模式沿用 `gh` 当前的活动账户,不会在项目环境中设置 `GH_TOKEN`。在 **设置 › 版本控制 › GitHub** 和 **拉取请求** 标题栏中,OpenIDEA 会根据仓库远程提示匹配的账户(**对此项目使用 `<login>`**),也可以手动为项目指定账户(保存在 `.openidea/settings.toml`)。显式选择账户后,OpenIDEA 会将该账户的 `GH_TOKEN` 传递给此项目中启动的进程(终端、智能体、Git、拉取请求和运行配置),而不会改动全局的 `gh auth switch` 状态。
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ description: "在项目之外保留临时文件,并在 TODO 工具窗口中汇
|
||||
| Windows | `%APPDATA%\ai.l0ng.openidea\scratches` |
|
||||
| Linux | `~/.local/share/ai.l0ng.openidea/scratches` |
|
||||
|
||||
它们列在项目视图的 **临时文件** 节点下,可以像其他文件一样打开、重命名和删除。
|
||||
它们列在项目视图的 **临时文件** 节点下,可以像其他文件一样打开、重命名和删除。要隐藏这个节点,可在项目视图的 **选项 › 外观** 菜单中关闭 **显示临时文件和控制台**;**临时文件和控制台** 视图仍会列出它们。
|
||||
|
||||
临时文件不属于任何项目,所以部分语言服务器只对它做语法检查,补全和导航可能受限;服务器报告这种情况时,编辑器顶部会显示横幅说明。
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配
|
||||
- 双击、按 `Enter` 或 `F4` 跳到测试源码(**跳转到源代码**)。
|
||||
- **显示已通过** 和 **显示已忽略** 用于筛选测试树。默认隐藏已通过的测试,筛选状态会被记住。
|
||||
- **⋯ › 测试运行器选项 › 完成后选中第一个失败的测试** 会在运行结束时选中第一个失败的测试并显示它的输出。默认关闭。
|
||||
- **⋯ › 测试运行器选项 › 跟踪正在运行的测试** 会在运行过程中,每个测试开始时选中它并显示它的输出。默认开启。
|
||||
- 右键单个测试或多选后,可以 **运行 '…'**、**调试 '…'** 或 **跳转到源代码**。
|
||||
- 对于带有期望值和实际值的断言失败,**显示差异** 会把两者并排对比。
|
||||
- 对于 Jest 或 Vitest 的快照不匹配,**更新快照**(在测试或其文件、套件上,失败输出上方,以及边栏运行菜单中)只用 `-u` 重新运行这些测试,只改写它们的快照。
|
||||
|
||||
@@ -90,7 +90,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
|
||||
| `dateFormat.overrideSystem` | `false` | **覆盖系统日期和时间格式**(日期格式页)。 |
|
||||
| `dateFormat.pattern` | `"dd.MM.yyyy"` | 日期格式,可用 `dd`、`MM`、`MMM`、`yy`、`yyyy`。 |
|
||||
| `dateFormat.use24Hour` | `true` | 使用 24 小时制。 |
|
||||
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间。 |
|
||||
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间(列表中带时间,注解装订区域仅显示日期)。 |
|
||||
|
||||
### `[appearance]`
|
||||
|
||||
@@ -140,6 +140,16 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
|
||||
|
||||
`[editor.general]`、`[editor.appearance]`、`[editor.completion]`、`[editor.tabs]`、`[editor.codeStyle]`、`[editor.encodings]` 等子表保存对应编辑器页面的选项。
|
||||
|
||||
项目 `.openidea/settings.toml` 中的 `[editor.encodings.mappings]` 为单个文件或文件夹指定编码。键是相对于项目的路径,使用 `/` 分隔。在状态栏中选择编码时,该文件会被添加到这里;使用 **Convert** 时,在保存文件之后添加。
|
||||
|
||||
```toml
|
||||
[editor.encodings.mappings]
|
||||
"src/main/java" = "iso-8859-15" # 文件夹中的所有文件
|
||||
"web/legacy/index.jsp" = "windows-1252"
|
||||
```
|
||||
|
||||
文件自身的条目优先于 `.editorconfig`。文件夹的条目在 `.editorconfig` 未设置 `charset` 时生效,并优先于项目编码;最近的文件夹优先。编码未知或路径在项目之外的条目会被忽略。
|
||||
|
||||
### `[files]`
|
||||
|
||||
| 键 | 默认值 | 说明 |
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { AgentConfigOption, AgentProvider, CopilotAuthStatus } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openAgents(page: Page) {
|
||||
const settings = "/src/features/settings/model/staging.ts";
|
||||
await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("agents.list"), settings);
|
||||
return page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
}
|
||||
|
||||
test("unifies Copilot sign-in, gates per-account models on auth, and supports in-IDE account switching", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
let savedAccount = "";
|
||||
let cliAuthenticated = false;
|
||||
let ghAccounts: { login: string; active: boolean }[] = [{ login: "alice", active: true }];
|
||||
let loginChannel: unknown = null;
|
||||
|
||||
const personalModel: AgentConfigOption = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
category: "model",
|
||||
current: "claude-sonnet-4.5",
|
||||
defaultValue: "claude-sonnet-4.5",
|
||||
via: "option",
|
||||
values: [
|
||||
{ value: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", description: null },
|
||||
{ value: "gpt-5", name: "GPT-5", description: null },
|
||||
],
|
||||
};
|
||||
const workModel: AgentConfigOption = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
category: "model",
|
||||
current: "gemini-4-neon",
|
||||
defaultValue: "gemini-4-neon",
|
||||
via: "option",
|
||||
values: [
|
||||
{ value: "gemini-4-neon", name: "Gemini 4 Neon", description: null },
|
||||
{ value: "gpt-5", name: "GPT-5", description: null },
|
||||
],
|
||||
};
|
||||
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
settings_get_global: () => ({}),
|
||||
agent_registry_list: () => ({ agents: [], warning: null }),
|
||||
agent_providers: () => {
|
||||
const env: Record<string, string> = { COPILOT_TELEMETRY_OPTOUT: "1" };
|
||||
if (savedAccount) env.OPENIDEA_COPILOT_GITHUB_ACCOUNT = savedAccount;
|
||||
const provider: AgentProvider = {
|
||||
id: "copilot",
|
||||
name: "GitHub Copilot",
|
||||
command: "copilot --headless --no-auto-update --stdio",
|
||||
program: "/tools/copilot",
|
||||
args: ["--headless", "--no-auto-update", "--stdio"],
|
||||
defaultProgram: "copilot",
|
||||
defaultArgs: ["--headless", "--no-auto-update", "--stdio"],
|
||||
loginHint: "Run `copilot login` in a terminal.",
|
||||
commandOverridden: false,
|
||||
commandEditable: false,
|
||||
commandReadOnlyReason: "registry",
|
||||
installed: true,
|
||||
canSignIn: true,
|
||||
canCheckCliUpdate: false,
|
||||
env,
|
||||
config: [workModel],
|
||||
thoughtLevels: {},
|
||||
commands: [],
|
||||
source: { kind: "registry", version: "1.0.116", update: null },
|
||||
};
|
||||
return [provider];
|
||||
},
|
||||
agent_copilot_auth_status: (): CopilotAuthStatus => ({
|
||||
authenticated: cliAuthenticated,
|
||||
login: cliAuthenticated ? "alice" : null,
|
||||
authType: cliAuthenticated ? "oauth" : null,
|
||||
statusMessage: cliAuthenticated ? "alice" : null,
|
||||
ghInstalled: true,
|
||||
ghAccounts,
|
||||
}),
|
||||
agent_refresh_models: () => ({
|
||||
provider: "copilot",
|
||||
config: [savedAccount === "alice-work" ? workModel : personalModel],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: Date.now(),
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
}),
|
||||
agent_set_env: ({ env }: { env: Record<string, string> }) => {
|
||||
savedAccount = env.OPENIDEA_COPILOT_GITHUB_ACCOUNT ?? "";
|
||||
return null;
|
||||
},
|
||||
agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
|
||||
loginChannel = onEvent;
|
||||
setTimeout(() => {
|
||||
window.__ipc.send(loginChannel, { type: "output", data: "Opening GitHub in browser...\r\n" });
|
||||
cliAuthenticated = true;
|
||||
window.__ipc.send(loginChannel, { type: "exited", code: 0 });
|
||||
}, 40);
|
||||
return { id: 1, pid: 1001, title: "copilot" };
|
||||
},
|
||||
agent_gh_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
|
||||
loginChannel = onEvent;
|
||||
setTimeout(() => {
|
||||
window.__ipc.send(loginChannel, { type: "output", data: "Logged in as alice-work\r\n" });
|
||||
ghAccounts = [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
];
|
||||
window.__ipc.send(loginChannel, { type: "exited", code: 0 });
|
||||
}, 40);
|
||||
return { id: 2, pid: 1002, title: "gh" };
|
||||
},
|
||||
term_resize: () => null,
|
||||
term_write: () => null,
|
||||
term_kill: () => null,
|
||||
});
|
||||
});
|
||||
|
||||
const dialog = await openAgents(page);
|
||||
const signIn = dialog.getByRole("region", { name: "Sign In" });
|
||||
const newTasks = dialog.getByRole("region", { name: "New Tasks" });
|
||||
const launch = dialog.getByRole("region", { name: "Launch" });
|
||||
|
||||
// Unified Sign In section holds GitHub account; Launch has no duplicate account control.
|
||||
const accountSelect = signIn.getByRole("button", { name: "GitHub account" });
|
||||
await expect(accountSelect).toContainText("Copilot CLI default (not signed in)");
|
||||
await expect(launch.getByRole("button", { name: "GitHub account" })).toHaveCount(0);
|
||||
|
||||
// Unauthenticated state hides stale cached models.
|
||||
await expect(newTasks.getByText("Sign in above to view and choose models available for this account.")).toBeVisible();
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0);
|
||||
|
||||
// Sign In runs in-IDE PTY and unlocks personal account models.
|
||||
await signIn.getByRole("button", { name: "Sign In…" }).click();
|
||||
await expect(page.getByRole("dialog", { name: "Sign In to GitHub Copilot" })).toHaveCount(0);
|
||||
await expect(accountSelect).toContainText("Copilot CLI default (alice)");
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Claude Sonnet 4.5)");
|
||||
|
||||
// Add account runs gh auth login in-IDE, auto-selects alice-work, and gates models on Apply.
|
||||
await signIn.getByRole("button", { name: "Add account…" }).click();
|
||||
await expect(page.getByRole("dialog", { name: "Sign In to GitHub CLI" })).toHaveCount(0);
|
||||
await expect(accountSelect).toContainText("alice-work");
|
||||
await expect(newTasks.getByText("Click Apply to load the models available for the selected account.")).toBeVisible();
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0);
|
||||
|
||||
// Applying loads the new account's subscription models.
|
||||
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Gemini 4 Neon)");
|
||||
expect(await ipcCalls(page, "agent_set_env")).toEqual([
|
||||
{
|
||||
id: "copilot",
|
||||
env: {
|
||||
COPILOT_TELEMETRY_OPTOUT: "1",
|
||||
OPENIDEA_COPILOT_GITHUB_ACCOUNT: "alice-work",
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -209,3 +209,48 @@ test("opens a folded process run with the keyboard and jumps back to the latest
|
||||
await expect(jump).toBeHidden();
|
||||
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(40);
|
||||
});
|
||||
|
||||
test("paints earlier turns past folded process runs longer than ENTRY_BATCH", async ({ page }) => {
|
||||
const longRun = (prefix: string, count: number): AgentEntry[] =>
|
||||
Array.from({ length: count }, (_, i): AgentEntry => ({
|
||||
type: "tool",
|
||||
id: `${prefix}-${i}`,
|
||||
kind: i % 3 === 0 ? "edit" : i % 2 === 0 ? "execute" : "read",
|
||||
title: `tool ${prefix}-${i}`,
|
||||
status: "completed",
|
||||
locations: [],
|
||||
output: null,
|
||||
diffs: [],
|
||||
}));
|
||||
const longProcessEntries: AgentEntry[] = [
|
||||
{ type: "user", text: "Earliest request before long runs", attachments: [], steered: false },
|
||||
{ type: "agent", text: "Initial reply" },
|
||||
{ type: "user", text: "Split PR into three focused PRs", attachments: [], steered: false },
|
||||
...longRun("batch-a", 75),
|
||||
{ type: "agent", text: "Interim status update" },
|
||||
...longRun("batch-b", 75),
|
||||
];
|
||||
await page.goto("/");
|
||||
await page.getByRole("tree", { name: "Project" }).waitFor();
|
||||
await page.evaluate(
|
||||
async ({ task, entries }) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const store = await import(path);
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([[task.id, { ...task, status: "running" }]]),
|
||||
entries: new Map([[task.id, entries]]),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, entries: longProcessEntries },
|
||||
);
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
await expect(stream.getByText("Earliest request before long runs")).toBeVisible();
|
||||
await expect(stream.getByText("Split PR into three focused PRs")).toBeVisible();
|
||||
await expect(stream.getByText("Interim status update")).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { AgentConfigOption, AgentProvider } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openAgents(page: Page) {
|
||||
const settings = "/src/features/settings/model/staging.ts";
|
||||
await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("agents.list"), settings);
|
||||
return page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
}
|
||||
|
||||
test("signs in to an agent in an IDE terminal dialog and refreshes its model catalog", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
const model: AgentConfigOption = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
category: "model",
|
||||
current: "claude-sonnet-4.5",
|
||||
defaultValue: "claude-sonnet-4.5",
|
||||
via: "option",
|
||||
values: [
|
||||
{ value: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", description: null },
|
||||
{ value: "gpt-5", name: "GPT-5", description: null },
|
||||
],
|
||||
};
|
||||
let signedIn = false;
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
settings_get_global: () => ({}),
|
||||
agent_registry_list: () => ({ agents: [], warning: null }),
|
||||
agent_providers: () => {
|
||||
const provider: AgentProvider = {
|
||||
id: "claude",
|
||||
name: "Claude Code",
|
||||
command: "claude",
|
||||
program: "/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/claude/claude",
|
||||
args: [],
|
||||
defaultProgram: "claude",
|
||||
defaultArgs: [],
|
||||
loginHint:
|
||||
"Run `'/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/claude/claude'` in a terminal and sign in.",
|
||||
commandOverridden: false,
|
||||
commandEditable: false,
|
||||
commandReadOnlyReason: "registry",
|
||||
installed: true,
|
||||
canSignIn: true,
|
||||
canCheckCliUpdate: false,
|
||||
env: {},
|
||||
config: signedIn ? [model] : [],
|
||||
thoughtLevels: {},
|
||||
commands: [],
|
||||
source: { kind: "registry", version: "1.0.0", update: null },
|
||||
};
|
||||
return [provider];
|
||||
},
|
||||
agent_refresh_models: () => ({
|
||||
provider: "claude",
|
||||
config: signedIn ? [model] : [],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: signedIn ? Date.now() : null,
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
}),
|
||||
agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
|
||||
setTimeout(() => {
|
||||
window.__ipc.send(onEvent, { type: "output", data: "Opening Claude in browser...\r\n" });
|
||||
signedIn = true;
|
||||
window.__ipc.send(onEvent, { type: "exited", code: 0 });
|
||||
}, 40);
|
||||
return { id: 1, pid: 1001, title: "claude" };
|
||||
},
|
||||
term_resize: () => null,
|
||||
term_write: () => null,
|
||||
term_kill: () => null,
|
||||
});
|
||||
});
|
||||
|
||||
const dialog = await openAgents(page);
|
||||
const signIn = dialog.getByRole("region", { name: "Sign In" });
|
||||
const newTasks = dialog.getByRole("region", { name: "New Tasks" });
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0);
|
||||
|
||||
await signIn.getByRole("button", { name: "Sign In…" }).click();
|
||||
await expect(page.getByRole("dialog", { name: "Sign In to Claude Code" })).toHaveCount(0);
|
||||
await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Claude Sonnet 4.5)");
|
||||
expect((await ipcCalls(page, "agent_login_spawn")).map((c) => c.id)).toEqual(["claude"]);
|
||||
});
|
||||
@@ -23,7 +23,7 @@ test("file tab actions are grouped around the tab the menu was opened from", asy
|
||||
}
|
||||
return groups;
|
||||
});
|
||||
expect(groups.slice(0, 4)).toEqual([
|
||||
expect(groups.slice(0, 5)).toEqual([
|
||||
[
|
||||
"Close",
|
||||
"Close Other Tabs",
|
||||
@@ -32,6 +32,7 @@ test("file tab actions are grouped around the tab the menu was opened from", asy
|
||||
"Close Tabs to the Left",
|
||||
"Close Tabs to the Right",
|
||||
],
|
||||
["File Color"],
|
||||
["Copy Path/Reference…"],
|
||||
["Split Right", "Split and Move Right", "Split Down", "Split and Move Down"],
|
||||
["Pin Tab", "Open in New Window", "Configure Editor Tabs…"],
|
||||
|
||||
@@ -65,7 +65,8 @@ test("Git Log commit choices fit their rows and navigate by keyboard after filte
|
||||
await expect(filter).toBeFocused();
|
||||
await expect(options).toHaveCount(2);
|
||||
const before = (await chooser.boundingBox())!;
|
||||
expect(before.height).toBeLessThan(200);
|
||||
// Two rows under the title, and the Close button a macOS sheet without buttons gets.
|
||||
expect(before.height).toBeLessThan(260);
|
||||
const first = options.filter({ hasText: firstSubject });
|
||||
const subject = first.getByText(firstSubject, { exact: true });
|
||||
const author = first.getByText("Priya Kapoor", { exact: true });
|
||||
|
||||
@@ -4,10 +4,11 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
await page.setViewportSize({ width: 1080, height: 700 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const path = "/dev/acme-api/status.svg";
|
||||
const path = "/dev/acme-api/status.png";
|
||||
// A black 128 × 96 PNG.
|
||||
const image =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>';
|
||||
window.__ipc.handlers.fs_read_image = () => "data:image/svg+xml," + encodeURIComponent(image);
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAIAAAABgCAYAAADVenpJAAAAtklEQVR42u3SQREAAAyDMPyb3oQ0jxjgqDqmiWAADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABkAEA2AADIABMAAGwAAYgAUPjHPSwnYk55QAAAAASUVORK5CYII=";
|
||||
window.__ipc.handlers.fs_read_image = () => "data:image/png;base64," + image;
|
||||
window.__ipc.handlers.fs_probe = () => ({ size: 4096, binary: false, tooLarge: false });
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ contributions);
|
||||
@@ -18,9 +19,8 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
const zoomIn = toolbar.getByRole("button", { name: "Zoom In", exact: true });
|
||||
const actualSize = toolbar.getByRole("button", { name: "Actual Size", exact: true });
|
||||
const chessboard = toolbar.getByRole("button", { name: "Show Chessboard", exact: true });
|
||||
const showText = toolbar.getByRole("button", { name: "Open as Text", exact: true });
|
||||
const dimensions = toolbar.getByText(/128\s*×\s*96/);
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("img", { name: "status.png", exact: true })).toBeVisible();
|
||||
await expect(dimensions).toBeVisible();
|
||||
const wideHeight = (await toolbar.boundingBox())!.height;
|
||||
|
||||
@@ -31,8 +31,7 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
expect((await toolbar.boundingBox())!.height).toBeGreaterThan(wideHeight);
|
||||
expect((await dimensions.boundingBox())!.y).toBeGreaterThan((await zoomIn.boundingBox())!.y);
|
||||
await expect(dimensions).toHaveCSS("font-size", "13px");
|
||||
await expect(showText).toHaveCSS("white-space", "nowrap");
|
||||
for (const item of [zoomIn, actualSize, chessboard, showText, dimensions]) {
|
||||
for (const item of [zoomIn, actualSize, chessboard, dimensions]) {
|
||||
await expect(item).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
await expect(toolbar.getByText("4.0 KB", { exact: true })).toBeVisible();
|
||||
@@ -43,6 +42,33 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
|
||||
await expect(toolbar.getByText("100%", { exact: true })).toBeVisible();
|
||||
await chessboard.click();
|
||||
await expect(chessboard).toHaveAttribute("aria-pressed", "false");
|
||||
await showText.click();
|
||||
});
|
||||
|
||||
test("an SVG file opens as its source with the image beside it", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
window.__ipc.handlers.fs_probe = () => ({ size: 96, binary: false, tooLarge: false });
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ contributions);
|
||||
await editorService().openFile("/dev/acme-api/status.svg");
|
||||
});
|
||||
const toolbar = page.getByRole("toolbar", { name: "Image viewer", exact: true });
|
||||
// Not an SVG yet: the preview says so, and draws the source once it is typed.
|
||||
await expect(page.getByText("The SVG source is not valid.", { exact: true })).toBeVisible();
|
||||
await page.locator(".cm-content").click();
|
||||
await page.keyboard.press("Meta+A");
|
||||
await page.keyboard.insertText(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>',
|
||||
);
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await expect(toolbar.getByText(/128\s*×\s*96/)).toBeVisible();
|
||||
await expect(toolbar.getByRole("button", { name: "Open as Text", exact: true })).toHaveCount(0);
|
||||
|
||||
const layout = page.getByRole("toolbar", { name: "SVG editor layout", exact: true });
|
||||
await layout.getByRole("button", { name: "Preview Only", exact: true }).click();
|
||||
await expect(page.locator(".cm-content")).toBeHidden();
|
||||
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
|
||||
await layout.getByRole("button", { name: "Editor Only", exact: true }).click();
|
||||
await expect(toolbar).toHaveCount(0);
|
||||
await expect(page.locator(".cm-content")).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { GhProjectAccountStatus } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
async function openGithubSettings(page: Page) {
|
||||
const settings = "/src/features/settings/model/staging.ts";
|
||||
await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("vcs.github"), settings);
|
||||
return page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
}
|
||||
|
||||
test("suggests and configures a project-scoped GitHub account in Settings › Version Control › GitHub", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
let configuredAccount = "";
|
||||
const makeStatus = (): GhProjectAccountStatus => ({
|
||||
ghInstalled: true,
|
||||
accounts: [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
],
|
||||
configuredAccount,
|
||||
effectiveAccount: configuredAccount || "alice",
|
||||
suggestedAccount: configuredAccount ? null : "alice-work",
|
||||
});
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
settings_get_global: () => ({}),
|
||||
gh_project_account_status: () => makeStatus(),
|
||||
gh_set_project_account: ({ account }: { account: string }) => {
|
||||
configuredAccount = account;
|
||||
return makeStatus();
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const dialog = await openGithubSettings(page);
|
||||
const select = dialog.getByRole("button", { name: "GitHub account" });
|
||||
await expect(select).toContainText("Automatic (alice)");
|
||||
await expect(
|
||||
dialog.getByText("Uses GitHub CLI's active account without setting GH_TOKEN in the project environment."),
|
||||
).toBeVisible();
|
||||
|
||||
await dialog.getByRole("button", { name: "Use alice-work for this project" }).click();
|
||||
await expect(select).toContainText("alice-work");
|
||||
await expect(
|
||||
dialog.getByText(
|
||||
"Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).",
|
||||
),
|
||||
).toBeVisible();
|
||||
expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]);
|
||||
});
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.53",
|
||||
"version": "0.1.54",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Runs _N_ persistent, isolated GitHub Actions runners via Docker Compose on a single Docker named volume (`runner-persist`) without requiring repository admin Personal Access Tokens.
|
||||
|
||||
In `.github/workflows/ci.yml` and `.github/workflows/language-smoke.yml`, every Linux job routes to `["self-hosted", "openidea-selfhosted"]` on trusted events (`push`, `merge_group`, `workflow_dispatch`, and same-repo pull requests) while the `SELFHOSTED_RUNNERS` repository variable is `true`. Fork pull requests, and every run while the variable is unset, fall back to `ubuntu-latest`. Workflows triggered on `pull_request_target` with write-scoped `GITHUB_TOKEN` permissions (`pr-check.yml`, `cancel-on-close.yml`) stay on `ubuntu-latest`.
|
||||
In `.github/workflows/ci.yml` and `.github/workflows/language-smoke.yml`, Linux jobs that compile Rust route to `["self-hosted", "openidea-selfhosted"]` and the short jobs that don't (`changes`, `rust-checks`, `deny`, `catalog`) route to `["self-hosted", "openidea-selfhosted-light"]` on trusted events (`push`, `merge_group`, `workflow_dispatch`, and same-repo pull requests) while the `SELFHOSTED_RUNNERS` repository variable is `true`. Fork pull requests, and every run while the variable is unset, fall back to `ubuntu-latest`. `frontend` and `e2e` always run on `ubuntu-latest`: they are CPU-bound and finish faster there. Workflows triggered on `pull_request_target` with write-scoped `GITHUB_TOKEN` permissions (`pr-check.yml`, `cancel-on-close.yml`) stay on `ubuntu-latest`.
|
||||
|
||||
> **Availability requirement:** GitHub Actions `runs-on` cannot fall back to GitHub-hosted runners when no matching self-hosted runner is online; jobs stay queued until one connects. Set `SELFHOSTED_RUNNERS=true` (**Settings → Secrets and variables → Actions → Variables**) only once the runners are up, and delete it before taking the host down.
|
||||
|
||||
@@ -86,13 +86,15 @@ Run all commands from `scripts/selfhost-runner/`:
|
||||
|
||||
You can pass variables on the command line or place them in a local `.env` file in this directory (git-ignored):
|
||||
|
||||
| Variable | Default | Description |
|
||||
| -------------------- | ------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `RUNNER_COUNT` | `4` | Number of concurrent runner replicas |
|
||||
| `RUNNER_NAME_PREFIX` | `openidea-runner` | Runner name prefix; registers as `<prefix>-1`, `<prefix>-2`, … |
|
||||
| `RUNNER_LABELS` | `openidea-selfhosted` | Comma-separated labels attached to each runner |
|
||||
| `REPO_URL` | `https://github.com/l0ng-ai/openidea` | Target GitHub repository URL |
|
||||
| `RUNNER_TOKEN` | _(empty)_ | One-time registration token (required only when registering new slots) |
|
||||
| Variable | Default | Description |
|
||||
| -------------------- | --------------------- | -------------------------------------------------------------- |
|
||||
| `RUNNER_COUNT` | `4` | Number of concurrent runner replicas |
|
||||
| `RUNNER_NAME_PREFIX` | `openidea-runner` | Runner name prefix; registers as `<prefix>-1`, `<prefix>-2`, … |
|
||||
| `RUNNER_LABELS` | `openidea-selfhosted` | Comma-separated labels attached to each runner |
|
||||
|
||||
A host with little disk can take only the lightweight jobs with `RUNNER_LABELS=openidea-selfhosted-light`; a host that should take both kinds uses `RUNNER_LABELS=openidea-selfhosted,openidea-selfhosted-light`.
|
||||
| `REPO_URL` | `https://github.com/l0ng-ai/openidea` | Target GitHub repository URL |
|
||||
| `RUNNER_TOKEN` | _(empty)_ | One-time registration token (required only when registering new slots) |
|
||||
|
||||
## Troubleshooting & Tips
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ services:
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
replicas: ${RUNNER_COUNT:-4}
|
||||
# Docker's 64 MB default /dev/shm starves Chromium: e2e pages render slowly enough to time out.
|
||||
shm_size: 2gb
|
||||
|
||||
environment:
|
||||
RUNNER_SCOPE: repo
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
/// Forking recorded native agent sessions into new tasks (API 1.18). Requires
|
||||
/// the `agents` capability. The session must belong to the invoking window's
|
||||
/// project and have been recorded in `cwd`; the host builds the fork invocation
|
||||
/// and names the fork's id for claude (codex assigns its own).
|
||||
interface agents {
|
||||
use types.{error};
|
||||
/// Fork the recorded session `session-id` of `agent` (a native provider,
|
||||
/// `claude` or `codex`) into a new task in the open project, returning the
|
||||
/// new task id. `cwd` must be where the session was recorded. The first
|
||||
/// turn continues the recording as the agent's own fork.
|
||||
fork-session: func(agent: string, session-id: string, cwd: string) -> result<string, error>;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
|
||||
interface endpoints-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
@@ -39,20 +39,52 @@ interface events {
|
||||
/// 0-based UTF-16 positions, when the caret moves in the focused editor;
|
||||
/// `settled` is true for the final position once the caret rests, so costly
|
||||
/// work waits for it; it requires `events`) through `other`.
|
||||
/// API 1.18 also delivers `project-closed` (JSON project root string) and
|
||||
/// `watched-files-changed` (see `watch-paths`) through `other`.
|
||||
/// Kinds: `file-opened`, `file-saved`, `document-changed` (versioned UTF-16
|
||||
/// replacements from explicit path subscriptions), `websocket-ready`
|
||||
/// (a host-owned connection has messages to drain), `caret-moved`, `files-changed` (batched disk changes
|
||||
/// as `other`, with created/modified/removed path lists in JSON), `editor-focused` (the focused editor
|
||||
/// changed), `vcs-changed` (a repository's state changed: commit,
|
||||
/// checkout, fetch…), `action-performed` (an IDE action ran) and
|
||||
/// checkout, fetch…), `action-performed` (an IDE action ran),
|
||||
/// `project-closed` (a project closed) and
|
||||
/// `scheduled` (the `on-schedule` period elapsed); later IDEs add more,
|
||||
/// and an IDE that doesn't know one fails with `invalid`.
|
||||
/// Requires `events` (`events.input` for `action-performed`).
|
||||
subscribe: func(kind: string) -> result<_, error>;
|
||||
/// Options for file path subscriptions (API 1.18).
|
||||
record subscription-options {
|
||||
globs: list<string>,
|
||||
/// Debounce quiet window in milliseconds before delivering changes (API 1.18).
|
||||
/// When omitted, changes are delivered immediately without debounce.
|
||||
debounce-ms: option<u32>,
|
||||
}
|
||||
|
||||
/// Replaces this kind's subscription with project-relative globs (OR).
|
||||
/// Empty globs pause delivery; `subscribe` restores unfiltered delivery.
|
||||
/// Kinds: file-opened, file-saved, document-changed, files-changed. Requires `events`.
|
||||
subscribe-paths: func(kind: string, globs: list<string>) -> result<_, error>;
|
||||
/// Replaces this kind's subscription with project-relative globs and options (API 1.18).
|
||||
/// Kinds: file-opened, file-saved, document-changed, files-changed. Requires `events`.
|
||||
subscribe-paths-with-options: func(kind: string, options: subscription-options) -> result<_, error>;
|
||||
/// Watches files and directories outside the invoking window's project (API 1.18),
|
||||
/// replacing what this plugin watched for that project; an empty list stops.
|
||||
/// Each path is absolute (or `~/…`), exists, and is readable through an
|
||||
/// `fs.read:<path>` grant, checked where it really is: a link out of the grant
|
||||
/// is `denied` (naming the capability). Paths inside the project are `invalid`
|
||||
/// (they come with `files-changed`); at most 32. A file is watched where it is,
|
||||
/// across atomic saves, removal and re-creation; a directory for its own entries,
|
||||
/// not recursively. Changes arrive as `watched-files-changed` events through
|
||||
/// `other`: JSON {project, created, modified, removed} like `files-changed`,
|
||||
/// debounced and coalesced, so read the files again rather than replaying
|
||||
/// steps; a rename is the old path removed and the new one created. A removed
|
||||
/// watched directory is reported once and no longer watched: call again once
|
||||
/// it exists. Watches end when the project or its window closes, or the plugin
|
||||
/// stops (disabled, updated, or a grant revoked); idle reclaim keeps them, and
|
||||
/// an event activates the plugin again. Nothing is watched over the network:
|
||||
/// remote files need the plugin's own refresh. Requires `events` and a call
|
||||
/// that serves a window's project (a command or event).
|
||||
watch-paths: func(paths: list<string>) -> result<_, error>;
|
||||
unsubscribe: func(kind: string);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
@@ -74,6 +74,57 @@ interface syntax-provider {
|
||||
folding: func(language: string, text: string) -> list<fold>;
|
||||
}
|
||||
|
||||
/// Optional Run Anything (Ctrl Ctrl) entries and command lines for the prefixes
|
||||
/// the plugin declares under `[[contributes.runAnything]]` (API 1.18).
|
||||
interface run-anything-provider {
|
||||
record run-anything-item {
|
||||
/// What the list shows, such as `task build`.
|
||||
label: string,
|
||||
/// Grey text after the label.
|
||||
detail: option<string>,
|
||||
/// The line Tab completes in the field and Enter runs (default: `label`).
|
||||
line: option<string>,
|
||||
}
|
||||
/// Entries for `text`, the field's text, which starts with the declared `prefix`
|
||||
/// (or is the start of it). Answer from what the plugin already knows: the IDE
|
||||
/// asks while the user types, keeps the first 100 entries, and drops an answer
|
||||
/// that comes after the text changed or takes longer than 300 ms.
|
||||
suggest: func(project: string, prefix: string, text: string) -> list<run-anything-item>;
|
||||
/// Runs `line`, whose first word is `prefix`, from the invoking window: the
|
||||
/// plugin starts it through its own host calls (`run.start`, terminals), with
|
||||
/// their trust and grant checks. True claims the line; false leaves it to the
|
||||
/// IDE's other entries and finally the shell. A failed call claims the line
|
||||
/// too, so it never runs in the shell instead.
|
||||
run: func(project: string, prefix: string, line: string) -> bool;
|
||||
}
|
||||
|
||||
/// Optional completion in the fields of this plugin's own run configurations, in
|
||||
/// the Run/Debug Configurations dialog (API 1.18).
|
||||
interface run-configuration-completion {
|
||||
record completion-item {
|
||||
/// What the list shows, such as `build`.
|
||||
label: string,
|
||||
/// Grey text after the label, such as the file the entry comes from.
|
||||
detail: option<string>,
|
||||
/// The text that replaces `[replace-start, replace-end)` (default: `label`).
|
||||
insert: option<string>,
|
||||
/// UTF-16 offsets into `text`; the caret ends after the inserted text.
|
||||
replace-start: u32,
|
||||
replace-end: u32,
|
||||
}
|
||||
/// Completions for `field` of the configuration `config` (its id as this plugin
|
||||
/// reported it) in `project`. `field` is `arguments` today: the field splits like a
|
||||
/// shell command line (whitespace separates arguments, `'` and `"` quote). Later
|
||||
/// IDEs may ask for other fields, so answer none for a field you don't know.
|
||||
/// `text` is the field as typed and `caret` a UTF-16 offset into it. Replace only
|
||||
/// the token being completed, so the other options, quoted values and arguments
|
||||
/// after `--` stay as they are. Answer from what the plugin already knows (no
|
||||
/// process per keystroke): the IDE asks while the user types, keeps the first 200
|
||||
/// items, drops an item whose range is outside `text`, and drops an answer that
|
||||
/// comes after the text changed or takes longer than 300 ms.
|
||||
complete: func(project: string, config: string, field: string, text: string, caret: u32) -> list<completion-item>;
|
||||
}
|
||||
|
||||
/// Optional pre-launch gate for targets owned by this plugin (API 1.5).
|
||||
interface run-target-validation {
|
||||
enum operation { run, test }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
@@ -40,6 +40,7 @@ world plugin {
|
||||
import mcp;
|
||||
import settings;
|
||||
import extensions;
|
||||
import agents;
|
||||
|
||||
export lifecycle;
|
||||
export commands;
|
||||
@@ -189,6 +190,10 @@ world configurations-provider { export run-configurations; }
|
||||
world plugin-launch-configurations { include plugin; export launch-configurations; }
|
||||
/// Export-only launch configurations world, composed with plugin by SDK macros.
|
||||
world launch-configurations-provider { export launch-configurations; }
|
||||
/// A plugin that exports configurations with environment, debugger, and output mode (API 1.18).
|
||||
world plugin-execution-configurations { include plugin; export execution-configurations; }
|
||||
/// Export-only execution configurations world, composed with plugin by SDK macros.
|
||||
world execution-configurations-provider { export execution-configurations; }
|
||||
/// A plugin that parses its test output.
|
||||
world plugin-test-results { include plugin; export test-results; }
|
||||
/// Export-only test parser world, composed with plugin by SDK macros.
|
||||
@@ -213,6 +218,16 @@ world plugin-run-target-validation { include plugin; export run-target-validatio
|
||||
/// Export-only validation, composed with the base plugin world.
|
||||
world run-target-validator { export run-target-validation; }
|
||||
|
||||
/// A plugin with Run Anything entries for its prefixes (API 1.18).
|
||||
world plugin-run-anything { include plugin; export run-anything-provider; }
|
||||
/// Export-only Run Anything provider, composed with the base plugin world.
|
||||
world run-anything-exports { export run-anything-provider; }
|
||||
|
||||
/// A plugin completing fields of its own run configurations (API 1.18).
|
||||
world plugin-run-configuration-completion { include plugin; export run-configuration-completion; }
|
||||
/// Export-only run configuration completion, composed with the base plugin world.
|
||||
world run-configuration-completion-exports { export run-configuration-completion; }
|
||||
|
||||
/// A plugin with custom Search Everywhere categories.
|
||||
world plugin-search { include plugin; export search-provider; }
|
||||
/// Optional export composed with the base plugin by the SDK.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.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]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Project-scoped targets owned by the registering plugin (API 1.4).
|
||||
interface run-targets {
|
||||
|
||||
@@ -1,11 +1,29 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Launches this plugin's configurations in the invoking window's Run tool window.
|
||||
interface run {
|
||||
use types.{error};
|
||||
/// Output stream transport for a plugin-owned run configuration (API 1.18).
|
||||
/// Ordinary pseudo-terminals combine stdout and stderr and can change
|
||||
/// buffering, input handling, and terminal behavior.
|
||||
enum output-mode {
|
||||
/// Separate stdout and stderr pipes in the Run console (default).
|
||||
pipes,
|
||||
/// Pseudo-terminal ("Emulate terminal in output console").
|
||||
pty,
|
||||
}
|
||||
/// Per-launch options for `start-with-options` (API 1.18).
|
||||
record start-options {
|
||||
debug: bool,
|
||||
/// Optional per-invocation override. A user-saved override wins over
|
||||
/// this value, which wins over the plugin configuration default.
|
||||
output-mode: option<output-mode>,
|
||||
}
|
||||
/// Starts an owned configuration, appending args. Debug requires a debugger.
|
||||
/// Only from a window command/event. The returned id receives run-exited.
|
||||
start: func(config: string, args: list<string>, debug: bool) -> result<string, error>;
|
||||
/// Starts an owned configuration with launch options, appending args (API 1.18).
|
||||
start-with-options: func(config: string, args: list<string>, options: start-options) -> result<string, error>;
|
||||
}
|
||||
|
||||
/// Optional dynamic configurations, refreshed alongside run detectors.
|
||||
@@ -64,6 +82,32 @@ interface launch-configurations {
|
||||
configurations: func(project-root: string) -> list<launch-configuration>;
|
||||
}
|
||||
|
||||
/// Optional dynamic configurations with environment, debugger, and output mode (API 1.18).
|
||||
/// When exported, the IDE uses this instead of `launch-configurations` and `run-configurations`.
|
||||
interface execution-configurations {
|
||||
use launch-configurations.{debugger};
|
||||
use run.{output-mode};
|
||||
/// `launch-configuration` with a default output transport mode.
|
||||
record execution-configuration {
|
||||
id: string,
|
||||
name: string,
|
||||
program: string,
|
||||
args: list<string>,
|
||||
cwd: option<string>,
|
||||
test: bool,
|
||||
framework: option<string>,
|
||||
/// Variables added to the run's environment (at most 64). A name the IDE's own
|
||||
/// environment already has, such as `PATH`, is refused like in `process`.
|
||||
env: list<tuple<string, string>>,
|
||||
/// None: Debug infers the debugger from a source file in `args`, as before.
|
||||
debugger: option<debugger>,
|
||||
/// Default output stream mode (`pipes` or `pty`).
|
||||
output-mode: output-mode,
|
||||
}
|
||||
/// Returns the complete set for this project root.
|
||||
configurations: func(project-root: string) -> list<execution-configuration>;
|
||||
}
|
||||
|
||||
/// Optional parser for test configurations whose framework is plugin.
|
||||
interface test-results {
|
||||
use types.{location, extension};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// On-demand results for `[[contributes.searchCategories]]`. Optional, API 1.13.
|
||||
interface search-provider {
|
||||
|
||||
Loaded 100 of 255 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача