дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
14e13220d7 | ||
|
|
7ecccb3b75 | ||
|
|
7cbf17b10e | ||
|
|
cb0d02620d | ||
|
|
d6ca43cba4 | ||
|
|
165d4f7d76 | ||
|
|
5785ebadd8 | ||
|
|
0c67a4eea2 | ||
|
|
5e2deed81e | ||
|
|
cae7c05fb1 | ||
|
|
be83458161 | ||
|
|
661124d0d4 | ||
|
|
0dae111b2d | ||
|
|
61d269045b | ||
|
|
266d85fa1a | ||
|
|
f964d79e10 | ||
|
|
4a3eacff62 | ||
|
|
aebc2fe02d | ||
|
|
9b63aa9526 | ||
|
|
df07073886 | ||
|
|
3433ee951b | ||
|
|
8f5b281486 | ||
|
|
43aee8058c | ||
|
|
4016c3c905 | ||
|
|
e6cb7df653 | ||
|
|
2a26c82357 | ||
|
|
66f0bce92f | ||
|
|
dfbd13e2af | ||
|
|
944b57dead | ||
|
|
5bcb37492f | ||
|
|
d5bde9af67 | ||
|
|
5b3e2b7a3d | ||
|
|
dbb6fa51c3 | ||
|
|
3d1769ef00 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a | ||
|
|
3240164840 | ||
|
|
f70f362a3d | ||
|
|
806bb4c78d | ||
|
|
57094bc285 | ||
|
|
a5e0c41663 | ||
|
|
77071238a0 | ||
|
|
64097d3c20 | ||
|
|
cf0e57e5df |
No files matched your search
@@ -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'
|
||||
|
||||
@@ -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
|
||||
|
||||
Створено
+49
-48
@@ -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",
|
||||
@@ -4444,7 +4444,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4463,7 +4463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4544,7 +4544,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4563,7 +4563,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4586,7 +4586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4598,7 +4598,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4614,7 +4614,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4623,7 +4623,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4634,7 +4634,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4693,7 +4693,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4704,6 +4704,7 @@ dependencies = [
|
||||
"ide-jsonrpc",
|
||||
"ide-jvm-inspect",
|
||||
"ide-language",
|
||||
"ide-sdk",
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"ignore",
|
||||
@@ -4722,7 +4723,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4741,7 +4742,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4762,7 +4763,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4784,7 +4785,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4798,7 +4799,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4818,7 +4819,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4843,7 +4844,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4859,7 +4860,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4885,7 +4886,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4906,7 +4907,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4919,7 +4920,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4944,7 +4945,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4957,7 +4958,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4972,7 +4973,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4986,7 +4987,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4999,7 +5000,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -5022,7 +5023,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5044,7 +5045,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5071,7 +5072,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5087,7 +5088,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6726,7 +6727,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;
|
||||
|
||||
@@ -627,6 +627,40 @@ impl crate::AgentManager {
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
let account = account.trim();
|
||||
if !account.is_empty() {
|
||||
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
|
||||
}
|
||||
match discover(&self.shared, spec, model).await {
|
||||
Ok(found) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: self.shared.config_for_new_task(found.config, "copilot"),
|
||||
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
|
||||
retry_at_ms: None,
|
||||
error: None,
|
||||
}),
|
||||
Err(error) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: Vec::new(),
|
||||
thought_levels: BTreeMap::new(),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: None,
|
||||
retry_at_ms: None,
|
||||
error: Some(error),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
|
||||
@@ -33,7 +33,7 @@ pub use catalogs::AgentCatalogs;
|
||||
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
|
||||
pub use external::ExternalSession;
|
||||
pub use model::*;
|
||||
pub use provider::LoginLaunch;
|
||||
pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch};
|
||||
pub use skill_installer::{
|
||||
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
|
||||
SkillScanWarning, SkillScanWarningKind,
|
||||
@@ -69,6 +69,34 @@ pub fn login_launch_without_project(
|
||||
.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>;
|
||||
|
||||
@@ -804,6 +832,11 @@ 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());
|
||||
@@ -853,6 +886,20 @@ impl AgentManager {
|
||||
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<()> {
|
||||
@@ -875,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.
|
||||
|
||||
@@ -650,6 +650,26 @@ 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")]
|
||||
|
||||
@@ -1481,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
|
||||
let message = translate::error_message(&e);
|
||||
return match translate::classify(&e, rate_limits) {
|
||||
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
|
||||
Failure::UsageLimit(resets) => Err(ResponseError {
|
||||
code: codes::INTERNAL_ERROR,
|
||||
message,
|
||||
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
|
||||
}),
|
||||
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
|
||||
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
};
|
||||
}
|
||||
_ => "end_turn",
|
||||
|
||||
@@ -455,6 +455,90 @@ fn failures_are_classified() {
|
||||
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turns_preserve_codex_error_diagnostics() {
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
|
||||
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
|
||||
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
|
||||
assert_eq!(failure.code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
// A completed turn's own error wins over an older error notification.
|
||||
let failure = stop_reason(
|
||||
&json!({ "status": "failed", "error": policy }),
|
||||
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
|
||||
for (value, expected) in [
|
||||
(
|
||||
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
|
||||
"Context is full.\nCodex error: contextWindowExceeded",
|
||||
),
|
||||
(
|
||||
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
|
||||
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
|
||||
),
|
||||
(
|
||||
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
|
||||
"Failed\nbecause",
|
||||
),
|
||||
(
|
||||
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
|
||||
"Codex failed\nDetails\nCodex error: cyberPolicy",
|
||||
),
|
||||
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
|
||||
(json!({}), "Codex failed"),
|
||||
] {
|
||||
assert_eq!(error_message(&value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
|
||||
for notification_only in [false, true] {
|
||||
let mut transcript = load(Scenario::UsageLimit.file());
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
match frame["method"].as_str() {
|
||||
Some("error") => frame["params"]["error"] = policy.clone(),
|
||||
Some("turn/completed") => {
|
||||
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
match result(&results, "prompt") {
|
||||
Err(RpcError::Server { code, message, .. }) => {
|
||||
assert_eq!(*code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(
|
||||
message,
|
||||
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
|
||||
);
|
||||
}
|
||||
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approvals_offer_what_codex_offers_and_always_a_decline() {
|
||||
let params = json!({"availableDecisions": ["accept",
|
||||
|
||||
@@ -740,7 +740,7 @@ pub(super) enum Failure {
|
||||
UsageLimit(Option<f64>),
|
||||
/// Signed out or refused.
|
||||
Auth,
|
||||
/// The model declined.
|
||||
/// The server blocked the turn under a safety policy.
|
||||
Refusal,
|
||||
Other,
|
||||
}
|
||||
@@ -780,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
|
||||
exhausted.map(|s| s * 1000.0)
|
||||
}
|
||||
|
||||
/// The text a failed turn reports: codex's message, with its details.
|
||||
/// The text a failed turn reports: Codex's message, details and diagnostic code.
|
||||
pub(super) fn error_message(error: &Value) -> String {
|
||||
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
|
||||
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
|
||||
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
|
||||
_ => message.to_owned(),
|
||||
let original =
|
||||
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
|
||||
let mut message = original.to_owned();
|
||||
if let Some(details) =
|
||||
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
|
||||
&& !original.contains(details)
|
||||
{
|
||||
message.push('\n');
|
||||
message.push_str(details);
|
||||
}
|
||||
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
|
||||
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
|
||||
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
|
||||
message.push_str(&format!("\nCodex error: {code}"));
|
||||
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
|
||||
message.push_str(&format!(" (HTTP {status})"));
|
||||
}
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
/// One choice of an approval: what ACP shows and what codex gets back.
|
||||
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
@@ -268,16 +285,26 @@ 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 is_valid_github_login(account: &str) -> bool {
|
||||
let bytes = account.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 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))
|
||||
if !is_valid_github_login(account) {
|
||||
return Err(format!("Invalid GitHub account login: {account}"));
|
||||
}
|
||||
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);
|
||||
@@ -303,6 +330,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)
|
||||
}
|
||||
@@ -311,18 +472,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`:
|
||||
@@ -333,9 +493,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(
|
||||
@@ -1251,12 +1412,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();
|
||||
@@ -1265,7 +1426,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));
|
||||
}
|
||||
@@ -1550,6 +1711,47 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[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();
|
||||
|
||||
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
|
||||
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
|
||||
}
|
||||
|
||||
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let linux_arm = format!(
|
||||
"copilot-{}-arm64.tar.gz",
|
||||
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
|
||||
);
|
||||
let linux_x64 =
|
||||
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
|
||||
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
|
||||
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
|
||||
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
|
||||
let (glibc_rel, musl_rel) = match arch {
|
||||
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
|
||||
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
|
||||
};
|
||||
let glibc = root.join(glibc_rel);
|
||||
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
|
||||
let points_to_musl =
|
||||
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
|
||||
let has_glibc = glibc.exists() && !points_to_musl;
|
||||
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -1304,4 +1328,96 @@ esac
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let archives_for = |root: &Path| -> (String, String) {
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
|
||||
(
|
||||
entry.distribution.binary["linux-x86_64"].archive.clone(),
|
||||
entry.distribution.binary["linux-aarch64"].archive.clone(),
|
||||
)
|
||||
};
|
||||
let touch = |path: PathBuf| {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b"").unwrap();
|
||||
};
|
||||
|
||||
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
assert_eq!(
|
||||
archives_for(empty.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
|
||||
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
|
||||
let glibc = tempfile::tempdir().unwrap();
|
||||
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
|
||||
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
|
||||
let musl = tempfile::tempdir().unwrap();
|
||||
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::create_dir_all(musl.path().join("lib64")).unwrap();
|
||||
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let parsed = parse(index).unwrap().remove(0);
|
||||
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
|
||||
assert!(
|
||||
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
|
||||
"unexpected linux-x86_64 archive: {}",
|
||||
parsed.distribution.binary["linux-x86_64"].archive
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -505,6 +505,19 @@ pub struct LanguageCodeStyle {
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
/// JavaScript / TypeScript › Imports › Import paths:
|
||||
/// `shortest` | `relative` | `non-relative` | `project-relative`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier_ending: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_file_exclude_patterns: Vec<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_specifier_exclude_regexes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -562,6 +575,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 {
|
||||
@@ -572,10 +604,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());
|
||||
}
|
||||
}
|
||||
@@ -1426,6 +1426,9 @@ pub struct PythonSettings {
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1438,6 +1441,7 @@ impl Default for PythonSettings {
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,6 +261,12 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of the formatters' language lists that covers `language`. MDX was part of Markdown
|
||||
/// and follows its entry, so lists saved before it had its own language keep formatting it.
|
||||
fn formatter_language(language: &str) -> &str {
|
||||
if language == "mdx" { "markdown" } else { language }
|
||||
}
|
||||
|
||||
/// The external formatter of a file, for a language with an external formatter.
|
||||
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
|
||||
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
|
||||
@@ -295,7 +301,8 @@ fn external_tool(
|
||||
)))
|
||||
};
|
||||
}
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
|
||||
let id = formatter_language(language.id.as_str());
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
|
||||
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
|
||||
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
|
||||
Some(Black)
|
||||
@@ -897,6 +904,24 @@ mod tests {
|
||||
external_tool(forced, language.as_ref(), file, settings)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mdx_follows_the_markdown_entry_of_saved_language_lists() {
|
||||
// Saved before MDX had its own language: the whole list, with no `mdx` in it.
|
||||
let old: ide_core::settings::Settings = serde_json::from_str(
|
||||
r#"{"languages":{"prettier":{"languages":["markdown","css"]},"oxfmt":{"languages":["css"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let file = Path::new("/project/docs/intro.mdx");
|
||||
assert_eq!(tool(None, "mdx", file, &old.languages).unwrap(), Some(Prettier));
|
||||
let mut no_markdown = old.languages.clone();
|
||||
no_markdown.prettier.languages.retain(|l| l != "markdown");
|
||||
assert_eq!(tool(None, "mdx", file, &no_markdown).unwrap(), None);
|
||||
let mut oxfmt = old.languages.clone();
|
||||
oxfmt.oxfmt.languages.push("markdown".into());
|
||||
oxfmt.oxfmt.prefer = true;
|
||||
assert_eq!(tool(None, "mdx", file, &oxfmt).unwrap(), Some(Oxfmt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_settings_use_ruff_for_python_and_prettier_for_the_web() {
|
||||
let settings = LanguagesSettings::default();
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -493,7 +493,7 @@ fn test_kinds(rel: &str) -> &'static [&'static str] {
|
||||
if JS_FILE.is_match(rel) {
|
||||
&["npm", "deno", "bun"]
|
||||
} else if rel.ends_with(".py") {
|
||||
&["pytest", "python"]
|
||||
&["pytest", "unittest", "python"]
|
||||
} else if rel.ends_with(".go") {
|
||||
&["go"]
|
||||
} else if rel.ends_with(".rs") {
|
||||
@@ -644,6 +644,11 @@ fn test_config_for(root: &Path, rel: &str, configs: &[RunConfig]) -> Option<RunC
|
||||
"npm" | "bun" if base.args.iter().any(|a| a == "--") => derived(&base, rel, with(&[file])),
|
||||
"npm" | "bun" => derived(&base, rel, with(&["--".into(), file])),
|
||||
"deno" | "pytest" | "python" => derived(&base, rel, with(&[file])),
|
||||
// `python -m unittest <file>`; a `discover` selection gives way to the file.
|
||||
"unittest" => {
|
||||
let end = base.args.iter().position(|a| a == "discover").unwrap_or(base.args.len());
|
||||
derived(&base, rel, [base.args[..end].to_vec(), vec![file]].concat())
|
||||
}
|
||||
"go" => {
|
||||
let dir = dir_of(&file);
|
||||
let target = if dir.is_empty() { ".".to_owned() } else { format!("./{dir}") };
|
||||
@@ -790,6 +795,11 @@ pub fn target_config(
|
||||
"pytest" | "python" => {
|
||||
Some(named(replace_last(file.args.clone(), |f| format!("{f}::{}", target.path.join("::")))))
|
||||
}
|
||||
// unittest names tests by dotted module path: `tests.test_calc.TestCalc.test_add`.
|
||||
"unittest" => Some(named(replace_last(file.args.clone(), |f| {
|
||||
let module = f.strip_suffix(".py").unwrap_or(f).replace(['/', '\\'], ".");
|
||||
format!("{module}.{}", target.path.join("."))
|
||||
}))),
|
||||
"go" => {
|
||||
let pattern = format!("^{}$", target.path.iter().map(|p| escape_regexp(p)).collect::<Vec<_>>().join("$/^"));
|
||||
let benchmark = target.path.first().is_some_and(|p| p.starts_with("Benchmark"));
|
||||
@@ -921,6 +931,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_unittest_configs_to_files_and_dotted_tests() {
|
||||
let root = Path::new("/p");
|
||||
let mut unittest =
|
||||
blank("unittest".into(), "unittest", "unittest", "python3".into(), vec!["-m".into(), "unittest".into()]);
|
||||
unittest.is_test = true;
|
||||
let mut discover = unittest.clone();
|
||||
discover.args.extend(["discover".into(), "-s".into(), "tests".into()]);
|
||||
let src = "import unittest\n\nclass TestCalc(unittest.TestCase):\n def test_add(self):\n pass\n";
|
||||
let rel = "tests/test_calc.py";
|
||||
for configs in [vec![unittest], vec![discover]] {
|
||||
let c = context_config(root, rel, &configs, src).unwrap();
|
||||
assert_eq!(
|
||||
(c.kind.as_str(), c.args.as_slice()),
|
||||
("unittest", ["-m", "unittest", rel].map(String::from).as_slice())
|
||||
);
|
||||
let ts = detect(src, rel);
|
||||
let c = target_config(root, &ts[1], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc.test_add"]);
|
||||
let c = target_config(root, &ts[0], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_cargo_test_configs() {
|
||||
let root = Path::new("/p");
|
||||
|
||||
@@ -754,6 +754,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
));
|
||||
|
||||
let mut tools = vec![
|
||||
act("code.saveAsLiveTemplate", "Save as Live Template…"),
|
||||
SEP,
|
||||
act("http.newRequest", "New HTTP Request"),
|
||||
act("http.showToolWindow", "HTTP Client"),
|
||||
SEP,
|
||||
|
||||
@@ -8,9 +8,9 @@ use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
|
||||
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
|
||||
RemoteSkillPreview, SkillsPolicy,
|
||||
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;
|
||||
@@ -80,6 +80,19 @@ pub fn agent_refresh_models(
|
||||
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_preview_copilot_models(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
account: String,
|
||||
model: Option<String>,
|
||||
) -> IdeResult<AgentModelCatalog> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
agents.preview_copilot_models(&account, model.as_deref()).await
|
||||
}
|
||||
|
||||
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
|
||||
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
|
||||
#[command(trust = trusted)]
|
||||
@@ -108,7 +121,21 @@ pub fn agent_set_env(
|
||||
host.project(window)?.agents.set_builtin_env(&id, env)
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_login_pty(
|
||||
/// 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,
|
||||
@@ -175,6 +202,25 @@ pub async fn agent_login_spawn(
|
||||
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)?;
|
||||
@@ -1530,12 +1576,14 @@ 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,
|
||||
@@ -1549,6 +1597,7 @@ ide_command::domain!(
|
||||
agent_mcp_save_json,
|
||||
agent_mcp_set_enabled,
|
||||
agent_mcp_test,
|
||||
agent_preview_copilot_models,
|
||||
agent_probe,
|
||||
agent_prompt,
|
||||
agent_providers,
|
||||
|
||||
@@ -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.
|
||||
@@ -118,7 +163,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
|
||||
}
|
||||
items
|
||||
}
|
||||
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
|
||||
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
|
||||
None => syntax(),
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
|
||||
@@ -493,7 +493,7 @@ async fn start_inner(
|
||||
}
|
||||
// A Python configuration pointing at a missing interpreter fails in the depth of
|
||||
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test");
|
||||
if is_python && Path::new(&config.command).components().count() > 1 {
|
||||
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -11,7 +11,7 @@ use ide_spell::{Region, RegionKind, SpellScope, Speller, Typo};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Languages checked as prose (all text but code spans).
|
||||
const PROSE: &[&str] = &["plaintext", "markdown", "restructuredtext", "asciidoc", "latex"];
|
||||
const PROSE: &[&str] = &["plaintext", "markdown", "mdx", "restructuredtext", "asciidoc", "latex"];
|
||||
|
||||
/// Custom dictionary paths: `~/…` from home, relative ones from the project root.
|
||||
fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
|
||||
|
||||
@@ -211,6 +211,8 @@ impl Host {
|
||||
crate::ts_code_style::configure(cfg, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
// After the global plugins: they keep the IDE's copies.
|
||||
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
|
||||
let container_python = effective.languages.python.run_target().is_some();
|
||||
crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective);
|
||||
// Attached dependency projects are source, so basedpyright/Pyright should
|
||||
@@ -452,7 +454,9 @@ impl Host {
|
||||
phpstan.files_removed(batch.removed.iter());
|
||||
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
|
||||
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed))
|
||||
|| ts_config_changed(changed.iter().chain(&batch.removed))
|
||||
{
|
||||
lsp.reconfigure_soon();
|
||||
}
|
||||
// Not while loading: a first `use flake` may write `flake.lock` itself.
|
||||
@@ -762,6 +766,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 +1534,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)
|
||||
}
|
||||
|
||||
@@ -1884,7 +1893,9 @@ fn content_root_watcher(
|
||||
index.ignore_rules_changed(&batch.ignore_rules);
|
||||
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
|
||||
// A workspace member's PHP language level follows its own composer.json.
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed))
|
||||
|| ts_config_changed(changed.iter().chain(&batch.removed))
|
||||
{
|
||||
lsp.reconfigure_soon();
|
||||
}
|
||||
if let Some(bridge) = &kotlin_bridge {
|
||||
@@ -1906,6 +1917,17 @@ fn content_root_watcher(
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// A tsconfig.json / jsconfig.json (or a `tsconfig.*.json` one extends) changed: the tsserver
|
||||
/// plugins it declares are part of vtsls' configuration.
|
||||
fn ts_config_changed<'a>(mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
|
||||
paths.any(|p| {
|
||||
let name = p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
|
||||
!p.components().any(|c| c.as_os_str() == "node_modules")
|
||||
&& (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
|
||||
&& name.ends_with(".json")
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the `composer.json` of `root` is among `paths`: the PHP language level follows it
|
||||
/// (`ide_sdk::php`).
|
||||
fn composer_changed<'a>(root: &Path, mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
|
||||
@@ -2015,7 +2037,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 +2063,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 +2526,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)]
|
||||
@@ -2628,9 +2753,20 @@ mod agent_worktree_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod composer_tests {
|
||||
use super::composer_changed;
|
||||
use super::{composer_changed, ts_config_changed};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[test]
|
||||
fn tsconfig_and_jsconfig_files_count_outside_node_modules() {
|
||||
let changed = |p: &str| ts_config_changed([PathBuf::from(p)].iter());
|
||||
for yes in ["/p/tsconfig.json", "/p/apps/web/jsconfig.json", "/p/tsconfig.base.json"] {
|
||||
assert!(changed(yes), "{yes}");
|
||||
}
|
||||
for no in ["/p/package.json", "/p/tsconfig.ts", "/p/node_modules/x/tsconfig.json"] {
|
||||
assert!(!changed(no), "{no}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_roots_own_composer_json_counts() {
|
||||
let root = Path::new("/work/app");
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation, Imports) as the TypeScript
|
||||
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
|
||||
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
|
||||
//! quick fixes, auto-imports, refactorings and organize imports.
|
||||
@@ -48,12 +48,7 @@ pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &
|
||||
.and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}"))))
|
||||
.unwrap_or_default();
|
||||
let section = section(language, code_style.languages.get(language), &pairs);
|
||||
if !section.is_empty() {
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
}
|
||||
if layer.is_empty() {
|
||||
return;
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
let mut merged = Value::Object(layer);
|
||||
if let Some(own) = cfg.settings.take() {
|
||||
@@ -96,10 +91,30 @@ fn section(
|
||||
if !format.is_empty() {
|
||||
section.insert("format".into(), Value::Object(format));
|
||||
}
|
||||
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
|
||||
// vtsls reads VS Code's names (`quoteStyle`, `importModuleSpecifier`), typescript-language-server
|
||||
// tsserver's (`quotePreference`, `importModuleSpecifierPreference`).
|
||||
let mut preferences = Map::new();
|
||||
if let Some(quotes) = quotes {
|
||||
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": quotes }));
|
||||
preferences.insert("quoteStyle".into(), json!(quotes));
|
||||
preferences.insert("quotePreference".into(), json!(quotes));
|
||||
}
|
||||
let paths = ["shortest", "relative", "non-relative", "project-relative"];
|
||||
if let Some(paths) = pick(style.and_then(|s| s.import_module_specifier.as_ref()), &paths) {
|
||||
preferences.insert("importModuleSpecifier".into(), json!(paths));
|
||||
preferences.insert("importModuleSpecifierPreference".into(), json!(paths));
|
||||
}
|
||||
let endings = ["auto", "minimal", "index", "js"];
|
||||
if let Some(ending) = pick(style.and_then(|s| s.import_module_specifier_ending.as_ref()), &endings) {
|
||||
preferences.insert("importModuleSpecifierEnding".into(), json!(ending));
|
||||
}
|
||||
// Sent even when empty: vtsls has no default for these, so a list left out keeps tsserver's
|
||||
// previous one, and clearing it would only apply after a restart. `[]` excludes nothing.
|
||||
let none = Vec::new();
|
||||
let patterns = style.map_or(&none, |s| &s.auto_import_file_exclude_patterns);
|
||||
let regexes = style.map_or(&none, |s| &s.auto_import_specifier_exclude_regexes);
|
||||
preferences.insert("autoImportFileExcludePatterns".into(), json!(patterns));
|
||||
preferences.insert("autoImportSpecifierExcludeRegexes".into(), json!(regexes));
|
||||
section.insert("preferences".into(), Value::Object(preferences));
|
||||
section
|
||||
}
|
||||
|
||||
@@ -133,9 +148,17 @@ mod tests {
|
||||
"typescript": {
|
||||
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
|
||||
// The server's own settings win.
|
||||
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
|
||||
"preferences": {
|
||||
"quoteStyle": "double",
|
||||
"quotePreference": "single",
|
||||
"autoImportFileExcludePatterns": [],
|
||||
"autoImportSpecifierExcludeRegexes": [],
|
||||
},
|
||||
},
|
||||
"javascript": {
|
||||
"format": { "semicolons": "insert" },
|
||||
"preferences": { "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] },
|
||||
},
|
||||
"javascript": { "format": { "semicolons": "insert" } },
|
||||
})
|
||||
);
|
||||
|
||||
@@ -144,7 +167,52 @@ mod tests {
|
||||
assert_eq!(eslint.settings, None);
|
||||
let mut untouched = server("vtsls");
|
||||
configure(&mut untouched, dir.path(), &Settings::default());
|
||||
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
|
||||
// Nothing set: the server's defaults, and empty exclusion lists so that clearing one reaches
|
||||
// a running server.
|
||||
let empty = json!({ "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] });
|
||||
let empty = json!({ "typescript": { "preferences": empty }, "javascript": { "preferences": empty } });
|
||||
assert_eq!(untouched.settings, Some(empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_style_reaches_the_preferences_of_each_language() {
|
||||
let mut settings = Settings::default();
|
||||
let ts = LanguageCodeStyle {
|
||||
import_module_specifier: Some("relative".into()),
|
||||
import_module_specifier_ending: Some("index".into()),
|
||||
auto_import_file_exclude_patterns: vec!["**/index.ts".into()],
|
||||
auto_import_specifier_exclude_regexes: vec!["^node:".into()],
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("typescript".into(), ts);
|
||||
let js = LanguageCodeStyle {
|
||||
import_module_specifier: Some("non-relative".into()),
|
||||
// Not a tsserver value: left out.
|
||||
import_module_specifier_ending: Some("ts".into()),
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("javascript".into(), js);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
assert_eq!(
|
||||
cfg.settings.unwrap(),
|
||||
json!({
|
||||
"typescript": { "preferences": {
|
||||
"importModuleSpecifier": "relative",
|
||||
"importModuleSpecifierPreference": "relative",
|
||||
"importModuleSpecifierEnding": "index",
|
||||
"autoImportFileExcludePatterns": ["**/index.ts"],
|
||||
"autoImportSpecifierExcludeRegexes": ["^node:"],
|
||||
} },
|
||||
"javascript": { "preferences": {
|
||||
"importModuleSpecifier": "non-relative",
|
||||
"importModuleSpecifierPreference": "non-relative",
|
||||
"autoImportFileExcludePatterns": [],
|
||||
"autoImportSpecifierExcludeRegexes": [],
|
||||
} },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -178,6 +246,6 @@ mod tests {
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
let s = cfg.settings.unwrap();
|
||||
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
|
||||
assert_eq!(s.get("javascript"), None);
|
||||
assert_eq!(s["javascript"].get("format"), None);
|
||||
}
|
||||
}
|
||||
@@ -542,6 +542,23 @@ impl Smoke {
|
||||
self.restore(doc, &before).await;
|
||||
}
|
||||
|
||||
/// Completion at the end of the typed line, once it offers the auto-import `control`, has
|
||||
/// none labelled `label`.
|
||||
async fn not_offered(&self, typed: Typed, label: &str, control: &str) {
|
||||
let (doc, pos, before) = self.type_line(typed).await;
|
||||
self.retry("completion without the item", self.warm_up, || async {
|
||||
let list = ops::lsp::lsp_completion(&self.host, WINDOW, RequestId(7), doc, pos, None).await;
|
||||
let labels: Vec<String> = match list {
|
||||
Ok(l) => l.items.into_iter().map(|i| i.label).collect(),
|
||||
Err(e) => vec![e.to_string()],
|
||||
};
|
||||
let has = |name: &str| labels.iter().any(|l| l == name);
|
||||
if has(control) && !has(label) { Ok(()) } else { Err(labels) }
|
||||
})
|
||||
.await;
|
||||
self.restore(doc, &before).await;
|
||||
}
|
||||
|
||||
async fn organize_imports(&self, import: Typed, expect: Imports) {
|
||||
let (doc, _, before) = self.type_line(import).await;
|
||||
let typed = import.text.trim();
|
||||
@@ -696,6 +713,71 @@ async fn typescript() {
|
||||
smoke("typescript", TYPESCRIPT).await;
|
||||
}
|
||||
|
||||
/// Code Style › TypeScript › Imports (#6072): each change reaches the running vtsls, and its
|
||||
/// auto-imports follow it: relative or path alias, `/index` or not, and excluded files and
|
||||
/// specifiers left out.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "language smoke: needs vtsls"]
|
||||
async fn typescript_import_style() {
|
||||
let checks = Checks {
|
||||
files: &[
|
||||
(
|
||||
"tsconfig.json",
|
||||
r#"{"compilerOptions": {"module": "ESNext", "moduleResolution": "Bundler", "strict": true,
|
||||
"noEmit": true, "allowImportingTsExtensions": true, "paths": {"@/*": ["./src/*"]}},
|
||||
"include": ["src"]}"#,
|
||||
),
|
||||
("src/lib/alpha.ts", "export function alphaHelper(): number {\n return 1;\n}\n"),
|
||||
// Never excluded, and matching what is typed (tsserver offers only those): the
|
||||
// auto-import candidates are in the completion list.
|
||||
("src/lib/betaWord.ts", "export function betaWord(): number {\n return 3;\n}\n"),
|
||||
("src/lib/hints.ts", "export function alphaHint(): number {\n return 4;\n}\n"),
|
||||
("src/app/components/index.ts", "export function betaWidget(): number {\n return 2;\n}\n"),
|
||||
("src/app/main.ts", "export const ready = true;\n"),
|
||||
("src/app/other.ts", "export const other = true;\n"),
|
||||
("src/app/third.ts", "export const third = true;\n"),
|
||||
("src/app/fourth.ts", "export const fourth = true;\n"),
|
||||
("src/app/fifth.ts", "export const fifth = true;\n"),
|
||||
],
|
||||
..TYPESCRIPT
|
||||
};
|
||||
let smoke = Smoke::start("typescript", &checks).await;
|
||||
let set = |key: &str, value: &str| {
|
||||
let scope = ide_workspace::settings::SettingsScope::Project;
|
||||
let key = format!("editor.codeStyle.languages.typescript.{key}");
|
||||
ops::project::settings_set(&smoke.host, WINDOW, scope, key, value.into()).unwrap();
|
||||
};
|
||||
let alpha = typed("src/app/main.ts", "export const ready", "alphaH");
|
||||
let beta = typed("src/app/main.ts", "export const ready", "betaW");
|
||||
let import = |typed, label, result| AutoImport { typed, label, result };
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
set("importModuleSpecifier", r#""non-relative""#);
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
set("importModuleSpecifierEnding", r#""index""#);
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
|
||||
set("importModuleSpecifierEnding", r#""minimal""#);
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
|
||||
// tsserver keeps the auto-import candidates of the file it last completed in until the
|
||||
// program changes; other files see an exclusion at once.
|
||||
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#);
|
||||
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
|
||||
smoke.not_offered(typed("src/app/third.ts", "export const third", "alphaH"), "alphaHelper", "alphaHint").await;
|
||||
|
||||
// Emptied lists reach the server too: the symbols are offered again.
|
||||
set("autoImportFileExcludePatterns", "[]");
|
||||
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
set("autoImportSpecifierExcludeRegexes", "[]");
|
||||
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
}
|
||||
|
||||
/// 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>> {
|
||||
|
||||
@@ -6794,6 +6794,8 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
let mut req = vec![0; len];
|
||||
let _ = reader.read_exact(&mut req);
|
||||
let body = "plain ok";
|
||||
// Recorded before the reply: the client may assert as soon as it reads it.
|
||||
seen.lock().push("served".into());
|
||||
let _ = writer.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
|
||||
@@ -6801,7 +6803,6 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
seen.lock().push("served".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -63,6 +63,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("lua", include_str!("../../../languages/lua.toml")),
|
||||
("makefile", include_str!("../../../languages/makefile.toml")),
|
||||
("markdown", include_str!("../../../languages/markdown.toml")),
|
||||
("mdx", include_str!("../../../languages/mdx.toml")),
|
||||
("nix", include_str!("../../../languages/nix.toml")),
|
||||
("objective-c", include_str!("../../../languages/objective-c.toml")),
|
||||
("objective-cpp", include_str!("../../../languages/objective-cpp.toml")),
|
||||
@@ -1281,6 +1282,7 @@ mod tests {
|
||||
("Views/MainWindow.axaml", "axaml"),
|
||||
("MainWindow.xaml", "xml"),
|
||||
("README.md", "markdown"),
|
||||
("Intro.mdx", "mdx"),
|
||||
("Dockerfile", "dockerfile"),
|
||||
("Dockerfile.dev", "dockerfile"),
|
||||
("Makefile", "makefile"),
|
||||
@@ -1362,6 +1364,22 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indented_sass_has_its_own_server() {
|
||||
let reg = reg();
|
||||
let names = |lang: &str| -> Vec<String> {
|
||||
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
|
||||
};
|
||||
assert_eq!(names("sass"), ["some-sass-language-server"]);
|
||||
let sass = ®.get(&LanguageId::new("sass")).unwrap().language_servers[0];
|
||||
assert_eq!(sass.settings.as_ref().and_then(|s| s.get("somesass")), Some(&serde_json::json!({})));
|
||||
for lang in ["scss", "css", "less"] {
|
||||
let names = names(lang);
|
||||
assert_eq!(names[0], "vscode-css-language-server", "{lang}");
|
||||
assert!(!names.iter().any(|n| n == "some-sass-language-server"), "{lang}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn astro_server_leaves_typescript_sdk_resolution_to_the_launcher() {
|
||||
let reg = reg();
|
||||
|
||||
@@ -28,6 +28,7 @@ percent-encoding = "2"
|
||||
zip.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
ide-sdk.workspace = true
|
||||
tempfile.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util"] }
|
||||
|
||||
@@ -969,6 +969,145 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
const MDX_BUTTON: &str =
|
||||
"export function Button(props: { label: string }) {\n return <button>{props.label}</button>;\n}\n";
|
||||
const MDX_DOC: &str = "import { Button } from \"./Button\"\n\nexport const count = 2\n\n# Hello\n\n<Button label=\"hi\" />\n\n<Button label={count} />\n\n{count.toFixed()}\n";
|
||||
|
||||
/// The MDX Language Server with the `typescript.tsdk` the launcher adds. Set
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @mdx-js/language-server
|
||||
/// typescript@6 @types/react`; the project is created inside it, so that it
|
||||
/// resolves the React types.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @mdx-js/language-server, typescript and @types/react (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn mdx_language_server_end_to_end() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir_in(&tools).unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
"{\"compilerOptions\":{\"strict\":true,\"jsx\":\"react-jsx\",\"moduleResolution\":\"bundler\",\"module\":\"esnext\"},\"mdx\":{\"checkMdx\":true}}",
|
||||
)
|
||||
.unwrap();
|
||||
let (button, file) = (root.join("Button.tsx"), root.join("doc.mdx"));
|
||||
std::fs::write(&button, MDX_BUTTON).unwrap();
|
||||
std::fs::write(&file, MDX_DOC).unwrap();
|
||||
|
||||
let mut mdx = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("mdx")).unwrap();
|
||||
let server = &mut mdx.language_servers[0];
|
||||
server.command = tools.join("node_modules/.bin/mdx-language-server").to_string_lossy().into_owned();
|
||||
let tsdk = tools.join("node_modules/typescript/lib").to_string_lossy().into_owned();
|
||||
server.initialization_options.as_mut().unwrap()["typescript"]
|
||||
.as_table_mut()
|
||||
.unwrap()
|
||||
.insert("tsdk".into(), toml::Value::String(tsdk));
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![mdx]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &file, &LanguageId::new("mdx"), 1, MDX_DOC);
|
||||
|
||||
// `Button` in `<Button label="hi" />`.
|
||||
let hover = retry("hover", Duration::from_secs(90), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.hover(doc, Pos::new(6, 3), Default::default()).await.ok().flatten() }
|
||||
})
|
||||
.await;
|
||||
assert!(hover.contents.value.contains("label: string"), "{}", hover.contents.value);
|
||||
let defs = mgr.goto(doc, Pos::new(6, 3), GotoKind::Definition).await.unwrap();
|
||||
assert!(defs.iter().any(|d| d.path == button), "{defs:?}");
|
||||
|
||||
// Members of `count` inside `{…}`, and the imported component in JSX.
|
||||
for (pos, label) in [(Pos::new(10, 7), "toFixed"), (Pos::new(6, 3), "Button")] {
|
||||
retry(label, Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move {
|
||||
let list = mgr.completion(doc, pos, None, Default::default()).await.ok()?;
|
||||
list.items.iter().any(|i| i.label == label).then_some(())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
// Markdown headings come from the server too (marksman skips `.mdx` by default).
|
||||
let symbols = mgr.document_symbols(doc).await.unwrap().unwrap();
|
||||
assert!(symbols.iter().any(|s| s.name.contains("Hello")), "{symbols:?}");
|
||||
|
||||
// `label={count}`: number is not assignable to string.
|
||||
retry("prop type error", Duration::from_secs(60), || {
|
||||
let found = events.lock().iter().any(|e| {
|
||||
matches!(e, IdeEvent::Diagnostics { path, items, .. }
|
||||
if path == &file && items.iter().any(|d| d.range.start.line == 8 && d.message.contains("string")))
|
||||
});
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// A tsserver plugin reporting `from <name>` at the start of every file.
|
||||
const DIAGNOSTIC_PLUGIN: &str = "module.exports = () => ({ create(info) {\n const ls = info.languageService;\n const proxy = Object.create(null);\n for (const k of Object.keys(ls)) proxy[k] = (...a) => ls[k](...a);\n proxy.getSemanticDiagnostics = (f) => [...ls.getSemanticDiagnostics(f), { file: ls.getProgram().getSourceFile(f), start: 0, length: 1, messageText: 'from ' + NAME, category: 1, code: 99001 }];\n return proxy;\n} });\n";
|
||||
|
||||
/// tsconfig `compilerOptions.plugins` load from the project's `node_modules` with vtsls' own
|
||||
/// TypeScript through the probe location `configure_tsconfig_plugins` writes (#6336); one that
|
||||
/// isn't installed is skipped, and the IDE's global plugins keep loading their own copies,
|
||||
/// also when the project has a package of the same name. Set `OPENIDEA_TEST_NPM_TOOLS` to a
|
||||
/// dir with `npm i @vtsls/language-server typescript@5`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn tsconfig_plugins_load_from_the_project_with_the_bundled_typescript() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
// Outside the project: a probe location resolves plugins from its ancestors' node_modules too.
|
||||
let ide = tempfile::tempdir().unwrap();
|
||||
let ide = dunce::canonicalize(ide.path()).unwrap();
|
||||
let plugin = |dir: &Path, name: &str, says: &str| {
|
||||
let dir = dir.join("node_modules").join(name);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("index.js"), DIAGNOSTIC_PLUGIN.replace("NAME", &format!("'{says}'"))).unwrap();
|
||||
};
|
||||
plugin(&root, "project-plugin", "project-plugin");
|
||||
plugin(&root, "global-plugin", "the project's global-plugin");
|
||||
plugin(&ide, "global-plugin", "global-plugin");
|
||||
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
|
||||
let plugins = r#"[{"name":"not-installed"},{"name":"project-plugin"}]"#;
|
||||
std::fs::write(root.join("tsconfig.json"), format!("{{\"compilerOptions\":{{\"plugins\":{plugins}}}}}")).unwrap();
|
||||
let main = root.join("main.ts");
|
||||
let text = "export const n: number = 1;\n";
|
||||
std::fs::write(&main, text).unwrap();
|
||||
let global = serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [{
|
||||
"name": "global-plugin",
|
||||
"location": ide.to_string_lossy(),
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
}] } } });
|
||||
|
||||
for configured in [false, true] {
|
||||
let mut server = npm_server(&tools, "vtsls", "vtsls", Some(global.clone()));
|
||||
server.tsserver_project = true;
|
||||
if configured {
|
||||
assert!(ide_sdk::apply::configure_tsconfig_plugins(&mut server, &root, &ide.join("data")));
|
||||
}
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &main, &LanguageId::new("typescript"), 1, text);
|
||||
let mut messages = retry("the plugins' diagnostics", Duration::from_secs(90), || {
|
||||
let found = events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path, items, .. } if path == &main && !items.is_empty() => {
|
||||
Some(items.iter().map(|d| d.message.clone()).collect::<Vec<_>>())
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
messages.sort();
|
||||
let expected: &[&str] =
|
||||
if configured { &["from global-plugin", "from project-plugin"] } else { &["from global-plugin"] };
|
||||
assert_eq!(messages, expected);
|
||||
let crashed = matches!(last_status(&events, "vtsls"), Some((ServerStatus::Crashed, _)));
|
||||
assert!(!crashed, "{:?}", last_status(&events, "vtsls"));
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n";
|
||||
const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n";
|
||||
const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n";
|
||||
@@ -1425,3 +1564,81 @@ async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
|
||||
.await;
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// Indented Sass through the built-in `sass` definition: completion, Go to
|
||||
/// Declaration and hover across `@use`, and syntax errors as diagnostics.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires some-sass-language-server on PATH"]
|
||||
async fn some_sass_indented_end_to_end() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
let theme = root.join("_theme.sass");
|
||||
std::fs::write(
|
||||
&theme,
|
||||
"/// Brand colour\n$brand: #336699\n\n/// Rounded corners\n@mixin rounded($r: 4px)\n border-radius: $r\n",
|
||||
)
|
||||
.unwrap();
|
||||
let main = root.join("main.sass");
|
||||
let source = "@use \"theme\"\n\n.button\n color: theme.$brand\n +theme.rounded(2px)\n";
|
||||
std::fs::write(&main, source).unwrap();
|
||||
let sass = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("sass")).unwrap();
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![sass]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &main, &LanguageId::new("sass"), 1, source);
|
||||
let name = "some-sass-language-server";
|
||||
retry("some-sass ready", Duration::from_secs(30), || {
|
||||
let status = last_status(&events, name);
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("some-sass failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
|
||||
// `theme.$brand` and the `+theme.rounded` mixin, both in `_theme.sass`.
|
||||
for (pos, line) in [(Pos::new(3, 17), 1), (Pos::new(4, 10), 4)] {
|
||||
let defs = retry("definition", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(doc, pos, GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!((defs[0].path.to_path_buf(), defs[0].range.start.line), (theme.clone(), line), "{pos:?}");
|
||||
}
|
||||
// The `@use` path is a document link, which Go to Declaration follows.
|
||||
let links = mgr.document_links(doc).await.unwrap();
|
||||
assert!(
|
||||
links
|
||||
.iter()
|
||||
.any(|l| l.range.start.line == 0 && l.path.as_ref().map(|p| p.to_path_buf()) == Some(theme.clone())),
|
||||
"{links:?}"
|
||||
);
|
||||
let hover = mgr.hover(doc, Pos::new(3, 17), Default::default()).await.unwrap().unwrap();
|
||||
assert!(hover.contents.value.contains("#336699") && hover.contents.value.contains("Brand colour"));
|
||||
let hover = mgr.hover(doc, Pos::new(4, 10), Default::default()).await.unwrap().unwrap();
|
||||
assert!(hover.contents.value.contains("Rounded corners"), "{}", hover.contents.value);
|
||||
|
||||
// `$` lists the module's variables, `+` its mixins.
|
||||
let edited = format!("{source} margin: theme.$\n +theme.\n");
|
||||
mgr.did_change(
|
||||
doc,
|
||||
2,
|
||||
&[AppliedChange { range: Range::point(Pos::new(5, 0)), text: edited[source.len()..].into() }],
|
||||
&|| unreachable!(),
|
||||
);
|
||||
let labels = |list: ide_lsp::types::CompletionList| list.items.into_iter().map(|i| i.label).collect::<Vec<_>>();
|
||||
let vars = labels(mgr.completion(doc, Pos::new(5, 16), Some("$".into()), Default::default()).await.unwrap());
|
||||
assert!(vars.iter().any(|l| l.contains("$brand")), "{vars:?}");
|
||||
let mixins = labels(mgr.completion(doc, Pos::new(6, 9), Some(".".into()), Default::default()).await.unwrap());
|
||||
assert!(mixins.iter().any(|l| l.contains("rounded")), "{mixins:?}");
|
||||
|
||||
let errors = retry("diagnostics", Duration::from_secs(30), || {
|
||||
let found = events.lock().iter().rev().find_map(|event| match event {
|
||||
IdeEvent::Diagnostics { source, items, .. } if source == name && !items.is_empty() => Some(items.clone()),
|
||||
_ => None,
|
||||
});
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
assert!(errors.iter().any(|d| d.range.start.line >= 5), "{errors:?}");
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
04c8f881e25aae1b7298f554f3c4ab38251eec48e8d88656d73cad019eb1644c
|
||||
db06d81fb37a51711e2b76ab0192eb23293ef498e8ff6e5e46e0b5099d6ba038
|
||||
@@ -78,7 +78,7 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
// Variables go by name (`-e NAME`) so their values stay out of the command line
|
||||
// echoed in the console; the docker CLI reads them from its own environment.
|
||||
let mut env: BTreeMap<String, String> = run.file_env.clone();
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test")
|
||||
&& !command.env.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
env.insert("PYTHONUNBUFFERED".into(), "1".into());
|
||||
|
||||
@@ -1227,7 +1227,10 @@ fn uses_pytest(root: &Path) -> bool {
|
||||
if read(&root.join("setup.cfg")).is_some_and(|s| s.contains("[tool:pytest]")) {
|
||||
return true;
|
||||
}
|
||||
if read(&root.join("pyproject.toml")).is_some_and(|py| py.contains("pytest") || root.join("tests").is_dir()) {
|
||||
// A `tests` folder alone means pytest unless its tests are the standard library's unittest.
|
||||
if read(&root.join("pyproject.toml"))
|
||||
.is_some_and(|py| py.contains("pytest") || (root.join("tests").is_dir() && !uses_unittest(root)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
["requirements.txt", "requirements-dev.txt", "requirements_dev.txt", "dev-requirements.txt"]
|
||||
@@ -1235,6 +1238,34 @@ fn uses_pytest(root: &Path) -> bool {
|
||||
.any(|f| read(&root.join(f)).is_some_and(|s| s.contains("pytest")))
|
||||
}
|
||||
|
||||
/// Whether the project's test modules (`test*.py` at the root and in `tests/` / `test/`) use the
|
||||
/// standard library's unittest and none of them pytest.
|
||||
fn uses_unittest(root: &Path) -> bool {
|
||||
let mut found = false;
|
||||
for dir in [root.to_path_buf(), root.join("tests"), root.join("test")] {
|
||||
let Ok(entries) = fs::read_dir(&dir) else { continue };
|
||||
// ponytail: the first 50 modules of each folder decide; enough to tell a project's style.
|
||||
for entry in entries.flatten().take(50) {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if !name.starts_with("test") || !name.ends_with(".py") {
|
||||
continue;
|
||||
}
|
||||
let Some(text) = read(&entry.path()) else { continue };
|
||||
if text
|
||||
.lines()
|
||||
.any(|l| l.trim_start().starts_with("import pytest") || l.trim_start().starts_with("from pytest"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
found |= text.lines().any(|l| {
|
||||
let l = l.trim_start();
|
||||
l.starts_with("import unittest") || l.starts_with("from unittest")
|
||||
});
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Python configurations of the project at `root`, a folder of the opened project `top`.
|
||||
fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini", "manage.py"];
|
||||
@@ -1280,6 +1311,11 @@ fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let own_pytest = matches!(env, PyEnv::Venv(ref v) if !v.starts_with("../")) && env.has_tool(root, "pytest");
|
||||
if uses_pytest(root) || own_pytest {
|
||||
out.push(py_config("pytest".into(), "pytest".into(), "pytest", env.tool(root, "pytest"), &[]).test());
|
||||
} else if !root.join("manage.py").is_file() && uses_unittest(root) {
|
||||
out.push(
|
||||
py_config("unittest".into(), "python -m unittest".into(), "unittest", env.python(), &["-m", "unittest"])
|
||||
.test(),
|
||||
);
|
||||
}
|
||||
// After pytest: a project set up for pytest (pytest-django) keeps it as the default test runner.
|
||||
if root.join("manage.py").is_file() {
|
||||
|
||||
@@ -341,6 +341,7 @@ impl Cx<'_> {
|
||||
DJANGO_SERVER => self.django_server(name, c, &mut ignored)?,
|
||||
DJANGO_TESTS => self.django_tests(name, c, &mut ignored)?,
|
||||
PYTHON_TESTS if matches!(factory, "py.test" | "pytest") => self.pytest(name, c, &mut ignored)?,
|
||||
PYTHON_TESTS if factory == "Unittests" => self.unittest(name, c, &mut ignored)?,
|
||||
NPM => self.npm(name, c, &mut ignored)?,
|
||||
JEST | VITEST => self.js_tests(name, c, ty == VITEST, &mut ignored)?,
|
||||
NODE => self.node(name, c, &mut ignored)?,
|
||||
@@ -667,6 +668,38 @@ impl Cx<'_> {
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
/// PyCharm's Unittests: a Python target (`tests.test_money.TestRound`) as unittest's name, a
|
||||
/// file as its path, a folder discovered (`discover -s`, with the configuration's pattern).
|
||||
fn unittest(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
|
||||
let (exe, mut args, dir, cwd) = self.interpreter(c, ignored)?;
|
||||
args.extend(["-m".to_owned(), "unittest".to_owned()]);
|
||||
let field = |key: &str| c.option(key).map(json_string).filter(|v| !v.trim().is_empty());
|
||||
if let Some(target) = field("_new_target") {
|
||||
let target = self.expand(&target)?;
|
||||
match field("_new_targetType").as_deref() {
|
||||
Some("PYTHON") => args.push(target),
|
||||
Some("CUSTOM") => {}
|
||||
_ => {
|
||||
let path = path_from(self.root, file_url_path(&target), &dir);
|
||||
if path.ends_with(".py") {
|
||||
args.push(path);
|
||||
} else {
|
||||
args.extend(["discover".to_owned(), "-s".to_owned(), path]);
|
||||
if let Some(pattern) = field("_new_pattern") {
|
||||
args.extend(["-p".to_owned(), strip_quotes(&pattern).to_owned()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
args.extend(self.args_quoted(field("_new_additionalArguments").as_deref(), Quotes::Single, &dir)?);
|
||||
let mut rc = config(name, "unittest", exe, args, Some("debugpy"));
|
||||
rc.cwd = cwd.map(Into::into);
|
||||
rc.is_test = true;
|
||||
self.python_env(c, &mut rc, ignored)?;
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
/// A pytest Python target (`tests.test_money.TestRound.test_eur`) as the node id PyCharm
|
||||
/// passes (`tests/test_money.py::TestRound::test_eur`, intellij-community `PyTestsShared.kt:366-400`):
|
||||
/// the longest prefix that is a module on disk (`a/b.py` or `a/b/__init__.py`, from the working
|
||||
|
||||
@@ -426,7 +426,7 @@ impl ProcessManager {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let mut env = launch_env(root, config)?;
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test") {
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") {
|
||||
crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?;
|
||||
}
|
||||
if let Some(dir) = options.ruby_reporter.as_deref().filter(|_| crate::ruby_reporter::applies(config)) {
|
||||
@@ -1087,7 +1087,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
|
||||
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
|
||||
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
|
||||
};
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test")
|
||||
&& !config.env.contains_key("PYTHONUNBUFFERED")
|
||||
&& !vars.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
|
||||
@@ -676,6 +676,34 @@ fn python_projects() {
|
||||
assert_eq!(ids(&c), ["python:module:app"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_unittest_projects() {
|
||||
const UNITTEST: &str = "import unittest\n\nclass T(unittest.TestCase):\n pass\n";
|
||||
// The standard library's unittest and no pytest: `python -m unittest`.
|
||||
let dir = project(&[("pyproject.toml", "[project]\nname = 'x'\n"), ("tests/test_x.py", UNITTEST)]);
|
||||
let c = detect(dir.path());
|
||||
assert_eq!(ids(&c), ["unittest"]);
|
||||
let unittest = find(&c, "unittest");
|
||||
let python = if cfg!(windows) { "python" } else { "python3" };
|
||||
assert_eq!(cmdline(unittest), format!("{python} -m unittest"));
|
||||
assert!(unittest.is_test);
|
||||
assert_eq!(unittest.debug_adapter.as_deref(), Some("debugpy"));
|
||||
let dir = project(&[("requirements.txt", ""), ("test_app.py", UNITTEST)]);
|
||||
assert_eq!(ids(&detect(dir.path())), ["unittest"]);
|
||||
// A module that imports pytest, a `tests` folder of pytest-style tests, or Django: as before.
|
||||
let dir = project(&[
|
||||
("pyproject.toml", "[project]\nname = 'x'\n"),
|
||||
("tests/test_x.py", UNITTEST),
|
||||
("tests/test_y.py", "import pytest\n"),
|
||||
]);
|
||||
assert_eq!(ids(&detect(dir.path())), ["pytest"]);
|
||||
let dir =
|
||||
project(&[("pyproject.toml", "[project]\nname = 'x'\n"), ("tests/test_x.py", "def test_x():\n assert 1\n")]);
|
||||
assert_eq!(ids(&detect(dir.path())), ["pytest"]);
|
||||
let dir = project(&[("manage.py", ""), ("shop/tests.py", UNITTEST), ("test_x.py", UNITTEST)]);
|
||||
assert_eq!(ids(&detect(dir.path())), ["django:runserver", "django:test"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn python_virtualenv() {
|
||||
|
||||
@@ -299,7 +299,16 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
</configuration>
|
||||
<configuration name="Unittests in tests" type="tests" factoryName="Unittests">
|
||||
{PY_COMMON}
|
||||
<option name="_new_target" value=""tests"" />
|
||||
<option name="_new_pattern" value=""check_*.py"" />
|
||||
<option name="_new_target" value=""$PROJECT_DIR$/tests"" />
|
||||
<option name="_new_targetType" value=""PATH"" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="Unittest case" type="tests" factoryName="Unittests">
|
||||
{PY_COMMON}
|
||||
<option name="_new_additionalArguments" value=""-f"" />
|
||||
<option name="_new_target" value=""tests.test_money.RoundTests"" />
|
||||
<option name="_new_targetType" value=""PYTHON"" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="dev" type="js.build_tools.npm">
|
||||
@@ -319,7 +328,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
);
|
||||
let r = import_from(dir.path(), &[]);
|
||||
let names: Vec<&str> = r.imported.iter().map(|c| c.config.name.as_str()).collect();
|
||||
assert_eq!(names, ["App", "Unit", "Case", "Path params", "Custom", "dev"]);
|
||||
assert_eq!(names, ["App", "Unit", "Case", "Path params", "Custom", "Unittests in tests", "Unittest case", "dev"]);
|
||||
|
||||
let app = get(&r, "App");
|
||||
// `$USER_HOME$` is this machine's: the configuration goes to run.local.toml.
|
||||
@@ -343,7 +352,11 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
assert_eq!(get(&r, "Path params").args, s(&["-m", "pytest", "tests/test_money.py", "-k", "slow or fast"]));
|
||||
assert_eq!(get(&r, "Custom").args, s(&["-m", "pytest", "tests/a.py", "--maxfail=2"]));
|
||||
|
||||
assert_eq!(reason(&r, "Unittests in tests"), &SkipReason::UnsupportedType { type_: "tests (Unittests)".into() });
|
||||
let unittests = get(&r, "Unittests in tests");
|
||||
assert_eq!(unittests.kind, "unittest");
|
||||
assert!(unittests.is_test);
|
||||
assert_eq!(unittests.args, s(&["-m", "unittest", "discover", "-s", "tests", "-p", "check_*.py"]));
|
||||
assert_eq!(get(&r, "Unittest case").args, s(&["-m", "unittest", "tests.test_money.RoundTests", "-f"]));
|
||||
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "JUnit".into() });
|
||||
|
||||
let dev = get(&r, "dev");
|
||||
@@ -366,7 +379,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
);
|
||||
assert_eq!(ignored(&r, "dev"), ["scripts"]);
|
||||
// Neither the template nor the temporary `build` is listed as skipped.
|
||||
assert_eq!(r.skipped.len(), 2);
|
||||
assert_eq!(r.skipped.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -35,6 +35,9 @@ pub(crate) const SOURCES: &[(&str, &str)] = generators![
|
||||
"astro",
|
||||
"nestjs",
|
||||
"express",
|
||||
"vue",
|
||||
"expo",
|
||||
"electron",
|
||||
// Systems
|
||||
"go",
|
||||
"rust",
|
||||
|
||||
@@ -20,8 +20,13 @@ dotnet:
|
||||
- "dotnet new console --name my-app --output my-app --language C#"
|
||||
- dotnet sln add my-app
|
||||
- dotnet new gitignore
|
||||
electron:
|
||||
- npx --yes create-electron-app@latest init my-app --skip-git --package-manager npm --template vite --typescript
|
||||
elixir:
|
||||
- mix new . --app my_app
|
||||
expo:
|
||||
- npx --yes create-expo-app@latest my-app --template blank-typescript --no-install --yes
|
||||
- npm install
|
||||
express:
|
||||
- npm install
|
||||
fastapi:
|
||||
@@ -77,5 +82,8 @@ symfony:
|
||||
vite:
|
||||
- npx --yes create-vite@latest my-app --template react-ts --no-interactive
|
||||
- npm install
|
||||
vue:
|
||||
- npx --yes create-vue@latest my-app --ts
|
||||
- npm install
|
||||
zig:
|
||||
- zig init
|
||||
@@ -130,6 +130,20 @@ fn package_steps_use_the_chosen_runner() {
|
||||
assert_eq!(argv(step, &values)[..2], ["bunx", "create-vite@latest"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_vue_runs_without_prompting() {
|
||||
let def = def("vue").unwrap();
|
||||
let mut values = with_defaults(def, "My App", &Values::new());
|
||||
// A valid package name, or create-vue asks for one.
|
||||
assert_eq!(argv(&def.steps[0], &values)[2..], ["create-vue@latest", "my-app", "--ts"]);
|
||||
values.insert("ts".into(), "false".into());
|
||||
assert!(argv(&def.steps[0], &values).ends_with(&["--oxlint".to_owned()]));
|
||||
for flag in ["router", "pinia", "vitest", "eslint"] {
|
||||
values.insert(flag.into(), "true".into());
|
||||
}
|
||||
assert!(argv(&def.steps[0], &values).ends_with(&["--router", "--pinia", "--vitest", "--eslint"].map(String::from)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_arguments() {
|
||||
let def = def("python").unwrap();
|
||||
|
||||
@@ -72,6 +72,10 @@ smoke! {
|
||||
astro: "astro", [], ["npm", "run", "build"];
|
||||
nestjs: "nestjs", [], ["npm", "run", "build"];
|
||||
express: "express", [], ["node", "--check", "index.js"];
|
||||
vue: "vue", [("router", "true"), ("pinia", "true"), ("vitest", "true"), ("eslint", "true")], ["npm", "run", "build"];
|
||||
expo: "expo", [], ["npx", "tsc", "--noEmit"];
|
||||
electron: "electron", [], ["npx", "tsc", "--noEmit"];
|
||||
electron_pnpm: "electron", [("pm", "pnpm")], ["pnpm", "exec", "tsc", "--noEmit"];
|
||||
html: "html", [], [];
|
||||
go: "go", [], ["go", "build", "./..."];
|
||||
rust: "rust", [], ["cargo", "build", "-q"];
|
||||
|
||||
@@ -1574,6 +1574,9 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
{
|
||||
cfg.command = bin.to_string_lossy().into_owned();
|
||||
}
|
||||
if name == crate::mdx::SERVER {
|
||||
crate::mdx::configure(cfg, root, server_root, s);
|
||||
}
|
||||
if name == crate::arduino::SERVER {
|
||||
crate::arduino::configure(cfg, root, server_root, s);
|
||||
}
|
||||
@@ -1649,6 +1652,32 @@ pub fn configure_path_aliases(cfg: &mut LanguageServerConfig, server_root: &Path
|
||||
true
|
||||
}
|
||||
|
||||
/// Lets vtsls load the tsserver plugins that the project's tsconfig.json / jsconfig.json
|
||||
/// declare (Next.js) with any TypeScript version, from a plugin probe location under
|
||||
/// `data_dir` that loads the project's packages (#6336). A plugin the IDE registers globally
|
||||
/// keeps the IDE's copy, also when a tsconfig names it, so call this after those are
|
||||
/// registered. No-op without declared plugins, and for TypeScript 7's native server.
|
||||
pub fn configure_tsconfig_plugins(cfg: &mut LanguageServerConfig, server_root: &Path, data_dir: &Path) -> bool {
|
||||
if cfg.name != "vtsls" || !cfg.tsserver_project {
|
||||
return false;
|
||||
}
|
||||
let options = cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok());
|
||||
let global: Vec<String> = options
|
||||
.as_ref()
|
||||
.and_then(|v| v.pointer("/vtsls/tsserver/globalPlugins")?.as_array().cloned())
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|p| p.get("name")?.as_str().map(str::to_owned))
|
||||
.collect();
|
||||
let mut declared = crate::tsconfig_plugins::declared(server_root);
|
||||
declared.packages.retain(|name, _| !global.contains(name));
|
||||
let Some(location) = crate::tsconfig_plugins::probe_location(data_dir, server_root, &declared) else {
|
||||
return false;
|
||||
};
|
||||
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "pluginPaths": [location] } } }));
|
||||
true
|
||||
}
|
||||
|
||||
/// The servers `language` uses after Settings › Language Servers: the
|
||||
/// definition's ones that aren't disabled, then the ones defined in settings for it.
|
||||
pub fn language_servers(language: &str, defined: &[LanguageServerConfig], s: &Settings) -> Vec<LanguageServerConfig> {
|
||||
@@ -1925,7 +1954,7 @@ pub fn run_target<'a>(config: &RunConfig, settings: &'a Settings) -> Option<&'a
|
||||
}
|
||||
|
||||
fn is_python_config(config: &RunConfig, program: &str) -> bool {
|
||||
matches!(config.kind.as_str(), "python" | "pytest" | "django-test") || is_python_command(program)
|
||||
matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") || is_python_command(program)
|
||||
}
|
||||
|
||||
/// Whether the configuration's `JAVA_HOME` is the one Settings choose (the Maven runner JRE,
|
||||
@@ -2038,7 +2067,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
|
||||
resolve_run_command(c, root, s);
|
||||
let mut path_dirs: Vec<PathBuf> = Vec::new();
|
||||
match c.kind.as_str() {
|
||||
"python" | "pytest" | "django-test" => {
|
||||
"python" | "pytest" | "unittest" | "django-test" => {
|
||||
let command = Path::new(&c.command);
|
||||
let own = !c.detected && command.components().count() > 1 && is_python_command(&c.command);
|
||||
let python = if own {
|
||||
@@ -2056,7 +2085,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
|
||||
let runner_options = runner
|
||||
&& c.args.first().map(String::as_str) == Some("run")
|
||||
&& c.args.get(1).is_some_and(|a| a.starts_with('-'));
|
||||
if (c.kind == "python" || c.kind == "django-test")
|
||||
if matches!(c.kind.as_str(), "python" | "unittest" | "django-test")
|
||||
&& !runner_options
|
||||
&& (runner || is_python_command(&c.command))
|
||||
{
|
||||
@@ -2689,6 +2718,47 @@ mod maven_linkage_tests {
|
||||
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vtsls_probes_the_tsconfig_plugins_but_not_its_global_ones() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, data) = (tmp.path().join("app"), tmp.path().join("data"));
|
||||
std::fs::create_dir_all(root.join("node_modules/next")).unwrap();
|
||||
std::fs::create_dir_all(root.join("node_modules/@vue/typescript-plugin")).unwrap();
|
||||
let vtsls = || {
|
||||
let mut cfg = custom_server("vtsls", &LanguageServerSettings::default());
|
||||
cfg.tsserver_project = true;
|
||||
merge_init_options(
|
||||
&mut cfg,
|
||||
json!({ "vtsls": { "tsserver": { "globalPlugins": [{ "name": vue::PLUGIN }] } } }),
|
||||
);
|
||||
cfg
|
||||
};
|
||||
let probed = |cfg: &LanguageServerConfig| {
|
||||
serde_json::to_value(&cfg.initialization_options)
|
||||
.unwrap()
|
||||
.pointer("/typescript/tsserver/pluginPaths")
|
||||
.cloned()
|
||||
};
|
||||
std::fs::write(root.join("tsconfig.json"), r#"{"compilerOptions":{"strict":true}}"#).unwrap();
|
||||
let mut cfg = vtsls();
|
||||
assert!(!configure_tsconfig_plugins(&mut cfg, &root, &data));
|
||||
assert_eq!(probed(&cfg), None);
|
||||
|
||||
let plugins = format!(r#"[{{"name":"next"}},{{"name":"{}"}}]"#, vue::PLUGIN);
|
||||
std::fs::write(root.join("tsconfig.json"), format!(r#"{{"compilerOptions":{{"plugins":{plugins}}}}}"#))
|
||||
.unwrap();
|
||||
let mut cfg = vtsls();
|
||||
assert!(configure_tsconfig_plugins(&mut cfg, &root, &data));
|
||||
let location = PathBuf::from(probed(&cfg).unwrap()[0].as_str().unwrap());
|
||||
assert!(location.starts_with(&data) && location.join("node_modules/next/index.js").is_file());
|
||||
// The IDE's Vue plugin is not replaced by the project's.
|
||||
assert!(!location.join("node_modules").join(vue::PLUGIN).exists());
|
||||
// TypeScript 7's native server hosts no plugins.
|
||||
let mut native = vtsls();
|
||||
native.tsserver_project = false;
|
||||
assert!(!configure_tsconfig_plugins(&mut native, &root, &data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typescript_7_keeps_vtsls_when_the_vue_server_is_installed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -22,12 +22,14 @@ pub mod libraries;
|
||||
pub mod locate;
|
||||
pub mod lombok;
|
||||
pub mod maven_profiles;
|
||||
mod mdx;
|
||||
mod npm;
|
||||
mod path_aliases;
|
||||
pub mod php;
|
||||
pub mod pinned;
|
||||
pub mod python;
|
||||
pub mod ruby;
|
||||
mod tsconfig_plugins;
|
||||
mod vue;
|
||||
mod zig;
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//! The MDX language server (Volar) refuses to start without `typescript.tsdk`.
|
||||
|
||||
use crate::apply::{merge_init_options, setting_path, tsdk};
|
||||
use crate::discover::workspace_tsdk;
|
||||
use crate::npm::{own_typescript, package_dir};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::tool_path::{find_command, search_path};
|
||||
use ide_language::LanguageServerConfig;
|
||||
use serde_json::json;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) const SERVER: &str = "mdx-language-server";
|
||||
|
||||
/// The TypeScript vtsls runs with: the selected version, else vtsls' bundled one.
|
||||
/// Without vtsls, the one installed with the server, then the project's.
|
||||
pub(crate) fn configure(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
|
||||
let explicit = |o: Option<&toml::Value>| o.and_then(|o| o.get("typescript")?.get("tsdk")).is_some();
|
||||
let overridden = s.language_servers.get(SERVER).and_then(|ls| ls.initialization_options.as_ref());
|
||||
if explicit(cfg.initialization_options.as_ref())
|
||||
|| overridden.is_some_and(|o| o.pointer("/typescript/tsdk").is_some())
|
||||
{
|
||||
return;
|
||||
}
|
||||
let search = cfg.env.get("PATH").map_or_else(search_path, OsString::from);
|
||||
// Missing servers keep the normal install hint.
|
||||
let Some(bin) = find_command(&cfg.command, &search, server_root) else { return };
|
||||
let bundled = |command: &Path, package: &str| own_typescript(&package_dir(command, package)?);
|
||||
let vtsls = s
|
||||
.tool_path("vtsls")
|
||||
.and_then(|p| setting_path(root, p))
|
||||
.or_else(|| find_command("vtsls", &search, server_root));
|
||||
let lib = tsdk(server_root, s)
|
||||
.or_else(|| tsdk(root, s))
|
||||
.or_else(|| bundled(vtsls.as_deref()?, "@vtsls/language-server"))
|
||||
.or_else(|| bundled(&bin, "@mdx-js/language-server"))
|
||||
.or_else(|| workspace_tsdk(server_root))
|
||||
.or_else(|| workspace_tsdk(root));
|
||||
match lib {
|
||||
Some(lib) => merge_init_options(cfg, json!({ "typescript": { "tsdk": lib.to_string_lossy() } })),
|
||||
None => {
|
||||
cfg.launch_error = Some(
|
||||
"MDX Language Server needs TypeScript. Install typescript@6 in the project or select a TypeScript lib directory in Settings."
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::LanguageId;
|
||||
use ide_language::LanguageRegistry;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn touch(path: &Path) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "{}").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::fs::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
fn bin(dir: &Path, name: &str) {
|
||||
touch(&dir.join("node_modules/.bin").join(if cfg!(windows) { format!("{name}.cmd") } else { name.into() }));
|
||||
}
|
||||
|
||||
/// An npm install of `package` with command `bin` under `dir`, and its TypeScript lib.
|
||||
fn install(dir: &Path, package: &str, bin: &str, typescript: &Path) -> PathBuf {
|
||||
self::bin(dir, bin);
|
||||
touch(&dir.join("node_modules").join(package).join("package.json"));
|
||||
let lib = typescript.join("node_modules/typescript/lib");
|
||||
touch(&lib.join("typescript.js"));
|
||||
touch(&lib.join("tsserver.js"));
|
||||
lib
|
||||
}
|
||||
|
||||
fn sdk(root: &Path, path: &[&Path], settings: &Settings) -> LanguageServerConfig {
|
||||
let reg = LanguageRegistry::load(None).unwrap();
|
||||
let mut cfg = reg.get(&LanguageId::new("mdx")).unwrap().language_servers.remove(0);
|
||||
let bins: Vec<PathBuf> = path.iter().map(|p| p.join("node_modules/.bin")).collect();
|
||||
cfg.env.insert("PATH".into(), std::env::join_paths(bins).unwrap().to_string_lossy().into_owned());
|
||||
configure(&mut cfg, root, root, settings);
|
||||
cfg
|
||||
}
|
||||
|
||||
fn tsdk_of(cfg: &LanguageServerConfig) -> Option<PathBuf> {
|
||||
let options = cfg.initialization_options.as_ref()?;
|
||||
assert_eq!(options.get("typescript")?.get("enabled")?.as_bool(), Some(true));
|
||||
Some(PathBuf::from(options.get("typescript")?.get("tsdk")?.as_str()?))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_the_typescript_of_vtsls_then_its_own_then_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (mdx, vtsls, project) = (t.join("mdx"), t.join("vtsls"), t.join("project"));
|
||||
let own = install(&mdx, "@mdx-js/language-server", SERVER, &mdx);
|
||||
let vtsls_lib =
|
||||
install(&vtsls, "@vtsls/language-server", "vtsls", &vtsls.join("node_modules/@vtsls/language-server"));
|
||||
let workspace = project.join("node_modules/typescript/lib");
|
||||
touch(&workspace.join("tsserver.js"));
|
||||
let mut settings = Settings::default();
|
||||
|
||||
assert_eq!(tsdk_of(&sdk(&project, &[&mdx], &settings)), Some(own));
|
||||
assert_eq!(tsdk_of(&sdk(&project, &[&mdx, &vtsls], &settings)), Some(vtsls_lib));
|
||||
settings.languages.typescript.version = "workspace".into();
|
||||
assert_eq!(tsdk_of(&sdk(&project, &[&mdx, &vtsls], &settings)), Some(workspace));
|
||||
|
||||
// Missing server: the usual install hint, nothing derived.
|
||||
let missing = sdk(&project, &[&vtsls], &settings);
|
||||
assert_eq!((tsdk_of(&missing), missing.launch_error), (None, None));
|
||||
// No TypeScript anywhere.
|
||||
let bare = t.join("bare");
|
||||
bin(&bare, SERVER);
|
||||
let none = sdk(&t.join("empty"), &[&bare], &Settings::default());
|
||||
assert_eq!(tsdk_of(&none), None);
|
||||
assert!(none.launch_error.unwrap().contains("TypeScript"));
|
||||
}
|
||||
}
|
||||
@@ -564,6 +564,7 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
run("django-test", "uv", &["run", "python", "manage.py", "test"]),
|
||||
run("django-test", ".venv/bin/python", &["manage.py", "test", "polls"]),
|
||||
run("python", "uv", &["run", "--with", "rich", "--no-sync", "main.py"]),
|
||||
run("unittest", "uv", &["run", "python", "-m", "unittest", "tests"]),
|
||||
];
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
assert_eq!(configs[0].command, python);
|
||||
@@ -581,6 +582,8 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
// uv's own options stay with uv (#5874).
|
||||
assert_eq!(configs[7].command, "uv");
|
||||
assert_eq!(configs[7].args, ["run", "--with", "rich", "--no-sync", "main.py"]);
|
||||
assert_eq!(configs[8].command, python);
|
||||
assert_eq!(configs[8].args, ["-m", "unittest", "tests"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -594,7 +597,7 @@ fn saved_python_configs_keep_their_explicit_interpreter() {
|
||||
settings.languages.python.interpreter = default.to_string_lossy().into_owned();
|
||||
|
||||
for command in [&override_python, relative_python] {
|
||||
for kind in ["python", "pytest", "django-test"] {
|
||||
for kind in ["python", "pytest", "unittest", "django-test"] {
|
||||
let command = command.to_string_lossy();
|
||||
let mut config = run(kind, &command, &["main.py"]);
|
||||
config.detected = false;
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! The tsserver plugins a project's tsconfig.json / jsconfig.json declares
|
||||
//! (`compilerOptions.plugins`, e.g. Next.js' `{ "name": "next" }`). tsserver looks for them
|
||||
//! next to the TypeScript it runs from and in its plugin probe locations only, so with the
|
||||
//! bundled TypeScript they are never found unless the project's folder is a probe location.
|
||||
//! Language servers run in trusted projects only, so untrusted ones never load them.
|
||||
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const CONFIGS: [&str; 2] = ["tsconfig.json", "jsconfig.json"];
|
||||
|
||||
/// The plugins that the tsconfig.json / jsconfig.json files under a server root declare.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Declared {
|
||||
/// The plugins' packages by name, resolved as tsserver resolves a plugin from a probe
|
||||
/// location: `node_modules` in the configuration's folder or above.
|
||||
pub packages: BTreeMap<String, PathBuf>,
|
||||
/// The text of the configurations declaring them, with what they extend. When one changes,
|
||||
/// tsserver applies its plugins again on top of the loaded ones (each diagnostic of the
|
||||
/// Next.js plugin shows once more), so the probe location changes and vtsls restarts.
|
||||
pub sources: String,
|
||||
}
|
||||
|
||||
/// The plugins that the configurations under `server_root` declare. Logs the ones that are
|
||||
/// not installed; tsserver skips them.
|
||||
pub(crate) fn declared(server_root: &Path) -> Declared {
|
||||
// ponytail: bounded walk, as the path aliases'; deeper workspace members keep the old behaviour.
|
||||
const MAX_DEPTH: usize = 4;
|
||||
const MAX_ENTRIES: usize = 50_000;
|
||||
let mut walker = ignore::WalkBuilder::new(server_root);
|
||||
walker
|
||||
.max_depth(Some(MAX_DEPTH))
|
||||
.require_git(ide_core::ignored::inside_git_repo(server_root))
|
||||
.follow_links(false)
|
||||
.filter_entry(|e| e.file_name() != "node_modules");
|
||||
let mut configs: Vec<PathBuf> = walker
|
||||
.build()
|
||||
.take(MAX_ENTRIES)
|
||||
.flatten()
|
||||
.filter(|e| CONFIGS.iter().any(|c| e.file_name() == *c))
|
||||
.map(|e| e.into_path())
|
||||
.collect();
|
||||
configs.sort();
|
||||
// ponytail: one package per name; a monorepo with two versions of a plugin gets the first one's.
|
||||
let mut declared = Declared::default();
|
||||
for config in configs {
|
||||
let Some(dir) = config.parent() else { continue };
|
||||
let mut sources = String::new();
|
||||
let names = plugins(&config, 0, &mut sources);
|
||||
if !names.is_empty() {
|
||||
declared.sources.push_str(&sources);
|
||||
}
|
||||
for name in names.into_iter().filter(|n| package_name(n)) {
|
||||
match dir.ancestors().map(|d| d.join("node_modules").join(&name)).find(|p| p.is_dir()) {
|
||||
Some(package) => {
|
||||
declared.packages.entry(name).or_insert(package);
|
||||
}
|
||||
None => tracing::warn!("vtsls: tsserver plugin `{name}` from {} is not installed", config.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
declared
|
||||
}
|
||||
|
||||
/// A plugin probe location under `data_dir` holding a package for each of the `declared`
|
||||
/// plugins that loads the project's one, and nothing else: packages the project has under the
|
||||
/// names of the IDE's global plugins never shadow those, as the project folder itself would
|
||||
/// (vtsls puts `pluginPaths` before the global plugins' locations). Named after its contents
|
||||
/// and the declaring configurations, so a change is a new location (and a configuration change
|
||||
/// that restarts vtsls). `None` without plugins or when it cannot be written.
|
||||
pub(crate) fn probe_location(data_dir: &Path, server_root: &Path, declared: &Declared) -> Option<PathBuf> {
|
||||
let plugins = &declared.packages;
|
||||
if plugins.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let parent = data_dir.join("tsplugins").join("project").join(key(&server_root.to_string_lossy()));
|
||||
let location = parent.join(key(&format!("{}{}", serde_json::to_string(plugins).ok()?, declared.sources)));
|
||||
for (name, package) in plugins {
|
||||
let dir = location.join("node_modules").join(name);
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
let index = format!("module.exports = require({});\n", Value::from(package.to_string_lossy()));
|
||||
let manifest = serde_json::json!({ "name": name, "main": "index.js" }).to_string();
|
||||
for (file, content) in [("index.js", index), ("package.json", manifest)] {
|
||||
if std::fs::read(dir.join(file)).ok().as_deref() != Some(content.as_bytes()) {
|
||||
std::fs::write(dir.join(file), content).ok()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The previous contents: a running tsserver loaded its plugins already.
|
||||
for old in std::fs::read_dir(&parent).into_iter().flatten().flatten() {
|
||||
if old.path() != location {
|
||||
let _ = std::fs::remove_dir_all(old.path());
|
||||
}
|
||||
}
|
||||
Some(location)
|
||||
}
|
||||
|
||||
fn key(text: &str) -> String {
|
||||
Sha256::digest(text.as_bytes()).iter().take(8).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// An npm package name (`next`, `@scope/name`): it becomes a path under the data dir.
|
||||
fn package_name(name: &str) -> bool {
|
||||
let parts: Vec<&str> = name.split('/').collect();
|
||||
let part = |p: &str| {
|
||||
!p.is_empty() && p != "." && p != ".." && p.chars().all(|c| c.is_ascii_alphanumeric() || "-._~".contains(c))
|
||||
};
|
||||
match parts.as_slice() {
|
||||
[name] => part(name),
|
||||
[scope, name] => scope.strip_prefix('@').is_some_and(part) && part(name),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `compilerOptions.plugins` names of `config`, else of the configurations it `extends`
|
||||
/// (the last of an `extends` array that has some wins, as tsc merges them). Appends the text
|
||||
/// of each file read, the whole `extends` chain, to `read`.
|
||||
fn plugins(config: &Path, depth: usize, read: &mut String) -> Vec<String> {
|
||||
let Ok(text) = std::fs::read_to_string(config) else { return Vec::new() };
|
||||
read.push_str(&text);
|
||||
let Ok(json) = serde_json::from_str::<Value>(&ide_core::jsonc::strip(&text)) else { return Vec::new() };
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let extends = match json.get("extends") {
|
||||
Some(Value::String(s)) => vec![s.as_str()],
|
||||
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let inherited: Vec<Vec<String>> = if depth > 8 {
|
||||
Vec::new()
|
||||
} else {
|
||||
extends.into_iter().filter_map(|spec| extended(dir, spec)).map(|base| plugins(&base, depth + 1, read)).collect()
|
||||
};
|
||||
match json.pointer("/compilerOptions/plugins").and_then(Value::as_array) {
|
||||
Some(own) => own.iter().filter_map(|p| p.get("name")?.as_str().map(str::to_owned)).collect(),
|
||||
None => inherited.into_iter().rev().find(|p| !p.is_empty()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file an `extends` entry names: a path relative to `dir`, or a package's file
|
||||
/// (`@tsconfig/next/tsconfig.json`, or a package's own `tsconfig.json`) in `node_modules`.
|
||||
fn extended(dir: &Path, spec: &str) -> Option<PathBuf> {
|
||||
let candidates = |base: PathBuf| [base.clone(), base.with_extension("json"), base.join("tsconfig.json")];
|
||||
if spec.starts_with('.') || Path::new(spec).is_absolute() {
|
||||
return candidates(dir.join(spec)).into_iter().find(|p| p.is_file());
|
||||
}
|
||||
dir.ancestors().flat_map(|d| candidates(d.join("node_modules").join(spec))).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(root: &Path, file: &str, text: &str) {
|
||||
let path = root.join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_plugins_resolve_to_the_project_packages() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "package.json", "{}");
|
||||
// A monorepo: the root tsconfig has no plugins, the Next.js app (comments, trailing commas) has.
|
||||
write(root, "tsconfig.json", r#"{ "compilerOptions": { "strict": true } }"#);
|
||||
write(
|
||||
root,
|
||||
"apps/web/tsconfig.json",
|
||||
"{\n // Next.js\n \"compilerOptions\": { \"plugins\": [{ \"name\": \"next\" },] } }",
|
||||
);
|
||||
write(root, "apps/web/node_modules/next/package.json", "{}");
|
||||
// Inherited from a shared configuration, in a package and in a relative file; resolved upwards.
|
||||
write(root, "apps/docs/tsconfig.json", r#"{ "extends": ["../../tsconfig.json", "@acme/tsconfig/next.json"] }"#);
|
||||
write(
|
||||
root,
|
||||
"node_modules/@acme/tsconfig/next.json",
|
||||
r#"{ "compilerOptions": { "plugins": [{ "name": "@acme/plugin" }] } }"#,
|
||||
);
|
||||
write(root, "node_modules/@acme/plugin/package.json", "{}");
|
||||
write(root, "apps/api/jsconfig.json", r#"{ "extends": "./base" }"#);
|
||||
write(
|
||||
root,
|
||||
"apps/api/base.json",
|
||||
r#"{ "compilerOptions": { "plugins": [{ "name": "missing-plugin" }, { "name": "../../escape" }] } }"#,
|
||||
);
|
||||
// An empty list overrides the inherited one; node_modules is never searched for configurations.
|
||||
write(
|
||||
root,
|
||||
"apps/plain/tsconfig.json",
|
||||
r#"{ "extends": "../api/base.json", "compilerOptions": { "plugins": [] } }"#,
|
||||
);
|
||||
write(root, "node_modules/x/tsconfig.json", r#"{ "compilerOptions": { "plugins": [{ "name": "x" }] } }"#);
|
||||
|
||||
let found = declared(root);
|
||||
let expected = [("@acme/plugin", "node_modules/@acme/plugin"), ("next", "apps/web/node_modules/next")];
|
||||
assert_eq!(found.packages, expected.map(|(n, p)| (n.to_owned(), root.join(p))).into_iter().collect());
|
||||
|
||||
// Forwarding packages, replaced when the plugins change.
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
let location = probe_location(data.path(), root, &found).unwrap();
|
||||
let index = std::fs::read_to_string(location.join("node_modules/@acme/plugin/index.js")).unwrap();
|
||||
assert!(index.contains(&serde_json::to_string(&root.join("node_modules/@acme/plugin")).unwrap()), "{index}");
|
||||
let next_only =
|
||||
Declared { packages: found.packages.clone().into_iter().filter(|(n, _)| n == "next").collect(), ..found };
|
||||
let changed = probe_location(data.path(), root, &next_only).unwrap();
|
||||
assert_ne!(changed, location);
|
||||
assert!(!location.exists() && changed.join("node_modules/next/index.js").is_file());
|
||||
// Any edit of a declaring configuration (or one it extends) makes a new location.
|
||||
write(root, "tsconfig.json", r#"{ "compilerOptions": { "strict": false } }"#);
|
||||
let edited =
|
||||
probe_location(data.path(), root, &Declared { sources: declared(root).sources, ..next_only }).unwrap();
|
||||
assert_ne!(edited, changed);
|
||||
assert_eq!(probe_location(data.path(), root, &Declared::default()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_names_are_package_names() {
|
||||
for ok in ["next", "@scope/name", "gql.tada", "@styled/typescript-styled-plugin"] {
|
||||
assert!(package_name(ok), "{ok}");
|
||||
}
|
||||
for bad in ["", "..", "../x", "a/b", "@scope", "@/x", "@scope/..", "a\\b", "/abs"] {
|
||||
assert!(!package_name(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projects_without_plugins_declare_none() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write(tmp.path(), "tsconfig.json", r#"{ "extends": "./missing.json", "compilerOptions": {} }"#);
|
||||
assert!(declared(tmp.path()).packages.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -183,15 +183,10 @@ pub fn arguments(
|
||||
return vec!["format".into(), path];
|
||||
}
|
||||
if tool == "prettier" {
|
||||
let parser = if config.parser == "markdown" && file.extension().is_some_and(|s| s == "mdx") {
|
||||
"mdx"
|
||||
} else {
|
||||
&config.parser
|
||||
};
|
||||
args.extend(
|
||||
[
|
||||
"--parser",
|
||||
parser,
|
||||
config.parser.as_str(),
|
||||
"--config-precedence",
|
||||
"file-override",
|
||||
"--tab-width",
|
||||
|
||||
@@ -447,7 +447,7 @@ impl Http {
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, unix))]
|
||||
pub(crate) fn gh_path(&self) -> Option<&Path> {
|
||||
self.gh.as_deref()
|
||||
}
|
||||
|
||||
@@ -446,6 +446,17 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "some-sass-language-server",
|
||||
display: "Some Sass Language Server",
|
||||
kind: LanguageServer,
|
||||
commands: &["some-sass-language-server"],
|
||||
method: Method::Npm { packages: &["some-sass-language-server"] },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/wkillerud/some-sass",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "vscode-html-language-server",
|
||||
display: "HTML Language Server",
|
||||
@@ -479,6 +490,17 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/withastro/astro/tree/main/packages/language-tools",
|
||||
needs: NODE,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "mdx-language-server",
|
||||
display: "MDX Language Server",
|
||||
kind: LanguageServer,
|
||||
commands: &["mdx-language-server"],
|
||||
method: Method::Npm { packages: &["@mdx-js/language-server", TYPESCRIPT] },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/mdx-js/mdx-analyzer",
|
||||
needs: NODE,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "svelte-language-server",
|
||||
display: "Svelte Language Server",
|
||||
|
||||
@@ -181,6 +181,9 @@ fn everything_missing_on_an_empty_system() {
|
||||
assert!(find(&list, "solargraph").unavailable_reason.as_deref().unwrap().contains("Ruby"));
|
||||
// Shared npm package: each server is its own row.
|
||||
assert_eq!(find(&list, "vscode-css-language-server").install_method.as_deref(), Some("npm"));
|
||||
let sass = find(&list, "some-sass-language-server");
|
||||
assert_eq!(sass.install_method.as_deref(), Some("npm"));
|
||||
assert_eq!(sass.languages, ["Sass"]);
|
||||
assert!(find(&list, "delve").kind == ToolKind::Debugger);
|
||||
}
|
||||
|
||||
@@ -652,6 +655,7 @@ for a in "$@"; do case "$a" in
|
||||
typescript-language-server@latest) n=typescript-language-server;;
|
||||
@vue/language-server@latest) n=vue-language-server; d=@vue/language-server;;
|
||||
@astrojs/language-server@latest) n=astro-ls; d=@astrojs/language-server;;
|
||||
@mdx-js/language-server@latest) n=mdx-language-server; d=@mdx-js/language-server;;
|
||||
*) continue;;
|
||||
esac
|
||||
d="${{d:-$n}}"; /bin/mkdir -p "$prefix/node_modules/$d"
|
||||
@@ -662,7 +666,7 @@ done"#,
|
||||
),
|
||||
);
|
||||
let tools = env.tools();
|
||||
for name in ["vue-language-server", "typescript-language-server", "astro-ls"] {
|
||||
for name in ["vue-language-server", "typescript-language-server", "astro-ls", "mdx-language-server"] {
|
||||
assert_eq!(
|
||||
tools.install(name, &langs(), &CancellationToken::new(), &|_| {}).unwrap().status,
|
||||
ToolStatus::Installed
|
||||
@@ -674,6 +678,7 @@ done"#,
|
||||
}
|
||||
assert!(installs.contains("@vue/language-server@latest"), "{installs}");
|
||||
assert!(installs.contains("@astrojs/language-server@latest"), "{installs}");
|
||||
assert!(installs.contains("@mdx-js/language-server@latest"), "{installs}");
|
||||
|
||||
fs::write(&log, "").unwrap();
|
||||
tools.uninstall("vue-language-server", &langs()).unwrap();
|
||||
|
||||
@@ -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,6 +168,8 @@ 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,
|
||||
@@ -247,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -365,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> {
|
||||
@@ -385,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);
|
||||
}
|
||||
@@ -400,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 {
|
||||
@@ -492,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);
|
||||
@@ -508,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 {
|
||||
@@ -517,6 +560,7 @@ impl Documents {
|
||||
}
|
||||
if let Some((enc, bom)) = ec.encoding()
|
||||
&& empty_file
|
||||
&& !encoding_chosen
|
||||
{
|
||||
(encoding, has_bom) = (enc.to_owned(), bom);
|
||||
}
|
||||
@@ -539,7 +583,8 @@ 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,
|
||||
@@ -617,6 +662,7 @@ impl Documents {
|
||||
dirty: false,
|
||||
can_reload_encoding,
|
||||
encoding_chosen: false,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
@@ -678,6 +724,7 @@ impl Documents {
|
||||
dirty: false,
|
||||
can_reload_encoding: false,
|
||||
encoding_chosen: false,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
@@ -1291,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<()> {
|
||||
@@ -1300,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);
|
||||
@@ -1470,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
|
||||
|
||||
@@ -850,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)?;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -1567,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}");
|
||||
}
|
||||
}
|
||||
@@ -241,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();
|
||||
|
||||
@@ -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 load automatically for the selected authenticated account, and **Apply** / **OK** saves the selection for new sessions.
|
||||
|
||||
**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
|
||||
|
||||
@@ -61,7 +61,7 @@ Language servers that support LSP inline completion show a grey suggestion at th
|
||||
- Hold `⌘` / `Ctrl` and hover over a name to see it underlined as a link, with brief information about it.
|
||||
- Gutter icons mark types and methods that are implemented or overridden (↓) and methods that implement or override another (↑). Click one to go there.
|
||||
- **Navigate › Test** jumps between a class and its tests by naming convention and offers **Create New Test…** when there is none.
|
||||
- **Navigate › Related Symbol…** goes to the files tied to the current one by convention: a C, C++ or Objective-C header and its source file, and in Rails a controller action and its views, a view and its action, a controller and its helper and model, a model and its controller and migrations. With several targets it shows a chooser.
|
||||
- **Navigate › Related Symbol…** goes to the files tied to the current one by convention: a C, C++ or Objective-C header and its source file, and in Rails a controller action and its views, a view and its action, a controller and its helper and model, a model and its controller and migrations, and a JavaScript or TypeScript component and the files beside it with the same name (an Angular component's template, styles and spec, or its `templateUrl` / `styleUrls`; `Button.tsx` and `Button.module.css`, `Button.test.tsx`, `Button.stories.tsx`). With several targets it shows a chooser.
|
||||
- In Rails, **Go to Declaration** also follows method symbols in callbacks (`before_action :load_user`, `if: :admin?`) to their `def`, and controller actions in `config/routes.rb` (`to: "users#index"`, `resources :users`) to the controller.
|
||||
|
||||
Going to files, classes and symbols by name is covered in [Search and navigation](/en/guide/search).
|
||||
@@ -75,7 +75,7 @@ Going to files, classes and symbols by name is covered in [Search and navigation
|
||||
| **Highlight Usages in File** | `⇧⌘F7` | `Ctrl+Shift+F7` |
|
||||
| **Next Highlighted Usage** / **Previous** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` |
|
||||
|
||||
**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. **Recent Find Usages** (from Find Action) lists the last ten searches, including those whose tab was closed, and runs the chosen one again. The occurrences of the symbol under the caret are highlighted in the editor as you move.
|
||||
**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. **Recent Find Usages** (from Find Action) lists the last ten searches, including those whose tab was closed, and runs the chosen one again. **Export to Text File** in the tool window's toolbar saves the results as shown (with the access filter applied, without excluded usages) to a text file. The occurrences of the symbol under the caret are highlighted in the editor as you move.
|
||||
|
||||
Above declarations, a **N usages** hint and the last author of the code (from Git blame) are shown, with the date of that last change. Turn them off under **Code Vision** in **Settings › Editor › Inlay Hints**.
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
|
||||
- Drag with `⌥` / `Alt` held (or with the middle mouse button on macOS and Windows) to make a rectangular selection without switching modes.
|
||||
- **Extend Selection** grows the selection to the enclosing word, expression, statement and block, using the syntax tree.
|
||||
- **Swap Selection Boundaries** moves the caret of each selection to its other end and keeps the text selected, so `⇧` / `Shift` with the arrow keys then extends or shrink it from that side. It has no default shortcut.
|
||||
- **Toggle Sticky Selection** starts a selection at each caret: arrow keys and other caret moves then extend it as if `⇧` / `Shift` were held. Run it again or press `Esc` to turn it off, which also removes the selection. Copying or editing the text turns it off too. It has no default shortcut.
|
||||
- **Select Line at Caret** selects the whole line at each caret together with its line break; a selection grows to the whole lines it touches. It has no default shortcut.
|
||||
|
||||
## Editing lines and code
|
||||
@@ -57,10 +58,12 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
|
||||
|
||||
**Move Caret to Next Word** / **Previous Word in Different "CamelHumps" Mode** (and their **with Selection** variants), **Delete to Word Start** and **Delete to Word End in Different "CamelHumps" Mode** move or delete by word the other way from **Settings › Editor › General › Smart Keys › Use "CamelHumps" words**: by hump (`parse|HTML|Document`) while it is off, by whole word while it is on. They have no default shortcut.
|
||||
|
||||
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
|
||||
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones. **Delete Duplicate Lines** works on the same lines and keeps only the first of each repeated line (the text must match exactly, whitespace included); run it from **Find Action** or assign a shortcut in **Settings › Keymap**.
|
||||
|
||||
**Cut up to Line End** cuts from each caret to the end of its line, together with the line break when only whitespace is left (or the caret is already at the line end), so pressing it again on the same caret cuts the next line too; those repeated cuts collect into one clipboard entry. **Delete to Line Start** and **Delete to Line End** delete the same way without copying (to the line start, or the line break before the caret at the line start), or delete the selection. They have no default shortcut except in the Eclipse keymaps (`⇧⌘⌦` / `Ctrl+Shift+Delete` for Delete to Line End).
|
||||
|
||||
**Kill to Word Start** and **Kill to Word End** cut from each caret back to the start of the previous word or on to the end of the next one, together with the whitespace and line breaks in between; with **Settings › Editor › General › Smart Keys › Use "CamelHumps" words** on they stop at humps (`parse|HTML|Document`). A selection is ignored. Repeated cuts at the same caret, and Cut up to Line End there, collect into one clipboard entry, the ones to the word start in front. They have no default shortcut.
|
||||
|
||||
**Hungry Backspace** deletes all the spaces, tabs and line breaks before each caret in one go, up to the previous non-whitespace character; after anything else, or with a selection, it works like `⌫` / `Backspace`. It has no default shortcut.
|
||||
|
||||
**Duplicate Entire Lines** copies every line touched by a caret or selection below itself, even when only part of a line is selected, and keeps the selection on the copy. It has no default shortcut; run it from **Find Action** or assign one in **Settings › Keymap**.
|
||||
@@ -149,11 +152,13 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
| ------------------------------------- | ----- | --------------- |
|
||||
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **Increase Font Size in All Editors** | `⌃⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size in All Editors** | `⌃⇧,` | `Alt+Shift+,` |
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll Left** | — | — |
|
||||
| **Scroll Right** | — | — |
|
||||
| **Scroll Up and Move if Necessary** | — | — |
|
||||
| **Scroll Down and Move if Necessary** | — | — |
|
||||
| **Move Up and Scroll** | — | — |
|
||||
@@ -161,10 +166,10 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
|
||||
| **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 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**.
|
||||
**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 Left** and **Scroll Right** do the same sideways, by one column. **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**.
|
||||
- **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). **Increase Font Size in All Editors** and **Decrease Font Size in All Editors** resize every open editor together, starting from the active one, and have no default shortcut. 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**.
|
||||
- **View › Appearance › Enter Distraction Free Mode** hides tool windows, tabs, the status bar and the gutter and centres the text. Run the same command again to leave.
|
||||
- **View › Appearance › Enter Zen Mode** turns on Distraction Free Mode and full screen together; **Exit Zen Mode** turns both off.
|
||||
- **Show Line Numbers**, **Show Indent Guides**, **Show Sticky Lines** and **Show Whitespaces** turn these on or off in every editor. Run them from Find Action, or right-click the gutter and open **Appearance**.
|
||||
|
||||
@@ -24,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>
|
||||
|
||||
|
||||
@@ -163,6 +163,7 @@ Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **R
|
||||
|
||||
- File paths and stack trace frames in the output are links. **Up the Stack Trace** / **Down the Stack Trace** in the toolbar (or **Previous / Next Occurrence**, `⌥⌘↑` / `⌥⌘↓`, `Ctrl+Alt+↑` / `Ctrl+Alt+↓` on Windows and Linux) select the previous / next one and open it; links in collapsed folds are skipped. In a test run these keys go through the failed tests instead.
|
||||
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern.
|
||||
- **Search with Google** in the console's context menu searches the web for the selected output, such as an error message, in the browser.
|
||||
- Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**.
|
||||
- For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing).
|
||||
|
||||
|
||||
@@ -42,6 +42,8 @@ In HTML, Vue, Svelte, JSX and TSX files, and in CSS, SCSS, Less and Sass, `⇥`
|
||||
|
||||
Templates are edited in **Settings › Editor › Live Templates**.
|
||||
|
||||
To start from existing code, select it and choose **Tools › Save as Live Template…**: a template in the **User** group gets the selection as its text (with `$` written as `$$`) and the file's language as its context, and Settings opens on it.
|
||||
|
||||
<Steps>
|
||||
<Step title="Add a template">
|
||||
Click **Add Template** and enter the **Abbreviation**, **Description** and **Group**.
|
||||
|
||||
@@ -18,7 +18,7 @@ Showing an empty Terminal window opens a tab in the start directory (the project
|
||||
|
||||
- **+** (**New Tab**) opens a tab with the default shell.
|
||||
- The **▾** button (**More Terminal Options**) has **New Terminal Tab**, **New Predefined Session** (one entry per installed shell, plus **SSH Session…**), **Split Right**, **Split Down** and **Settings**.
|
||||
- Right-click a tab for **Rename Session…**, **Move to Editor**, **Close Tab**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it.
|
||||
- Right-click a tab for **Rename Session…**, **Move to Editor**, **Close Tab**, **Close All Tabs**, **Close Other Tabs**, **Split Right**, **Split and Move Right**, **Split Down**, **Split and Move Down** and **Unsplit**. Double-clicking a tab also renames it.
|
||||
- Drag tabs to reorder them, drop a tab on the edge of another group to split, or drag a tab into an editor group (or its edge) to keep the session running as an editor tab. A terminal moved to the editor can return via **Move to Terminal** or by dragging its editor tab onto a Terminal tab strip, pane edge, or the **Terminal** stripe button.
|
||||
|
||||
A tab is named after your custom name, otherwise after the program running in it (when the shell reports it), otherwise `Local`, `Local (2)` and so on. A spinner shows while a command runs; **Exited** or **Failed** shows once the session ends.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -64,7 +64,7 @@ To create a theme or icon theme, see [Themes](/en/plugins/guides/themes) and [Ic
|
||||
- **Enable ligatures** for fonts with programming ligatures.
|
||||
- **Typography Settings**: **Main font weight**, **Bold font weight**, and a **Fallback font** for characters the main font lacks.
|
||||
|
||||
To change the size temporarily in the active editor, use **Increase Font Size** (`⌥⇧.` / `Alt+Shift+.`) and **Decrease Font Size** (`⌥⇧,` / `Alt+Shift+,`); **View › Reset Font Size** (or **View › Reset Font Size in All Editors**) goes back. In **Settings › Editor › General**, **Change font size with Ctrl/Command+Mouse Wheel** enables wheel zoom for the **Active editor** (default) or **All editors**.
|
||||
To change the size temporarily, use **Increase Font Size in All Editors** (`⌃⇧.` / `Alt+Shift+.`) and **Decrease Font Size in All Editors** (`⌃⇧,` / `Alt+Shift+,`), or **Increase Font Size** / **Decrease Font Size** from Find Action for the active editor only; **View › Reset Font Size** (or **View › Reset Font Size in All Editors**) goes back. In **Settings › Editor › General**, **Change font size with Ctrl/Command+Mouse Wheel** enables wheel zoom for the **Active editor** (default) or **All editors**.
|
||||
|
||||
### UI font and zoom
|
||||
|
||||
|
||||
@@ -138,7 +138,7 @@ The toolbar switches between **Side-by-side Viewer** and **Unified Viewer**, and
|
||||
Other ways to compare:
|
||||
|
||||
- **Compare with Branch or Revision…** and **Compare with Revision…** for the current file, or for folders (a list of changed files).
|
||||
- **Compare With…** (`⌘D` / `Ctrl+D` in the Project view), **Compare Files**, **Compare Directories** (with copy left/right) and **View › Compare with Clipboard**.
|
||||
- **Compare With…** (`⌘D` / `Ctrl+D` in the Project view), **Compare Files**, **Compare File with Editor** (the selected file against the active editor's, at its caret), **Compare Directories** (with copy left/right) and **View › Compare with Clipboard**.
|
||||
|
||||
## Branches
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ The IDE never needs `sudo`. It installs tools into its own tools folder in the l
|
||||
|
||||
| Method | Used for |
|
||||
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| npm | Node-based servers such as vtsls, Pyright, Intelephense, the Vue, Svelte, Astro, Angular, CSS, HTML, JSON, YAML, Bash and Dockerfile servers. Needs Node.js. |
|
||||
| npm | Node-based servers such as vtsls, Pyright, Intelephense, the Vue, Svelte, Astro, MDX, Angular, CSS, Sass, HTML, JSON, YAML, Bash and Dockerfile servers. Needs Node.js. |
|
||||
| pip into a private virtualenv | basedpyright, ty, pyrefly, Ruff (uses `uv` when available). |
|
||||
| pip into a private folder | debugpy. |
|
||||
| `go install` | gopls, Delve, sqls. Needs Go. |
|
||||
@@ -143,6 +143,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | Yes | Yes | **lua-language-server** | — |
|
||||
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | Yes | Yes | — | — |
|
||||
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | Yes | Yes | **marksman** | — |
|
||||
| MDX | `mdx` | `.mdx` | Yes | Yes | **mdx-language-server** | — |
|
||||
| Nix | `nix` | `.nix` | Yes | Yes | nil → nixd | — |
|
||||
| Objective-C | `objective-c` | `.m` | Yes | — | **clangd** | lldb-dap |
|
||||
| Objective-C++ | `objective-cpp` | `.mm` | Yes | — | **clangd** | lldb-dap |
|
||||
@@ -160,7 +161,7 @@ The table lists every built-in language definition. Server and debugger names in
|
||||
| reStructuredText | `restructuredtext` | `.rst` | Yes | — | — | — |
|
||||
| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | Yes | Yes | **ruby-lsp** → **solargraph** | rdbg |
|
||||
| Rust | `rust` | `.rs` | Yes | Yes | **rust-analyzer** | **codelldb** |
|
||||
| Sass | `sass` | `.sass` | Yes | — | — | — |
|
||||
| Sass | `sass` | `.sass` | Yes | — | **some-sass-language-server** | — |
|
||||
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | Yes | Yes | metals | — |
|
||||
| SCSS | `scss` | `.scss` | Yes | — | **vscode-css-language-server** + **stylelint** | — |
|
||||
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | Yes | Yes | **bash-language-server** | **bash-debug** |
|
||||
|
||||
@@ -89,6 +89,8 @@ With **Automatic**, a JavaScript or TypeScript file below the tool's own configu
|
||||
|
||||
**Settings › Editor › Code Style › JavaScript** and **TypeScript** have **Spaces** (after commas, around operators, within braces and so on) and **Punctuation** (semicolons: keep, use or don't use; quotes: as in the file, single or double). They are saved per project with the other code style settings and sent to the TypeScript server, which applies them to **Reformat Code** and to the code it adds: quick fixes, auto-imports, refactorings and **Optimize Imports**. JSX files follow JavaScript and TSX files TypeScript. When EditorConfig support is on, the project's `.editorconfig` comes first where it sets `quote_type` or the IntelliJ properties `ij_typescript_use_semicolon_after_statement`, `ij_typescript_use_double_quotes`, `ij_typescript_space_after_comma`, `ij_typescript_spaces_within_object_literal_braces` and the like (`ij_javascript_*` for JavaScript). tsserver has no trailing-comma option, so trailing commas stay as written.
|
||||
|
||||
The **Imports** tab sets how the TypeScript server writes the imports it adds (auto-import, quick fixes, moving files): **Import paths** (shortest, relative, non-relative through `paths` / `baseUrl`, or relative within the project), **Import path ending** (automatic, `./components`, `./components/index` or `./components/index.js`), **Do not auto-import from** (globs such as `**/index.ts` to keep barrel files out) and **Do not auto-import specifiers matching** (regular expressions for the import path, such as `^node:`). Like the other tabs, they are saved per project, separately for JavaScript and TypeScript, and apply to a running server without a restart.
|
||||
|
||||
### Biome lint
|
||||
|
||||
In a Biome project, Biome's diagnostics show in the editor and the Problems tool window, and `⌥⏎` / `Alt+Enter` offers its quick fixes and suppressions. Biome's safe fixes (`source.fixAll.biome`) run with **Code › Code Cleanup** and, when **Settings › Tools › Actions on Save › Run code cleanup** is on, on save. When Biome's formatter is enabled, its fix-all formats the file too.
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -188,19 +188,19 @@ Some shortcuts depend on where the focus is. For example `⌘N` / `Alt+Insert` i
|
||||
|
||||
## Files, tabs and view
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
| -------------------- | ------------ | ----------------------- |
|
||||
| Settings… | `⌘,` | `Ctrl+Alt+S` |
|
||||
| Project Structure… | `⌘;` | `Ctrl+Alt+Shift+S` |
|
||||
| Save All | `⌘S` | `Ctrl+S` |
|
||||
| New Scratch File… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` |
|
||||
| Close Tab | `⌘W` | `Ctrl+F4` |
|
||||
| Select Next Tab | `⌃→` / `⇧⌘]` | `Alt+Right` |
|
||||
| Select Previous Tab | `⌃←` / `⇧⌘[` | `Alt+Left` |
|
||||
| Quick Switch Scheme… | `` ⌃` `` | `` Ctrl+` `` |
|
||||
| Zoom In IDE | `⌃⌥=` | `Alt+Shift+=` |
|
||||
| Zoom Out IDE | `⌃⌥-` | `Alt+Shift+-` |
|
||||
| Reset IDE Zoom | `⌃⌥0` | `Alt+Shift+0` |
|
||||
| Increase Font Size | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| Decrease Font Size | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| Toggle Full Screen | `⌃⌘F` | — |
|
||||
| Action | macOS | Windows / Linux |
|
||||
| --------------------------------- | ------------ | ----------------------- |
|
||||
| Settings… | `⌘,` | `Ctrl+Alt+S` |
|
||||
| Project Structure… | `⌘;` | `Ctrl+Alt+Shift+S` |
|
||||
| Save All | `⌘S` | `Ctrl+S` |
|
||||
| New Scratch File… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` |
|
||||
| Close Tab | `⌘W` | `Ctrl+F4` |
|
||||
| Select Next Tab | `⌃→` / `⇧⌘]` | `Alt+Right` |
|
||||
| Select Previous Tab | `⌃←` / `⇧⌘[` | `Alt+Left` |
|
||||
| Quick Switch Scheme… | `` ⌃` `` | `` Ctrl+` `` |
|
||||
| Zoom In IDE | `⌃⌥=` | `Alt+Shift+=` |
|
||||
| Zoom Out IDE | `⌃⌥-` | `Alt+Shift+-` |
|
||||
| Reset IDE Zoom | `⌃⌥0` | `Alt+Shift+0` |
|
||||
| Increase Font Size in All Editors | `⌃⇧.` | `Alt+Shift+.` |
|
||||
| Decrease Font Size in All Editors | `⌃⇧,` | `Alt+Shift+,` |
|
||||
| Toggle Full Screen | `⌃⌘F` | — |
|
||||
@@ -132,6 +132,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。
|
||||
|
||||
对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。选择已验证的账号后,**新任务**会自动加载该账号对应的可用模型列表,点击**应用**或**确定**保存以供新会话使用。
|
||||
|
||||
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
|
||||
### 外部 MCP 服务器
|
||||
|
||||
@@ -61,7 +61,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
|
||||
- 按住 `⌘` / `Ctrl` 把鼠标悬停在名称上,名称会显示为链接,并附带简要信息。
|
||||
- 装订区域的图标标出被实现或被重写的类型和方法(↓),以及实现或重写了其他方法的方法(↑),单击即可跳转。
|
||||
- **导航 › 测试** 按命名约定在类和它的测试之间跳转;还没有测试时会提供 **创建新测试…**。
|
||||
- **导航 › 相关符号…** 跳到按约定与当前文件相关的文件:C、C++、Objective-C 的头文件和源文件,以及 Rails 中控制器动作与其视图、视图与其动作、控制器与其辅助模块和模型、模型与其控制器和迁移。有多个目标时显示选择列表。
|
||||
- **导航 › 相关符号…** 跳到按约定与当前文件相关的文件:C、C++、Objective-C 的头文件和源文件,以及 Rails 中控制器动作与其视图、视图与其动作、控制器与其辅助模块和模型、模型与其控制器和迁移,以及 JavaScript / TypeScript 组件与同一文件夹中同名的文件(Angular 组件的模板、样式和 spec,或其 `templateUrl` / `styleUrls`;`Button.tsx` 与 `Button.module.css`、`Button.test.tsx`、`Button.stories.tsx`)。有多个目标时显示选择列表。
|
||||
- 在 Rails 中,**转到声明** 还能从回调里的方法符号(`before_action :load_user`、`if: :admin?`)跳到对应的 `def`,从 `config/routes.rb` 里的控制器动作(`to: "users#index"`、`resources :users`)跳到控制器。
|
||||
|
||||
按名称跳转到文件、类和符号,见 [搜索与导航](/zh/guide/search)。
|
||||
@@ -75,7 +75,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
|
||||
| **高亮文件中的用法** | `⇧⌘F7` | `Ctrl+Shift+F7` |
|
||||
| **下一个高亮的用法** / **上一个** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` |
|
||||
|
||||
**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。**最近的查找用法**(通过查找操作执行)列出最近十次搜索,包括标签页已关闭的,选中一项即重新运行。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。
|
||||
**查找用法** 把结果按文件分组列在 **查找用法** 工具窗口中,并带预览。**显示用法** 在光标处用弹窗显示。**最近的查找用法**(通过查找操作执行)列出最近十次搜索,包括标签页已关闭的,选中一项即重新运行。工具窗口工具栏中的 **导出到文本文件** 把当前显示的结果(应用访问过滤,不含已排除的用法)保存为文本文件。移动光标时,编辑器会自动高亮光标下符号的所有出现位置。
|
||||
|
||||
声明上方会显示用法数量(如 `3 usages`)和这段代码最后的作者(来自 Git blame),并标注最近一次修改的日期。可以在 **设置 › 编辑器 › 嵌入提示** 的 **Code Vision** 一节中关闭。
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
- 按住 `⌥` / `Alt` 拖动鼠标(macOS 和 Windows 上也可以用鼠标中键拖动)可以直接做矩形选区,不用切换模式。
|
||||
- **扩展选区** 依据语法树逐级扩大到所在的单词、表达式、语句和代码块。
|
||||
- **交换选区边界** 把每个选区的光标移到选区的另一端并保持选中,之后用 `⇧` / `Shift`+方向键即可从这一端扩大或缩小选区。它默认没有快捷键。
|
||||
- **切换粘滞选区** 从每个光标处开始一个选区:之后方向键等光标移动会像按住 `⇧` / `Shift` 一样扩大选区。再执行一次或按 `Esc` 即可关闭,同时取消选区。复制或编辑文本也会关闭它。它默认没有快捷键。
|
||||
- **选择光标所在行** 选中每个光标所在的整行及其换行符;有选区时扩大到选区涉及的所有整行。它默认没有快捷键。
|
||||
|
||||
## 编辑行与代码
|
||||
@@ -59,9 +60,11 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
**剪切到行尾** 从每个光标剪切到所在行的行尾;光标后只剩空白(或光标已在行尾)时连同换行符一起剪切,所以在同一光标处再按一次会剪切下一行,这些连续的剪切合并为剪贴板中的一条内容。**删除到行首** 和 **删除到行尾** 以同样方式删除但不复制(删除到行首时,若光标在行首则删除前面的换行符),有选区时删除选区。除 Eclipse 键位映射(删除到行尾为 `⇧⌘⌦` / `Ctrl+Shift+Delete`)外,它们默认没有快捷键。
|
||||
|
||||
**剪切到词首** 和 **剪切到词尾** 从每个光标向前剪切到上一个单词的开头,或向后剪切到下一个单词的结尾,连同其间的空白和换行符;开启 **设置 › 编辑器 › 常规 › 智能键 › 使用“驼峰”单词** 时按驼峰片段(`parse|HTML|Document`)停下。选区会被忽略。在同一光标处连续剪切(包括剪切到行尾)会合并为剪贴板中的一条内容,剪切到词首的部分排在前面。它们默认没有快捷键。
|
||||
|
||||
**贪婪退格** 一次删除每个光标前的所有空格、制表符和换行符,直到前一个非空白字符;光标前是其他字符或有选区时,它与 `⌫` / `Backspace` 相同。它默认没有快捷键。
|
||||
|
||||
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行(没有选区时为整个文件)重新排序,默认没有快捷键。对行排序按字符编码排序,大写字母排在小写字母之前。
|
||||
**编辑 › 对行排序** 和 **编辑 › 反转行** 对选中的行(没有选区时为整个文件)重新排序,默认没有快捷键。对行排序按字符编码排序,大写字母排在小写字母之前。**删除重复行** 作用于同样的行,每组重复行只保留第一行(文本须完全相同,包括空白);可在查找操作中运行,或在 **设置 › 按键映射** 中分配快捷键。
|
||||
|
||||
**复制整行** 把光标或选区涉及的每一行完整复制到其下方(即使只选中了行的一部分),并让选区落在副本上。它默认没有快捷键,可在查找操作中运行,或在 **设置 › 按键映射** 中分配快捷键。
|
||||
|
||||
@@ -147,11 +150,13 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| ------------------------------ | ----- | --------------- |
|
||||
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **增大所有编辑器中的字体** | `⌃⇧.` | `Alt+Shift+.` |
|
||||
| **减小所有编辑器中的字体** | `⌃⇧,` | `Alt+Shift+,` |
|
||||
| **滚动到中央** | `⌃L` | `Ctrl+M` |
|
||||
| **向上滚动** | — | `Ctrl+Up` |
|
||||
| **向下滚动** | — | `Ctrl+Down` |
|
||||
| **向左滚动** | — | — |
|
||||
| **向右滚动** | — | — |
|
||||
| **向上滚动并在必要时移动光标** | — | — |
|
||||
| **向下滚动并在必要时移动光标** | — | — |
|
||||
| **向上移动并滚动** | — | — |
|
||||
@@ -159,10 +164,10 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
|
||||
| **滚动到顶部** | — | — |
|
||||
| **滚动到底部** | — | — |
|
||||
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**向上移动并滚动** 和 **向下移动并滚动** 把光标移动一行,视图随之滚动同样的距离,光标在屏幕上的位置保持不变;对应的 **并选择** 版本边移动边选择。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
|
||||
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域;**向左滚动** 和 **向右滚动** 以同样方式横向移动一列。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**向上移动并滚动** 和 **向下移动并滚动** 把光标移动一行,视图随之滚动同样的距离,光标在屏幕上的位置保持不变;对应的 **并选择** 版本边移动边选择。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
|
||||
|
||||
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
|
||||
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。**增大所有编辑器中的字体** 和 **减小所有编辑器中的字体** 以当前编辑器为起点同时调整所有打开的编辑器,默认没有快捷键。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
- **视图 › 外观 › 进入无干扰模式** 隐藏工具窗口、标签页、状态栏和装订区域,并让正文居中。再执行一次即可退出。
|
||||
- **视图 › 外观 › 进入 Zen 模式** 同时开启无干扰模式和全屏;**退出 Zen 模式** 同时关闭两者。
|
||||
- **显示行号**、**显示缩进参考线**、**显示粘滞行** 和 **显示空白** 在所有编辑器中打开或关闭对应显示。可从查找操作运行,或右键单击装订区域并打开 **外观**。
|
||||
|
||||
@@ -21,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>
|
||||
|
||||
|
||||
@@ -159,6 +159,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建
|
||||
|
||||
- 输出里的文件路径和堆栈帧都可以点击跳转。工具栏的 **沿堆栈跟踪向上** / **沿堆栈跟踪向下**(或 **上一个 / 下一个匹配项**,`⌥⌘↑` / `⌥⌘↓`,Windows 和 Linux 上为 `Ctrl+Alt+↑` / `Ctrl+Alt+↓`)选中上一个 / 下一个链接并打开它;折叠起来的行里的链接会跳过。测试运行时这两个快捷键改为在失败的测试之间跳转。
|
||||
- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。
|
||||
- 控制台右键菜单中的 **使用 Google 搜索** 会在浏览器中搜索选中的输出(例如一条错误信息)。
|
||||
- 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。
|
||||
- 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。
|
||||
|
||||
|
||||
@@ -42,6 +42,8 @@ items.for → for (var item : items) { … }
|
||||
|
||||
模板在 **设置 › 编辑器 › 实时模板** 中编辑。
|
||||
|
||||
要从已有代码开始,选中代码后选择 **工具 › 另存为实时模板…**:会在 **User** 组中新建一个模板,以选中内容为模板文本(`$` 写成 `$$`),以当前文件的语言为上下文,并在设置中打开它。
|
||||
|
||||
<Steps>
|
||||
<Step title="添加模板">单击 **添加模板**,填写 **缩写**、**描述** 和 **组**。</Step>
|
||||
<Step title="编写模板正文">
|
||||
|
||||
@@ -18,7 +18,7 @@ description: "使用内置终端:标签页、拆分、Shell、链接、查找
|
||||
|
||||
- **+**(**新建标签页**)用默认 Shell 打开一个标签页。
|
||||
- **▾** 按钮(**更多终端选项**)包含 **新建终端标签页**、**新建预定义会话**(每个已安装的 Shell 一项,另有 **SSH 会话…**)、**向右拆分**、**向下拆分** 和 **设置**。
|
||||
- 右键标签页可以 **重命名会话…**、**移至编辑器**、**关闭标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。
|
||||
- 右键标签页可以 **重命名会话…**、**移至编辑器**、**关闭标签页**、**关闭所有标签页**、**关闭其他标签页**、**向右拆分**、**向右拆分并移动**、**向下拆分**、**向下拆分并移动**、**取消拆分**。双击标签页也能重命名。
|
||||
- 拖动标签页可以调整顺序,拖到另一组的边缘会拆分;拖入编辑器分组(或其边缘)则会带着正在运行的会话作为编辑器标签页打开。移到编辑器的终端可通过 **移至终端**,或将编辑器标签拖回终端标签栏、面板边缘或 **终端** 边栏按钮来归位。
|
||||
|
||||
标签页名称优先用你设置的名字,其次是 Shell 报告的正在运行的程序名,否则就是 `本地`、`本地 (2)` 等默认名称。命令运行时标签上会显示转圈图标,会话结束后显示 **已退出** 或 **失败**。
|
||||
|
||||
@@ -51,6 +51,7 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配
|
||||
- 双击、按 `Enter` 或 `F4` 跳到测试源码(**跳转到源代码**)。
|
||||
- **显示已通过** 和 **显示已忽略** 用于筛选测试树。默认隐藏已通过的测试,筛选状态会被记住。
|
||||
- **⋯ › 测试运行器选项 › 完成后选中第一个失败的测试** 会在运行结束时选中第一个失败的测试并显示它的输出。默认关闭。
|
||||
- **⋯ › 测试运行器选项 › 跟踪正在运行的测试** 会在运行过程中,每个测试开始时选中它并显示它的输出。默认开启。
|
||||
- 右键单个测试或多选后,可以 **运行 '…'**、**调试 '…'** 或 **跳转到源代码**。
|
||||
- 对于带有期望值和实际值的断言失败,**显示差异** 会把两者并排对比。
|
||||
- 对于 Jest 或 Vitest 的快照不匹配,**更新快照**(在测试或其文件、套件上,失败输出上方,以及边栏运行菜单中)只用 `-u` 重新运行这些测试,只改写它们的快照。
|
||||
|
||||
@@ -64,7 +64,7 @@ OpenIDEA 会把主题(以及其中附带的编辑器配色方案)转换为
|
||||
- **启用连字**:用于带编程连字的字体。
|
||||
- **排版设置**:**主字重**、**粗体字重**,以及主字体缺少字符时使用的 **备用字体**。
|
||||
|
||||
在当前编辑器中临时调整字号可以用 **增大字体**(`⌥⇧.` / `Alt+Shift+.`)和 **减小字体**(`⌥⇧,` / `Alt+Shift+,`),用 **视图 › 重置字体大小**(或 **视图 › 重置所有编辑器中的字体大小**)恢复。在 **设置 › 编辑器 › 常规** 中开启 **使用 Ctrl/Command+鼠标滚轮更改字体大小** 后可以用滚轮缩放,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
临时调整字号可以用 **增大所有编辑器中的字体**(`⌃⇧.` / `Alt+Shift+.`)和 **减小所有编辑器中的字体**(`⌃⇧,` / `Alt+Shift+,`),只调当前编辑器可在查找操作中运行 **增大字体** / **减小字体**;用 **视图 › 重置字体大小**(或 **视图 › 重置所有编辑器中的字体大小**)恢复。在 **设置 › 编辑器 › 常规** 中开启 **使用 Ctrl/Command+鼠标滚轮更改字体大小** 后可以用滚轮缩放,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
|
||||
|
||||
### 界面字体与缩放
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓
|
||||
其他比较方式:
|
||||
|
||||
- 对当前文件或文件夹使用 **与分支或修订比较…** 和 **与修订版比较…**(文件夹会显示变更文件列表)。
|
||||
- **比较对象…**(在项目视图中按 `⌘D` / `Ctrl+D`)、**比较文件**、**比较目录**(可向左/向右复制)和 **视图 › 与剪贴板比较**。
|
||||
- **比较对象…**(在项目视图中按 `⌘D` / `Ctrl+D`)、**比较文件**、**将文件与编辑器比较**(所选文件与活动编辑器中的文件比较,定位到其光标所在行)、**比较目录**(可向左/向右复制)和 **视图 › 与剪贴板比较**。
|
||||
|
||||
## 分支
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
|
||||
| 方式 | 适用于 |
|
||||
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| npm | 基于 Node 的服务器,如 vtsls、Pyright、Intelephense,以及 Vue、Svelte、Astro、Angular、CSS、HTML、JSON、YAML、Bash、Dockerfile 的服务器。需要 Node.js。 |
|
||||
| npm | 基于 Node 的服务器,如 vtsls、Pyright、Intelephense,以及 Vue、Svelte、Astro、MDX、Angular、CSS、Sass、HTML、JSON、YAML、Bash、Dockerfile 的服务器。需要 Node.js。 |
|
||||
| pip 安装到私有虚拟环境 | basedpyright、ty、pyrefly、Ruff(有 `uv` 时用 `uv`)。 |
|
||||
| pip 安装到私有目录 | debugpy。 |
|
||||
| `go install` | gopls、Delve、sqls。需要 Go。 |
|
||||
@@ -138,6 +138,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| Lua | `lua` | `.lua`, `.luau`, `.rockspec` | 是 | 是 | **lua-language-server** | — |
|
||||
| Makefile | `makefile` | `.mk`, `.mak`, `.make` | 是 | 是 | — | — |
|
||||
| Markdown | `markdown` | `.md`, `.markdown`, `.mdown`, `.mkd`, `.mkdn`, … | 是 | 是 | **marksman** | — |
|
||||
| MDX | `mdx` | `.mdx` | 是 | 是 | **mdx-language-server** | — |
|
||||
| Nix | `nix` | `.nix` | 是 | 是 | nil → nixd | — |
|
||||
| Objective-C | `objective-c` | `.m` | 是 | — | **clangd** | lldb-dap |
|
||||
| Objective-C++ | `objective-cpp` | `.mm` | 是 | — | **clangd** | lldb-dap |
|
||||
@@ -155,7 +156,7 @@ IDE 安装工具从不需要 `sudo`。工具装在本地数据目录下 IDE 自
|
||||
| reStructuredText | `restructuredtext` | `.rst` | 是 | — | — | — |
|
||||
| Ruby | `ruby` | `.rb`, `.rake`, `.gemspec`, `.ru`, `.rbi`, … | 是 | 是 | **ruby-lsp** → **solargraph** | rdbg |
|
||||
| Rust | `rust` | `.rs` | 是 | 是 | **rust-analyzer** | **codelldb** |
|
||||
| Sass | `sass` | `.sass` | 是 | — | — | — |
|
||||
| Sass | `sass` | `.sass` | 是 | — | **some-sass-language-server** | — |
|
||||
| Scala | `scala` | `.scala`, `.sc`, `.sbt`, `.mill` | 是 | 是 | metals | — |
|
||||
| SCSS | `scss` | `.scss` | 是 | — | **vscode-css-language-server** + **stylelint** | — |
|
||||
| Shell Script | `shellscript` | `.sh`, `.bash`, `.zsh`, `.ksh`, `.ash`, … | 是 | 是 | **bash-language-server** | **bash-debug** |
|
||||
|
||||
@@ -90,6 +90,8 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
|
||||
|
||||
**设置 › 编辑器 › 代码样式 › JavaScript** 和 **TypeScript** 有 **空格**(逗号后、运算符两侧、花括号内等)和 **标点**(分号:保持原样、使用或不使用;引号:与文件一致、单引号或双引号)两个标签页。它们和其他代码样式设置一起按项目保存,并发送给 TypeScript 服务器:服务器将其用于 **重新格式化代码**,以及它添加的代码,包括快速修复、自动导入、重构和 **优化导入**。JSX 文件跟随 JavaScript,TSX 文件跟随 TypeScript。启用 EditorConfig 支持时,项目 `.editorconfig` 中设置的 `quote_type` 或 IntelliJ 属性 `ij_typescript_use_semicolon_after_statement`、`ij_typescript_use_double_quotes`、`ij_typescript_space_after_comma`、`ij_typescript_spaces_within_object_literal_braces` 等(JavaScript 用 `ij_javascript_*`)优先。tsserver 没有尾随逗号选项,尾随逗号保持原样。
|
||||
|
||||
**导入** 标签页决定 TypeScript 服务器添加导入(自动导入、快速修复、移动文件)时的写法:**导入路径**(最短、相对路径、通过 `paths` / `baseUrl` 的非相对路径,或项目内使用相对路径)、**导入路径结尾**(自动、`./components`、`./components/index` 或 `./components/index.js`)、**不从以下位置自动导入**(glob,例如用 `**/index.ts` 排除 barrel 文件)和 **不自动导入匹配以下表达式的路径**(匹配导入路径的正则表达式,例如 `^node:`)。和其他标签页一样,它们按项目保存,JavaScript 和 TypeScript 分开设置,修改后无需重启服务器即可生效。
|
||||
|
||||
### Biome 检查
|
||||
|
||||
在 Biome 项目中,Biome 的诊断显示在编辑器和“问题”工具窗口里,`⌥⏎` / `Alt+Enter` 提供它的快速修复和抑制。Biome 的安全修复(`source.fixAll.biome`)随 **代码 › 代码清理** 运行;开启 **设置 › 工具 › 保存时操作 › 运行代码清理** 后,保存时也会运行。Biome 的格式化器开启时,它的全部修复也会格式化文件。
|
||||
|
||||
@@ -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]`
|
||||
|
||||
| 键 | 默认值 | 说明 |
|
||||
|
||||
@@ -188,19 +188,19 @@ macOS 符号:`⌘` Command、`⌥` Option、`⌃` Control、`⇧` Shift、`↵
|
||||
|
||||
## 文件、标签页与视图
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| ---------------- | ------------ | ----------------------- |
|
||||
| 设置… | `⌘,` | `Ctrl+Alt+S` |
|
||||
| 项目结构… | `⌘;` | `Ctrl+Alt+Shift+S` |
|
||||
| 全部保存 | `⌘S` | `Ctrl+S` |
|
||||
| 新建临时文件… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` |
|
||||
| 关闭标签页 | `⌘W` | `Ctrl+F4` |
|
||||
| 选择下一个标签页 | `⌃→` / `⇧⌘]` | `Alt+Right` |
|
||||
| 选择上一个标签页 | `⌃←` / `⇧⌘[` | `Alt+Left` |
|
||||
| 快速切换方案… | `` ⌃` `` | `` Ctrl+` `` |
|
||||
| 放大 IDE | `⌃⌥=` | `Alt+Shift+=` |
|
||||
| 缩小 IDE | `⌃⌥-` | `Alt+Shift+-` |
|
||||
| 重置 IDE 缩放 | `⌃⌥0` | `Alt+Shift+0` |
|
||||
| 增大字体 | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| 减小字体 | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| 切换全屏 | `⌃⌘F` | — |
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| ---------------------- | ------------ | ----------------------- |
|
||||
| 设置… | `⌘,` | `Ctrl+Alt+S` |
|
||||
| 项目结构… | `⌘;` | `Ctrl+Alt+Shift+S` |
|
||||
| 全部保存 | `⌘S` | `Ctrl+S` |
|
||||
| 新建临时文件… | `⇧⌘N` | `Ctrl+Alt+Shift+Insert` |
|
||||
| 关闭标签页 | `⌘W` | `Ctrl+F4` |
|
||||
| 选择下一个标签页 | `⌃→` / `⇧⌘]` | `Alt+Right` |
|
||||
| 选择上一个标签页 | `⌃←` / `⇧⌘[` | `Alt+Left` |
|
||||
| 快速切换方案… | `` ⌃` `` | `` Ctrl+` `` |
|
||||
| 放大 IDE | `⌃⌥=` | `Alt+Shift+=` |
|
||||
| 缩小 IDE | `⌃⌥-` | `Alt+Shift+-` |
|
||||
| 重置 IDE 缩放 | `⌃⌥0` | `Alt+Shift+0` |
|
||||
| 增大所有编辑器中的字体 | `⌃⇧.` | `Alt+Shift+.` |
|
||||
| 减小所有编辑器中的字体 | `⌃⇧,` | `Alt+Shift+,` |
|
||||
| 切换全屏 | `⌃⌘F` | — |
|
||||
@@ -0,0 +1,173 @@
|
||||
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_preview_copilot_models: ({ account }: { account: string }) => ({
|
||||
provider: "copilot",
|
||||
config: [account === "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 immediately previews its models before 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.getByRole("button", { name: "Model" })).toContainText("Agent's default (Gemini 4 Neon)");
|
||||
expect(await ipcCalls(page, "agent_set_env")).toEqual([]);
|
||||
|
||||
// Applying saves the staged account selection.
|
||||
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",
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { AgentEntry, AgentTask } from "../src/bindings";
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
const policyMessage = "This content was flagged for possible cybersecurity risk.";
|
||||
const policyDetails = "Contact support if this is unexpected.";
|
||||
const diagnostics = `${policyMessage}\n${policyDetails}\nCodex error: cyberPolicy`;
|
||||
const now = Date.now();
|
||||
const task: AgentTask = {
|
||||
id: "sample-policy-failure",
|
||||
title: "Investigate sample editor crash",
|
||||
provider: "codex",
|
||||
model: null,
|
||||
status: "failed",
|
||||
isolation: "local",
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: diagnostics,
|
||||
createdMs: now - 2000,
|
||||
updatedMs: now,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
const entries: AgentEntry[] = [
|
||||
{
|
||||
type: "user",
|
||||
text: "Investigate and fix the sample editor shutdown crash.",
|
||||
attachments: [],
|
||||
sentMs: now - 2000,
|
||||
doneMs: now - 1000,
|
||||
},
|
||||
{ type: "agent", text: "I will check the shutdown sequence and run the regression tests." },
|
||||
{ type: "error", message: diagnostics },
|
||||
];
|
||||
|
||||
async function showFailure(page: Page) {
|
||||
await page.evaluate(
|
||||
async ({ task, entries }) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const store = await import(storePath);
|
||||
const { commands } = await import(ipcPath);
|
||||
commands.agentEntries = async () => ({ status: "ok", data: entries });
|
||||
commands.agentChanges = async () => ({ status: "ok", data: [] });
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map(),
|
||||
unread: new Set(),
|
||||
});
|
||||
await store.openTaskInEditorLocation(task.id);
|
||||
},
|
||||
{ task, entries },
|
||||
);
|
||||
}
|
||||
|
||||
for (const width of [1400, 700]) {
|
||||
test(`preserves saved Codex error details and code at width ${width}`, async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await showFailure(page);
|
||||
const error = page.getByRole("alert").filter({ hasText: policyMessage });
|
||||
await expect(error).toBeVisible();
|
||||
await expect(error).toContainText(policyDetails);
|
||||
await expect(error).toContainText("Codex error: cyberPolicy");
|
||||
await expect(error).toHaveCSS("white-space", "pre-wrap");
|
||||
await expect(page.getByText("The agent declined to continue.", { exact: true })).toHaveCount(0);
|
||||
await expect(error.getByRole("button", { name: "Sign In…" })).toHaveCount(0);
|
||||
expect(await error.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
|
||||
// A different editor must not replace the saved failure with a generic task status.
|
||||
await openFromTree(page, "README.md");
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await page.getByRole("tree", { name: "Agent tasks", exact: true }).getByText(task.title, { exact: true }).click();
|
||||
await expect(error).toContainText(diagnostics);
|
||||
});
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
@@ -30,15 +30,15 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat
|
||||
agent_registry_list: () => ({ agents: [], warning: null }),
|
||||
agent_providers: () => {
|
||||
const provider: AgentProvider = {
|
||||
id: "copilot",
|
||||
name: "GitHub Copilot",
|
||||
command: "copilot --headless --no-auto-update --stdio",
|
||||
program: "/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/copilot/1.0.116/copilot",
|
||||
args: ["--headless", "--no-auto-update", "--stdio"],
|
||||
defaultProgram: "copilot",
|
||||
defaultArgs: ["--headless", "--no-auto-update", "--stdio"],
|
||||
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/copilot/1.0.116/copilot' login` in a terminal.",
|
||||
"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",
|
||||
@@ -49,12 +49,12 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat
|
||||
config: signedIn ? [model] : [],
|
||||
thoughtLevels: {},
|
||||
commands: [],
|
||||
source: { kind: "registry", version: "1.0.116", update: null },
|
||||
source: { kind: "registry", version: "1.0.0", update: null },
|
||||
};
|
||||
return [provider];
|
||||
},
|
||||
agent_refresh_models: () => ({
|
||||
provider: "copilot",
|
||||
provider: "claude",
|
||||
config: signedIn ? [model] : [],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
@@ -64,11 +64,11 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat
|
||||
}),
|
||||
agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
|
||||
setTimeout(() => {
|
||||
window.__ipc.send(onEvent, { type: "output", data: "Opening GitHub in browser...\r\n" });
|
||||
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: "copilot" };
|
||||
return { id: 1, pid: 1001, title: "claude" };
|
||||
},
|
||||
term_resize: () => null,
|
||||
term_write: () => null,
|
||||
@@ -82,7 +82,7 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat
|
||||
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 GitHub Copilot" })).toHaveCount(0);
|
||||
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(["copilot"]);
|
||||
expect((await ipcCalls(page, "agent_login_spawn")).map((c) => c.id)).toEqual(["claude"]);
|
||||
});
|
||||
Loaded 100 of 404 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача