Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 012ba7ace8 Merge remote-tracking branch 'origin/main' into fix/plugin-secrets-credential-store 2026-11-27 04:12:04 +08:00
l0ng-ai 93c74a1f0f fix(plugins): keep plugin secrets in the OS credential store on Windows and Linux
Plugin secrets were written in plain text to plugin-secrets.json on every
platform but macOS. They now go to the same credential store as SSH and
database passwords, keyed by plugin and name; values already in the file
are read as a fallback and moved on the next write. Without a usable
credential store the file is still used, with a warning.
2026-11-27 03:19:25 +08:00
738 змінених файлів з 2937 додано та 36734 видалено

No files matched your search

+6 -7
Переглянути файл
@@ -3,8 +3,7 @@ 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_DEPLOY_KEY secret (the private half of a write deploy key on
# l0ng-ai/homebrew-tap).
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
on:
workflow_call:
inputs:
@@ -28,17 +27,17 @@ jobs:
env:
TAG: ${{ inputs.tag }}
TAP: l0ng-ai/homebrew-tap
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
GH_TOKEN: ${{ github.token }}
steps:
- name: Check tag and deploy key
- name: Check tag and token
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_DEPLOY_KEY" ]; then
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
@@ -48,7 +47,7 @@ jobs:
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
path: tap
- uses: actions/setup-node@v5
if: steps.check.outputs.skip != 'true'
+1 -2
Переглянути файл
@@ -39,7 +39,6 @@ on:
- "src/editor/lsp/hint.ts"
- "src/editor/lsp/lsp.ts"
- "src/editor/lsp/positions.ts"
- "src/editor/lsp/snippet.ts"
- "src/bindings.ts"
- "src/styles/tokens.css"
- "src/test/setup.ts"
@@ -107,7 +106,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+1 -1
Переглянути файл
@@ -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_DEPLOY_KEY.
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
homebrew:
needs: publish
uses: ./.github/workflows/homebrew.yml
Створено
+49 -49
Переглянути файл
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4182,7 +4182,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"serde",
@@ -4205,7 +4205,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"blake3",
"chardetng",
@@ -4223,7 +4223,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4248,7 +4248,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4259,7 +4259,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4281,7 +4281,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-run",
@@ -4294,7 +4294,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4323,7 +4323,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4362,7 +4362,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"serde",
@@ -4375,7 +4375,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4389,7 +4389,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4409,7 +4409,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-android",
"ide-core",
@@ -4420,7 +4420,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4432,7 +4432,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4440,11 +4440,12 @@ dependencies = [
"serde_json",
"specta",
"tracing",
"which",
]
[[package]]
name = "ide-heap"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"criterion",
"ide-core",
@@ -4463,7 +4464,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4544,7 +4545,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"hyper-util",
"ide-core",
@@ -4563,7 +4564,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"blake3",
"criterion",
@@ -4586,7 +4587,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4598,7 +4599,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4614,7 +4615,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"libc",
"tempfile",
@@ -4623,7 +4624,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"futures",
"serde",
@@ -4634,7 +4635,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"blake3",
"criterion",
@@ -4693,7 +4694,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"criterion",
"dunce",
@@ -4704,7 +4705,6 @@ dependencies = [
"ide-jsonrpc",
"ide-jvm-inspect",
"ide-language",
"ide-sdk",
"ide-text",
"ide-vfs",
"ignore",
@@ -4723,7 +4723,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"bytes",
"dunce",
@@ -4742,7 +4742,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4763,7 +4763,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"blake3",
"dunce",
@@ -4785,7 +4785,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4799,7 +4799,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"dunce",
"futures",
@@ -4819,7 +4819,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"dunce",
"encoding_rs",
@@ -4844,7 +4844,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-tools",
@@ -4860,7 +4860,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4886,7 +4886,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"criterion",
"encoding_rs",
@@ -4907,7 +4907,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"parking_lot 0.12.5",
@@ -4920,7 +4920,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4945,7 +4945,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-language",
@@ -4958,7 +4958,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"ide-language",
@@ -4973,7 +4973,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"ide-core",
"libc",
@@ -4987,7 +4987,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"criterion",
"ide-core",
@@ -5000,7 +5000,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"flate2",
"hex",
@@ -5023,7 +5023,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"blake3",
"dunce",
@@ -5045,7 +5045,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"chardetng",
"dunce",
@@ -5072,7 +5072,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5088,7 +5088,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"blake3",
"dunce",
@@ -6727,7 +6727,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.54"
version = "0.1.53"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.54"
version = "0.1.53"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+1 -1
Переглянути файл
@@ -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, &shared.paths.project_root)
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
&& super::auth_required(0, &err) =>
{
let retry = run_once(shared, spec, true, model).await;
-48
Переглянути файл
@@ -283,20 +283,6 @@ impl AgentCatalogs {
}
}
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
let key = Self::key(shared, provider);
let mut state = self.state.lock();
if let Some(entry) = state.entries.get_mut(&key)
&& entry.flight.is_none()
&& entry.error.is_some()
{
entry.completed = None;
entry.retry_at_ms = None;
entry.error = None;
}
}
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
let catalog = entry.catalog.clone().unwrap_or_default();
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
@@ -627,40 +613,6 @@ 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(
+2 -99
Переглянути файл
@@ -33,7 +33,6 @@ pub use catalogs::AgentCatalogs;
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
pub use external::ExternalSession;
pub use model::*;
pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch};
pub use skill_installer::{
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
SkillScanWarning, SkillScanWarningKind,
@@ -54,49 +53,6 @@ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;
/// Resolves agent `id`'s interactive sign-in command without an open project.
pub fn login_launch_without_project(
custom_agents_dir: Option<&Path>,
secrets: Option<&dyn EnvSecrets>,
cwd: &Path,
id: &str,
) -> IdeResult<LoginLaunch> {
let spec = provider::load(custom_agents_dir, secrets)
.into_iter()
.find(|p| p.id == id)
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
spec.login_launch(cwd, None)
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
}
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
pub async fn copilot_auth_status_with(
custom_agents_dir: Option<&Path>,
secrets: Option<&dyn EnvSecrets>,
cwd: &Path,
) -> CopilotAuthStatus {
let copilot_spec = provider::load(custom_agents_dir, secrets).into_iter().find(|p| p.id == "copilot");
let cwd_buf = cwd.to_path_buf();
let cli_fut = async move {
let spec = copilot_spec?;
native::copilot::probe_auth_status(spec, cwd_buf).await
};
let gh_fut = tokio::task::spawn_blocking(provider::gh_authenticated_accounts);
let (cli, gh) = tokio::join!(cli_fut, gh_fut);
let (gh_installed, gh_accounts) = gh.unwrap_or((false, Vec::new()));
match cli {
Some(cli) => CopilotAuthStatus {
authenticated: cli.authenticated,
login: cli.login,
auth_type: cli.auth_type,
status_message: cli.status_message,
gh_installed,
gh_accounts,
},
None => CopilotAuthStatus { gh_installed, gh_accounts, ..CopilotAuthStatus::default() },
}
}
/// Receives the events of one project's tasks.
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
@@ -245,8 +201,6 @@ struct Shared {
providers: RwLock<Vec<provider::ProviderSpec>>,
/// Last probe of each provider.
probes: Mutex<HashMap<String, AgentProbe>>,
/// `type: "terminal"` login arguments reported during `initialize`, by provider id.
terminal_auth_args: RwLock<HashMap<String, Vec<String>>>,
/// Copilot CLI installs where `--headless` failed and fell back to `--acp`.
copilot_acp_fallback: Mutex<HashSet<CopilotBinaryKey>>,
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
@@ -752,7 +706,6 @@ impl AgentManager {
known,
providers,
probes: Mutex::new(HashMap::new()),
terminal_auth_args: RwLock::new(HashMap::new()),
copilot_acp_fallback: Mutex::new(HashSet::new()),
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
@@ -832,24 +785,16 @@ impl AgentManager {
*self.shared.git_executable.write() = Some(hook);
}
/// Directory holding linked Git worktrees created for agent tasks of this project.
pub fn worktrees_dir(&self) -> &Path {
&self.shared.paths.worktrees_dir
}
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
pub fn providers(&self) -> Vec<AgentProvider> {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
let in_use: std::collections::HashSet<String> =
self.tasks.read().values().map(|t| t.state.lock().task.provider.clone()).collect();
let terminal_auth = self.shared.terminal_auth_args.read();
let list = specs
.iter()
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
.map(|p| {
let mut info = provider::describe(p);
info.can_sign_in =
p.can_sign_in(&self.shared.paths.project_root, terminal_auth.get(&p.id).map(Vec::as_slice));
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
@@ -857,7 +802,6 @@ impl AgentManager {
info
})
.collect();
drop(terminal_auth);
let mut prev = self.shared.providers.write();
let mut probes = self.shared.probes.lock();
probes.retain(|id, _| {
@@ -871,35 +815,6 @@ impl AgentManager {
list
}
/// Resolves the interactive sign-in command for agent `id`.
pub fn login_launch(&self, id: &str) -> IdeResult<LoginLaunch> {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
let spec = specs
.into_iter()
.find(|p| p.id == id)
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
let terminal_args = self.shared.terminal_auth_args.read().get(id).cloned();
let launch = spec.login_launch(&self.shared.paths.project_root, terminal_args.as_deref()).ok_or_else(|| {
IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))
})?;
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, id);
Ok(launch)
}
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
pub async fn copilot_auth_status(&self) -> CopilotAuthStatus {
let status = copilot_auth_status_with(
self.shared.paths.custom_agents_dir.as_deref(),
self.shared.env_secrets(),
&self.shared.paths.project_root,
)
.await;
if status.authenticated || !status.gh_accounts.is_empty() {
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, "copilot");
}
status
}
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
@@ -922,9 +837,7 @@ 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)?;
self.shared.paths.catalogs.evict_if_idle(&self.shared, id);
Ok(())
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)
}
/// Saves a new custom ACP agent through its agent file.
@@ -3596,14 +3509,6 @@ impl Task {
let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message));
SessionOpenError { message: self.describe(e), allow_acp_fallback: !is_auth }
})?;
if let Some(args) = init.auth_methods.iter().find_map(|method| {
if method.get("type").and_then(Value::as_str) != Some("terminal") {
return None;
}
method.get("args")?.as_array()?.iter().map(|v| v.as_str().map(str::to_owned)).collect::<Option<Vec<_>>>()
}) {
self.shared.terminal_auth_args.write().insert(provider_id.to_owned(), args);
}
let sign_in_message = spec.sign_in_message(&init.auth_methods);
let can_load = init.load_session();
let (capabilities, embedded) = capabilities_of(&init);
@@ -5105,8 +5010,7 @@ fn tool_event(
i: usize,
entry: &AgentEntry,
) -> Option<AgentEvent> {
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms, command } =
entry
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms } = entry
else {
return None;
};
@@ -5121,7 +5025,6 @@ fn tool_event(
diffs: diffs.clone(),
started_ms: *started_ms,
ended_ms: *ended_ms,
command: command.clone(),
};
let text = output.as_deref().unwrap_or_default();
let key = (subagent, i);
-34
Переглянути файл
@@ -547,9 +547,6 @@ pub enum AgentEntry {
started_ms: Option<f64>,
#[serde(default)]
ended_ms: Option<f64>,
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
#[serde(default)]
command: Option<String>,
},
Plan {
items: Vec<AgentPlanItem>,
@@ -626,9 +623,6 @@ pub struct AgentProvider {
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
#[serde(default)]
pub can_sign_in: bool,
/// The built-in command can be owned by a global npm package.
#[serde(default)]
pub can_check_cli_update: bool,
@@ -653,34 +647,6 @@ pub enum AgentCommandReadOnlyReason {
CustomAgent,
}
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GhAuthAccount {
pub login: String,
pub active: bool,
}
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CopilotAuthStatus {
pub authenticated: bool,
pub login: Option<String>,
pub auth_type: Option<String>,
pub status_message: Option<String>,
pub gh_installed: bool,
pub gh_accounts: Vec<GhAuthAccount>,
}
/// Output and completion of an interactive sign-in PTY started by the IDE.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum AgentLoginEvent {
Output { data: String },
Exited { code: Option<i32> },
}
/// Where an agent comes from.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
+2 -1
Переглянути файл
@@ -1481,13 +1481,14 @@ 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::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
};
}
_ => "end_turn",
-84
Переглянути файл
@@ -455,90 +455,6 @@ 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",
+6 -20
Переглянути файл
@@ -740,7 +740,7 @@ pub(super) enum Failure {
UsageLimit(Option<f64>),
/// Signed out or refused.
Auth,
/// The server blocked the turn under a safety policy.
/// The model declined.
Refusal,
Other,
}
@@ -780,27 +780,13 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
exhausted.map(|s| s * 1000.0)
}
/// The text a failed turn reports: Codex's message, details and diagnostic code.
/// The text a failed turn reports: codex's message, with its details.
pub(super) fn error_message(error: &Value) -> String {
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 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 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.
+1 -73
Переглянути файл
@@ -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, &cwd);
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
Err(err)
if !prefer_stored
@@ -185,78 +185,6 @@ 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>,
+22 -338
Переглянути файл
@@ -2,10 +2,7 @@
//! `<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,
GhAuthAccount,
};
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -76,7 +73,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
"GitHub Copilot",
Driver::Copilot,
&["copilot", "--headless", "--no-auto-update", "--stdio"],
"Run `copilot login` in a terminal.",
"Run `copilot` in a terminal and sign in.",
),
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
@@ -154,26 +151,12 @@ impl ProviderSpec {
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
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 account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
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)
}
@@ -183,7 +166,7 @@ impl ProviderSpec {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
@@ -193,80 +176,6 @@ impl ProviderSpec {
.into_owned();
self
}
/// Resolves the executable, arguments, and environment to run this agent's interactive
/// sign-in flow directly in an IDE PTY without shell quoting.
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
let search = ide_core::tool_path::search_path();
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
let candidate =
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
if candidate.is_absolute() && is_executable(&candidate) {
return Some(candidate);
}
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
};
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
"claude-acp" => Some(("claude", &[][..])),
"codex-acp" => Some(("codex", &["login"][..])),
"vibe" => Some(("vibe", &[][..])),
_ => None,
} {
let program = resolve_exe(separate_cmd, &self.env)?;
return Some(LoginLaunch {
program,
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
env: self.env.iter().cloned().collect(),
});
}
if let Some(builtin) = builtin_spec(&self.id) {
let args = terminal_auth_args
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
.map(<[String]>::to_vec)
.or_else(|| builtin_login_args(&builtin))?;
let resolved = self.clone().resolve_for_launch_base(cwd, true);
let program = resolve_exe(&resolved.command, &resolved.env)?;
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
if is_copilot_provider(&self.id) {
for key in AMBIENT_COPILOT_AUTH_VARS {
env.insert(key.to_owned(), String::new());
}
}
return Some(LoginLaunch { program, args, env });
}
let args = terminal_auth_args?.to_vec();
let resolved = self.clone().resolve_for_launch_base(cwd, true);
let program = resolve_exe(&resolved.command, &resolved.env)?;
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
}
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
self.login_launch(cwd, terminal_auth_args).is_some()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoginLaunch {
pub program: PathBuf,
pub args: Vec<String>,
pub env: BTreeMap<String, String>,
}
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
let prefix = format!("Run `{}", builtin.command);
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
match rest {
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
let (args, _) = after_space.split_once('`')?;
Some(args.split_whitespace().map(str::to_owned).collect())
}
Some(_) => Some(Vec::new()),
None => None,
}
}
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
@@ -285,26 +194,16 @@ 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> {
if !is_valid_github_login(account) {
return Err(format!("Invalid GitHub account login: {account}"));
}
let program = find_gh_executable()
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))
.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);
@@ -330,140 +229,6 @@ 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)
}
@@ -472,17 +237,18 @@ 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)], cwd: &Path) -> bool {
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
})
}
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())
})
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()))
}
/// Builds child environment overrides for `copilot`:
@@ -493,10 +259,9 @@ fn ambient_copilot_env_value(key: &str, cwd: &Path) -> 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, |key| ambient_copilot_env_value(key, cwd))
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
}
pub(crate) fn sanitize_copilot_env_with(
@@ -624,7 +389,6 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
can_sign_in: spec.can_sign_in(Path::new("."), None),
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
env: spec.env.iter().cloned().collect(),
config: vec![],
@@ -1137,22 +901,6 @@ mod tests {
assert_eq!(reset.env, custom.env);
}
#[test]
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
for spec in builtins() {
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
continue;
}
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
}
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
assert_eq!(args("copilot"), ["login"]);
assert_eq!(args("goose"), ["configure"]);
assert_eq!(args("hermes"), ["model"]);
assert!(args("qwen").is_empty());
}
#[test]
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
for spec in builtins() {
@@ -1412,12 +1160,12 @@ mod tests {
"copilot",
BTreeMap::from([
("REGISTRY_SETTING".into(), "kept".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".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("alice-work"));
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
.unwrap_err();
@@ -1426,7 +1174,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(), "alice-work".into()));
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
let resolved = spec.resolve_for_launch(Path::new("."));
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
@@ -1710,68 +1458,4 @@ mod tests {
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
);
}
#[test]
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
let raw = r#"{
"hosts": {
"github.com": [
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
],
"ghe.example.com": [
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
]
}
}"#;
assert_eq!(
parse_gh_auth_status_json(raw),
Some(vec![
GhAuthAccount { login: "alice".into(), active: true },
GhAuthAccount { login: "alice-work".into(), active: false },
])
);
let text = "\
github.com
✓ Logged in to github.com account env_user (GH_TOKEN)
- Active account: true
✓ Logged in to github.com account alice (keyring)
- Active account: false
✓ Logged in to github.com account alice-work (keyring)
- Active account: true
";
assert_eq!(
parse_gh_auth_status_text(text),
vec![
GhAuthAccount { login: "alice".into(), active: false },
GhAuthAccount { login: "alice-work".into(), active: true },
]
);
}
#[test]
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
let dir = tempfile::tempdir().unwrap();
let app_support = dir.path().join("Application Support/copilot");
std::fs::create_dir_all(&app_support).unwrap();
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let mut spec = builtin_spec("copilot").unwrap();
spec.command = bin.to_string_lossy().into_owned();
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
let launch = spec.login_launch(dir.path(), None).unwrap();
assert_eq!(launch.program, bin);
assert_eq!(launch.args, ["login"]);
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
}
}
+4 -120
Переглянути файл
@@ -189,11 +189,6 @@ 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");
@@ -201,12 +196,9 @@ fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str,
Some(p) => (p.args.clone(), p.env.clone()),
None => (vec!["--acp".into()], BTreeMap::new()),
};
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 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 targets = [
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
@@ -227,22 +219,6 @@ fn add_copilot_release_binaries_with_root(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('.')
@@ -1236,7 +1212,7 @@ esac
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
assert_eq!(spec.name, "GitHub Copilot");
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
let mut providers = vec![provider::describe(&spec)];
@@ -1328,96 +1304,4 @@ 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
);
}
}
}
+1 -1
Переглянути файл
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
}
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
fn command_from_value(val: &Value) -> Option<String> {
match val {
Value::String(s) => {
let trimmed = s.trim();
-1
Переглянути файл
@@ -4369,7 +4369,6 @@ fn a_running_tools_output_is_sent_as_appends() {
diffs: Vec::new(),
started_ms: Some(1.0),
ended_ms: None,
command: None,
};
let running = |output| call(AgentToolStatus::Running, output);
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
+1 -35
Переглянути файл
@@ -91,7 +91,6 @@ impl Timeline {
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
command: None,
};
let index = match self.tools.get(&id) {
Some(&i) => {
@@ -155,7 +154,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
&mut self.entries[index]
else {
return;
@@ -172,11 +171,6 @@ impl Timeline {
*ended_ms = Some(crate::now_ms());
}
}
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
&& let Some(cmd) = crate::security::command_from_value(raw)
{
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
}
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
@@ -477,34 +471,6 @@ mod tests {
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn an_execute_call_keeps_the_command_from_its_structured_input() {
let mut t = Timeline::default();
let command = |t: &Timeline, i: usize| match &t.entries[i] {
AgentEntry::Tool { command, .. } => command.clone(),
_ => panic!(),
};
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
"rawInput": {"command": "python hello_world.py"}}));
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
// An argv array whose shell wraps the script, sent with a later update.
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
assert_eq!(command(&t, 1), None);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
// One shell line, unwrapped as the permission card does.
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
// A later update without one keeps it; tasks saved before the field load without it.
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
old.as_object_mut().unwrap().remove("command");
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
}
#[test]
fn tool_images_survive_updates_text_truncation_and_serialization() {
use base64::Engine;
+3 -4
Переглянути файл
@@ -323,8 +323,7 @@ mod tests {
"exclude": [path(&root.join("node_modules"))],
})
);
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
let a = root.join("packages").join("a");
let a = root.join("packages/a");
assert_eq!(
copy(1),
json!({
@@ -337,14 +336,14 @@ mod tests {
"exclude": [path(&a.join("node_modules"))],
})
);
let b = root.join("packages").join("b");
let b = root.join("packages/b");
assert_eq!(
copy(2),
json!({
"extends": path(&b.join("tsconfig.json")),
"compilerOptions": {
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
},
"references": [{"path": s("1.json")}],
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
+4 -7
Переглянути файл
@@ -91,14 +91,12 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
/// redirector loaded before Maven calculates its lifecycle execution plans.
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
pub fn build(
root: &Path,
model: &BuildModel,
bundle: &Path,
generation: &Path,
cancel: &CancellationToken,
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
) -> IdeResult<Outcome> {
std::fs::create_dir_all(generation)?;
let mut plan = plan(root, model, cancel)?;
@@ -126,10 +124,10 @@ pub fn build(
for step in &plan.steps {
let mut reactor = plan.clone();
reactor.steps = vec![step.clone()];
let result = compile::run(root, &reactor, cancel, &|event| match event {
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
_ => {}
let result = compile::run(root, &reactor, cancel, &|event| {
if let BuildEvent::Output { text, .. } = event {
tracing::debug!("kotlin bridge: {}", text.trim_end());
}
})?;
messages.extend(result.messages);
}
@@ -458,7 +456,6 @@ mod tests {
Path::new("unused.jar"),
&directory.path().join("private"),
&CancellationToken::new(),
&|_, _| {},
)
.err()
.unwrap();
-62
Переглянути файл
@@ -486,16 +486,6 @@ pub struct LanguageCodeStyle {
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
/// Java: organize imports switches to a wildcard import once this many
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
/// 5; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub class_count_to_use_import_with_star: Option<u32>,
/// Java: organize imports switches to a wildcard static import once this
/// many statically imported names are used (jdtls `staticStarThreshold`;
/// IDEA's default 3; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub names_count_to_use_static_import_with_star: Option<u32>,
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
#[serde(skip_serializing_if = "Option::is_none")]
pub semicolons: Option<String>,
@@ -505,19 +495,6 @@ 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).
@@ -575,25 +552,6 @@ 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 {
@@ -604,30 +562,10 @@ 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};
+4 -25
Переглянути файл
@@ -13,34 +13,13 @@ use std::sync::Arc;
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
/// Run would, answered the same way.
/// started or failed to.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum McpUiRequest {
Confirm {
client: String,
tool: String,
subject: String,
project: String,
detail: Option<String>,
},
OpenFile {
path: crate::IpcPath,
line: Option<u32>,
column: Option<u32>,
},
AgentRun {
name: String,
command: String,
cwd: crate::IpcPath,
env: BTreeMap<String, String>,
},
RunConfiguration {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
+11 -124
Переглянути файл
@@ -14,33 +14,10 @@ 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();
@@ -54,103 +31,35 @@ 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 => {
let mut entry = Entry::new(root.to_path_buf());
entry.loading = true;
entries.push(entry);
}
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
}
}
/// 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`].
/// What children started in `root` (or below it) get 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();
match entries.iter_mut().position(|e| e.root == root) {
Some(idx) => {
let entry = &mut entries[idx];
entry.direnv = changes;
let changes = Arc::new(changes);
match entries.iter_mut().find(|e| e.root == root) {
Some(entry) => {
entry.changes = changes;
entry.loading = false;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
}
None if !changes.is_empty() => {
let mut entry = Entry::new(root.to_path_buf());
entry.direnv = changes;
entry.rebuild();
entries.push(entry);
}
None => {}
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
}
SETTLED.notify_all();
}
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
pub fn settle(root: &Path) {
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 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();
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
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) {
/// `root` has no environment of its own any more (closed, or not trusted).
pub fn remove(root: &Path) {
entries().retain(|e| e.root != root);
SETTLED.notify_all();
}
@@ -226,26 +135,4 @@ 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());
}
}
-26
Переглянути файл
@@ -99,20 +99,6 @@ pub struct AgentSettings {
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
pub fit_window_width: bool,
/// Chat text follows the interface font (Appearance › Use custom font).
pub chat_use_ui_font: bool,
/// Chat text family when it does not follow the interface font.
pub chat_font_family: String,
/// Covers characters the chat font lacks.
pub chat_font_fallback: String,
pub chat_font_size: u32,
/// Code in chat follows the built-in code font.
pub code_use_default_font: bool,
/// Code family when it does not follow the built-in code font.
pub code_font_family: String,
/// Covers characters the code font lacks.
pub code_font_fallback: String,
pub code_font_size: u32,
#[serde(deserialize_with = "or_default")]
#[specta(type = ThinkingDisplay)]
pub thinking: ThinkingDisplay,
@@ -159,14 +145,6 @@ impl Default for AgentSettings {
show_cost: false,
smooth_text: true,
fit_window_width: false,
chat_use_ui_font: true,
chat_font_family: "Inter".into(),
chat_font_fallback: String::new(),
chat_font_size: 13,
code_use_default_font: true,
code_font_family: "JetBrains Mono".into(),
code_font_fallback: String::new(),
code_font_size: 13,
thinking: ThinkingDisplay::Auto,
tool_calls: ToolCallDisplay::Grouped,
expand_tool_output: false,
@@ -1448,9 +1426,6 @@ 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 {
@@ -1463,7 +1438,6 @@ impl Default for PythonSettings {
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
test_runner: "auto".into(),
}
}
}
-32
Переглянути файл
@@ -73,38 +73,6 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
}
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
/// only when installed, then the user's `PATH`), and standard OS install locations.
pub fn find_gh_executable() -> Option<PathBuf> {
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
}
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
return Some(explicit);
}
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
}
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
return Some(explicit.to_path_buf());
}
if let Some(found) = find_command("gh", search, Path::new("")) {
return Some(found);
}
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
}
fn is_executable(path: &Path) -> bool {
let Ok(metadata) = path.metadata() else { return false };
#[cfg(unix)]
-12
Переглянути файл
@@ -25,17 +25,6 @@ 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
@@ -79,7 +68,6 @@ impl Default for VcsSettings {
shelf: ShelfSettings::default(),
issue_navigation: Vec::new(),
mappings: VcsMappings::default(),
github: GithubSettings::default(),
}
}
}
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-coverage"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo XML)"
version.workspace = true
edition.workspace = true
license.workspace = true
-174
Переглянути файл
@@ -1,174 +0,0 @@
//! Cobertura XML reports (`coverage xml` of coverage.py, and many other tools):
//!
//! ```xml
//! <coverage>
//! <sources><source>/home/runner/work/app/app</source></sources>
//! <packages><package name="calc"><classes>
//! <class filename="src/calc/__init__.py">
//! <methods/>
//! <lines>
//! <line number="2" hits="1" branch="true" condition-coverage="50% (1/2)"/>
//! ```
//!
//! A relative `filename` belongs to the first `<source>` it exists under, else to the
//! first `<source>` (whose path may be another machine's; the importer relocates it).
//! Lines repeated under `<methods>` are skipped so their hits don't count twice.
use crate::Accumulator;
use quick_xml::events::{BytesStart, Event};
use quick_xml::{Reader, XmlVersion};
use std::path::{Path, PathBuf};
fn attr(e: &BytesStart, name: &str) -> Option<String> {
e.attributes()
.flatten()
.find(|a| a.key.as_ref() == name)
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok())
.map(Into::into)
}
/// `"50% (1/2)"` → `(1, 2)`.
fn conditions(text: &str) -> Option<(u32, u32)> {
let (_, rest) = text.split_once('(')?;
let (covered, total) = rest.trim_end_matches(')').split_once('/')?;
Some((covered.trim().parse().ok()?, total.trim().parse().ok()?))
}
/// `sources` pairs each `<source>` with whether it exists here (asked once: another
/// machine's `/home/…` is slow to look up on macOS).
fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf {
let p = Path::new(filename);
if p.has_root() {
return p.to_path_buf();
}
sources
.iter()
.filter(|(_, here)| *here)
.map(|(s, _)| s.join(p))
.find(|c| c.is_file())
.unwrap_or_else(|| sources.first().map_or_else(|| base.join(p), |(s, _)| s.join(p)))
}
/// Relative sources (and filenames without sources) resolve against `base`.
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
let mut reader = Reader::from_str(xml);
let mut acc = Accumulator::default();
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
let mut source: Option<String> = None;
let mut file: Option<PathBuf> = None;
let mut in_methods = false;
loop {
match reader.read_event()? {
Event::Start(e) if e.name().as_ref() == "methods" => in_methods = true,
Event::Start(e) | Event::Empty(e) => match e.name().as_ref() {
"source" => source = Some(String::new()),
"class" => {
let path = resolve(&attr(&e, "filename").unwrap_or_default(), &sources, base);
acc.file(&path);
file = Some(path);
}
"line" if !in_methods => {
let Some(path) = &file else { continue };
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
let line = number.saturating_sub(1);
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
if attr(&e, "branch").as_deref() == Some("true")
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
{
acc.has_branches = true;
for i in 0..total {
acc.branch(path, line, i.to_string(), i < covered);
}
}
}
_ => {}
},
Event::Text(t) => {
if let Some(s) = &mut source {
s.push_str(t.as_ref());
}
}
Event::GeneralRef(r) => {
if let Some(s) = &mut source {
s.push('&');
s.push_str(r.as_ref());
s.push(';');
}
}
Event::End(e) => match e.name().as_ref() {
"source" => {
let raw = source.take().unwrap_or_default();
let text = quick_xml::escape::unescape(raw.trim()).map(|t| t.into_owned()).unwrap_or(raw);
if !text.is_empty() {
let path = Path::new(&text);
// Joining a drive-less foreign root on Windows would add the checkout's drive.
let dir = if path.has_root() { path.to_path_buf() } else { base.join(path) };
let here = dir.is_dir();
sources.push((dir, here));
}
}
"methods" => in_methods = false,
"class" => file = None,
_ => {}
},
Event::Eof => break,
_ => {}
}
}
Ok(acc)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_lines_branches_and_skips_method_lines() {
let tmp = tempfile::tempdir().unwrap();
let second = tmp.path().join("b&c");
std::fs::create_dir_all(&second).unwrap();
std::fs::write(second.join("m.py"), "").unwrap();
let xml = format!(
r#"<?xml version="1.0" ?>
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
<coverage><sources><source>/elsewhere/a</source><source>{}</source></sources>
<packages><package name="p"><classes>
<class name="m" filename="m.py">
<methods><method name="f"><lines><line number="2" hits="5"/></lines></method></methods>
<lines>
<line number="1" hits="1"/>
<line number="2" hits="5" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
<line number="3" hits="0"/>
</lines>
</class>
<class name="n" filename="n.py"><lines><line number="1" hits="0"/></lines></class>
<class name="abs" filename="/abs/x.py"><lines><line number="7" hits="2"/></lines></class>
</classes></package></packages></coverage>"#,
tmp.path().join("b&amp;c").display()
);
let suite = parse(&xml, tmp.path()).unwrap().finish("Cobertura");
assert!(suite.has_branches);
assert_eq!(suite.files.len(), 3);
let file = |path: &Path| suite.files.iter().find(|f| f.path.as_ref() as &Path == path).unwrap();
// `m.py` exists under the second source; `n.py` falls back to the first.
let m = file(&second.join("m.py"));
assert_eq!(file(Path::new("/elsewhere/a/n.py")).lines[0].hits, 0);
assert_eq!(
m.lines.iter().map(|l| (l.line, l.hits, l.branches_total, l.branches_covered)).collect::<Vec<_>>(),
[(0, 1, 0, 0), (1, 5, 2, 1), (2, 0, 0, 0)]
);
assert!(m.lines[1].partial());
assert_eq!(file(Path::new("/abs/x.py")).lines[0].line, 6);
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
}
#[test]
fn filenames_without_sources_resolve_against_the_base() {
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
let suite = parse(xml, Path::new("/root")).unwrap().finish("Cobertura");
assert_eq!(suite.files[0].path.as_ref() as &Path, Path::new("/root/a/b.py"));
assert!(!suite.has_branches);
assert_eq!(conditions("100% (4/4)"), Some((4, 4)));
assert_eq!(conditions("100%"), None);
}
}
-281
Переглянути файл
@@ -1,281 +0,0 @@
//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of
//! executed lines and arcs. Which lines are statements, excluded or branches only comes from
//! analysing the source, so coverage.py in the project's interpreter combines the data into a
//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML.
use crate::{CoverageSuite, cobertura};
use ide_core::cli_process::{CliTool, Decoding};
use ide_core::{IdeError, IdeResult};
use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
const COVERAGE_PY: CliTool = CliTool::new("coverage.py", Decoding::ToolOutput);
/// Analysing a large project's sources takes a while; a `[run] plugins` that hangs must not
/// block the import for good.
const TIMEOUT: Duration = Duration::from_secs(600);
/// Files of the combined data (`relative_files` keeps them relative to the directory it ran in).
const MEASURED: &str = "import sys, json, coverage\n\
d = coverage.CoverageData(sys.argv[1]); d.read(); print(json.dumps(sorted(d.measured_files())))";
/// The files coverage.py reads its configuration from, in the directory it runs in.
const CONFIG_FILES: [&str; 4] = [".coveragerc", "setup.cfg", "tox.ini", "pyproject.toml"];
/// Whether `path` is an SQLite database (coverage.py 5+ data).
pub fn is_data_file(path: &Path) -> bool {
let mut head = [0u8; 16];
std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"
}
/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's.
fn inputs(path: &Path) -> Vec<PathBuf> {
let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage."));
let mut files: Vec<PathBuf> = match (parallel, path.parent()) {
(true, Some(dir)) => std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| {
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p)
})
.collect(),
_ => Vec::new(),
};
if files.is_empty() {
files.push(path.to_path_buf());
}
files.sort();
files
}
/// Where coverage.py ran: the nearest directory of `path` inside `root` with a coverage.py
/// configuration file (a monorepo's `backend/pyproject.toml`), else `root`.
fn run_dir(path: &Path, root: &Path) -> PathBuf {
path.ancestors()
.skip(1)
.take_while(|d| d.starts_with(root))
.find(|d| CONFIG_FILES.iter().any(|f| d.join(f).is_file()))
.unwrap_or(root)
.to_path_buf()
}
/// Runs `python -W ignore <args>` in `dir` and returns its stdout. Python warnings are
/// ignored so `PYTHONWARNINGS=error` can't turn coverage.py's warnings into failures.
fn python(python: &Path, dir: &Path, args: &[&OsStr]) -> IdeResult<String> {
let mut cmd = Command::new(python);
cmd.current_dir(dir).args(["-W", "ignore"]).args(args);
let out = COVERAGE_PY.run(cmd, TIMEOUT, None)?;
if out.success {
return Ok(out.stdout);
}
let text = if out.stderr.trim().is_empty() { out.stdout } else { out.stderr };
let text = text.trim();
if text.contains("No module named coverage") {
return Err(IdeError::unavailable(format!(
"Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.",
python.display()
)));
}
if text.contains("no such option") {
return Err(IdeError::unavailable(format!(
"Reading a .coverage data file needs coverage.py 6.3 or later in the project's interpreter ({}): {text}",
python.display()
)));
}
Err(IdeError::invalid(format!("coverage.py could not read the data: {text}")))
}
/// Reads the data file at `path` with `python`'s coverage.py, run where the project's coverage.py
/// configuration is; `out` holds the scratch files. Blocking.
pub(crate) fn import(path: &Path, root: &Path, python_path: &Path, out: &Path) -> IdeResult<CoverageSuite> {
let dir = run_dir(path, root);
let data = out.join(".coverage");
let xml = out.join("coverage.xml");
let coverage = |args: &[&OsStr]| {
let mut all: Vec<&OsStr> = vec!["-m".as_ref(), "coverage".as_ref()];
all.extend(args);
python(python_path, &dir, &all)
};
let inputs = inputs(path);
let mut args: Vec<&OsStr> = vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()];
args.extend(inputs.iter().map(|p| p.as_os_str()));
coverage(&args)?;
// `-i`: report what has source here instead of failing on the first file that has none.
// `--fail-under=0`: a `[report] fail_under` the data misses must not fail the import.
coverage(&[
"xml".as_ref(),
"-i".as_ref(),
"--fail-under=0".as_ref(),
"--data-file".as_ref(),
data.as_ref(),
"-o".as_ref(),
xml.as_ref(),
])?;
let text = std::fs::read_to_string(&xml)?;
let mut acc = cobertura::parse(&text, &dir).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
// The files the report left out (no source here): listed without lines.
let measured = python(python_path, &dir, &["-c".as_ref(), MEASURED.as_ref(), data.as_ref()])?;
let measured: Vec<PathBuf> = serde_json::from_str(measured.trim())
.map_err(|e| IdeError::invalid(format!("coverage.py listed the measured files unreadably: {e}")))?;
for file in measured {
acc.file(&dir.join(file));
}
Ok(acc.finish("coverage.py"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_the_files_of_a_parallel_run() {
let tmp = tempfile::tempdir().unwrap();
let db = |name: &str| {
let p = tmp.path().join(name);
std::fs::write(&p, b"SQLite format 3\0rest").unwrap();
p
};
let a = db(".coverage.host.1.x");
let b = db(".coverage.host.2.y");
let single = db(".coverage");
std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap();
std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap();
assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc")));
assert_eq!(inputs(&a), [a.clone(), b]);
assert_eq!(inputs(&single), [single]);
}
/// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`.
/// Needs coverage.py in `python3`; skipped without it.
#[test]
fn combines_parallel_data_with_the_projects_paths() {
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
if !has_coverage.is_ok_and(|o| o.status.success()) {
eprintln!("skipped: no coverage.py in python3");
return;
}
let tmp = tempfile::tempdir().unwrap();
// coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`).
let base = tmp.path().canonicalize().unwrap();
let ci = base.join("ci/app");
let root = base.join("project");
let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n";
for dir in [&ci, &root] {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join("calc.py"), calc).unwrap();
}
std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap();
std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap();
std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap();
for script in ["neg.py", "pos.py"] {
let ok = Command::new("python3")
.current_dir(&ci)
.args(["-m", "coverage", "run", "--branch", "--parallel-mode", script])
.status()
.unwrap();
assert!(ok.success());
}
let data = root.join("data");
std::fs::create_dir_all(&data).unwrap();
for e in std::fs::read_dir(&ci).unwrap().flatten() {
if e.file_name().to_string_lossy().starts_with(".coverage.") {
std::fs::rename(e.path(), data.join(e.file_name())).unwrap();
}
}
std::fs::remove_dir_all(&ci).unwrap();
std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap();
let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path();
let out = base.join("out");
std::fs::create_dir_all(&out).unwrap();
let suite = import(&first, &root, Path::new("python3"), &out).unwrap();
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap();
// Both runs together take both branches of line 2.
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2));
// The scripts and `gone.py` have no source in the project: listed without lines.
let empty: Vec<&str> = suite
.files
.iter()
.filter(|f| f.lines.is_empty())
.filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str())
.collect();
assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]);
// They keep the recorded path, so the import notification counts them as not in the project.
assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci)));
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept");
}
#[test]
fn runs_where_the_coverage_configuration_is() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join("backend/reports")).unwrap();
std::fs::create_dir_all(root.join("data")).unwrap();
std::fs::write(root.join("backend/pyproject.toml"), "").unwrap();
assert_eq!(run_dir(&root.join("backend/reports/.coverage"), root), root.join("backend"));
assert_eq!(run_dir(&root.join("data/.coverage"), root), root);
// A data file outside the project runs in the project.
assert_eq!(run_dir(Path::new("/elsewhere/.coverage"), root), root);
}
/// A stand-in interpreter that prints `stderr` and exits with `code`.
#[cfg(unix)]
fn fake_python(dir: &Path, stderr: &str, code: i32) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let p = dir.join("python");
std::fs::write(&p, format!("#!/bin/sh\necho '{stderr}' >&2\nexit {code}\n")).unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
p
}
#[cfg(unix)]
#[test]
fn reports_why_coverage_py_failed() {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join(".coverage");
let err = |stderr: &str| {
let python = fake_python(tmp.path(), stderr, 1);
import(&data, tmp.path(), &python, tmp.path()).unwrap_err().to_string()
};
assert!(err("No module named coverage").contains("needs coverage.py in the project's interpreter"));
assert!(err("no such option: --data-file").contains("needs coverage.py 6.3 or later"));
assert!(err("No usable data files").contains("coverage.py could not read the data: No usable data files"));
}
/// A monorepo member's data recorded with `relative_files`, below its `fail_under`, with
/// coverage.py's warnings turned off. Needs coverage.py in `python3`; skipped without it.
#[test]
fn reads_a_members_relative_data_below_fail_under() {
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
if !has_coverage.is_ok_and(|o| o.status.success()) {
eprintln!("skipped: no coverage.py in python3");
return;
}
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
let member = root.join("backend");
std::fs::create_dir_all(member.join("app")).unwrap();
std::fs::write(
member.join("pyproject.toml"),
"[tool.coverage.run]\nrelative_files = true\nbranch = true\ndisable_warnings = [\"couldnt-parse\"]\n\
[tool.coverage.report]\nfail_under = 90\n",
)
.unwrap();
std::fs::write(member.join("app/x.py"), "def f(n):\n if n:\n return 1\n return 2\n").unwrap();
std::fs::write(member.join("t.py"), "from app import x\nx.f(1)\n").unwrap();
let ok = Command::new("python3").current_dir(&member).args(["-m", "coverage", "run", "t.py"]).status().unwrap();
assert!(ok.success());
std::fs::remove_file(member.join("t.py")).unwrap();
let out = root.join("out");
std::fs::create_dir_all(&out).unwrap();
let suite = import(&member.join(".coverage"), &root, Path::new("python3"), &out).unwrap();
let x = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("app/x.py")).unwrap();
assert_eq!((x.lines_total, x.lines_covered, x.branches_total, x.branches_covered), (4, 3, 2, 1));
// `t.py` has no source any more and its warning is off: still listed, without lines.
let t = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("t.py")).unwrap();
assert!(t.lines.is_empty());
}
}
+8 -127
Переглянути файл
@@ -1,10 +1,9 @@
//! "Import a report collected in CI from disk": the format is sniffed from the
//! content (lcov, Go cover profile, JaCoCo or Cobertura XML, SimpleCov resultset) and paths recorded on another
//! content (lcov, Go cover profile, JaCoCo XML, SimpleCov resultset) and paths recorded on another
//! machine are mapped into the project by their longest existing suffix.
use crate::{Accumulator, CoverageSuite, cobertura, goprofile, jacoco, lcov, simplecov};
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov, simplecov};
use ide_core::{IdeError, IdeResult};
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -12,19 +11,13 @@ pub(crate) enum Format {
Lcov,
GoProfile,
Jacoco,
Cobertura,
SimpleCov,
}
pub(crate) fn detect(text: &str) -> Option<Format> {
let head = text.trim_start_matches('\u{feff}').trim_start();
if head.starts_with('<') {
// The root element, after any prolog or DOCTYPE naming it.
return match (head.find("<report"), head.find("<coverage")) {
(Some(r), c) if c.is_none_or(|c| r < c) => Some(Format::Jacoco),
(_, Some(_)) => Some(Format::Cobertura),
_ => None,
};
return head.contains("<report").then_some(Format::Jacoco);
}
if head.starts_with('{') {
return head.contains("\"coverage\"").then_some(Format::SimpleCov);
@@ -46,9 +39,6 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
let (module, module_dir) = go_module_for(root, &text);
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
}
Some(Format::Cobertura) => cobertura::parse(&text, root)
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?
.finish("Cobertura"),
Some(Format::Jacoco) => {
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
let module = jacoco::module_dir(path);
@@ -63,24 +53,18 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
acc.finish("JaCoCo")
}
None if text.starts_with("!coverage.py: This is a private format") => {
return Err(IdeError::invalid(format!(
"{} is coverage.py 4 data, which current coverage.py can't read. Import the output of `coverage xml` instead.",
path.display()
)));
}
None => {
return Err(IdeError::invalid(format!(
"{} is not an lcov tracefile, Go cover profile, JaCoCo or Cobertura XML report or SimpleCov resultset",
"{} is not an lcov tracefile, Go cover profile, JaCoCo XML report or SimpleCov resultset",
path.display()
)));
}
};
let mut dirs = HashMap::new();
for f in &mut suite.files {
let p: &Path = f.path.as_ref();
let present = p.parent().is_none_or(|d| dir_exists(d, &mut dirs)) && p.exists();
if !present && let Some(found) = relocate(p, root) {
if !p.exists()
&& let Some(found) = relocate(p, root)
{
f.path = found.into();
}
}
@@ -88,24 +72,6 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
Ok(suite)
}
/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`,
/// run in `root`; `out` is an empty scratch directory. Blocking.
pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
crate::coveragepy::import(path, root, python, out)
}
/// Whether `dir` exists, without asking again below a directory known to be missing: every
/// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports
/// (`/home/runner/work/…`) name thousands of files there.
fn dir_exists(dir: &Path, known: &mut HashMap<PathBuf, bool>) -> bool {
if let Some(&e) = known.get(dir) {
return e;
}
let e = dir.parent().is_none_or(|p| dir_exists(p, known)) && dir.is_dir();
known.insert(dir.to_path_buf(), e);
e
}
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
/// `path` that exists under `root`.
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
@@ -163,30 +129,12 @@ mod tests {
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
Some(Format::Jacoco)
);
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), Some(Format::Cobertura));
assert_eq!(
detect("<?xml version=\"1.0\"?><!DOCTYPE coverage SYSTEM \"x.dtd\"><coverage/>"),
Some(Format::Cobertura)
);
assert_eq!(detect("<?xml version=\"1.0\"?><html/>"), None);
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
assert_eq!(detect("{\"RSpec\": {\"coverage\": {}}}"), Some(Format::SimpleCov));
assert_eq!(detect("{\"name\": \"package.json\"}"), None);
assert_eq!(detect("hello"), None);
}
#[test]
fn missing_directories_are_looked_up_once() {
let tmp = tempfile::tempdir().unwrap();
let mut known = HashMap::new();
assert!(dir_exists(tmp.path(), &mut known));
let gone = tmp.path().join("gone");
assert!(!dir_exists(&gone.join("a/b"), &mut known));
std::fs::create_dir_all(gone.join("a/c")).unwrap();
// Known to be missing, so its subdirectories are not looked up.
assert!(!dir_exists(&gone.join("a/c"), &mut known));
assert_eq!(known.get(&gone), Some(&false));
}
#[test]
fn imports_ci_simplecov_with_foreign_paths() {
let tmp = tempfile::tempdir().unwrap();
@@ -220,75 +168,8 @@ mod tests {
assert!(import(&tmp.path().join("missing"), &root).is_err());
std::fs::write(&report, "nothing").unwrap();
assert!(import(&report, &root).is_err());
std::fs::write(&report, "!coverage.py: This is a private format, don't read it directly!{\"lines\":{}}")
.unwrap();
assert!(import(&report, &root).unwrap_err().to_string().contains("coverage.py 4 data"));
}
/// `coverage xml` (coverage.py 7.17, `--branch`) of a project checked out on a CI runner.
#[test]
fn imports_coverage_py_xml_with_foreign_sources() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("app");
std::fs::create_dir_all(root.join("src/calc")).unwrap();
std::fs::write(root.join("src/calc/__init__.py"), "").unwrap();
let report = tmp.path().join("coverage.xml");
std::fs::write(&report, COVERAGE_PY_XML).unwrap();
let suite = import(&report, &root).unwrap();
assert_eq!(suite.runner, "Cobertura");
assert!(suite.has_branches);
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("src/calc/__init__.py")).unwrap();
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (8, 5, 4, 2));
assert_eq!(calc.lines.iter().filter(|l| l.partial()).map(|l| l.line).collect::<Vec<_>>(), [1, 3]);
// The test file is not in this checkout: it keeps the runner's path.
assert!(
suite.files.iter().any(|f| f.path.as_ref() as &Path == Path::new("/home/runner/work/app/app/test_calc.py"))
);
}
const COVERAGE_PY_XML: &str = r#"<?xml version="1.0" ?>
<coverage version="7.17.5" timestamp="1795754882920" lines-valid="13" lines-covered="10" line-rate="0.7692" branches-valid="4" branches-covered="2" branch-rate="0.5" complexity="0">
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.17.5 -->
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
<sources>
<source>/home/runner/work/app/app</source>
</sources>
<packages>
<package name="." line-rate="1" branch-rate="1" complexity="0">
<classes>
<class name="test_calc.py" filename="test_calc.py" complexity="0" line-rate="1" branch-rate="1">
<methods/>
<lines>
<line number="1" hits="1"/>
<line number="2" hits="1"/>
<line number="3" hits="1"/>
<line number="6" hits="1"/>
<line number="7" hits="1"/>
</lines>
</class>
</classes>
</package>
<package name="src.calc" line-rate="0.625" branch-rate="0.5" complexity="0">
<classes>
<class name="__init__.py" filename="src/calc/__init__.py" complexity="0" line-rate="0.625" branch-rate="0.5">
<methods/>
<lines>
<line number="1" hits="1"/>
<line number="2" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
<line number="3" hits="0"/>
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="5"/>
<line number="5" hits="0"/>
<line number="6" hits="1"/>
<line number="13" hits="1"/>
<line number="14" hits="0"/>
</lines>
</class>
</classes>
</package>
</packages>
</coverage>
"#;
#[test]
fn imports_go_profiles_of_nested_modules() {
let tmp = tempfile::tempdir().unwrap();
+1 -4
Переглянути файл
@@ -16,8 +16,6 @@
//!
//! Lines in the model are 0-based, like every IPC coordinate.
mod cobertura;
mod coveragepy;
mod goprofile;
mod import;
mod jacoco;
@@ -25,8 +23,7 @@ mod lcov;
mod plan;
mod simplecov;
pub use coveragepy::is_data_file;
pub use import::{import, import_data};
pub use import::import;
pub use plan::prepare;
use ide_core::{IdeError, IdeResult, IpcPath};
+1 -2
Переглянути файл
@@ -326,8 +326,7 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
argv.extend(py.target.iter().cloned());
let report = CoverageReportSpec::Exported {
runner: s("coverage.py"),
// `--fail-under=0`: a `[report] fail_under` the run misses must not lose its report.
argv: with(&["-m", "coverage", "lcov", "--fail-under=0", "-o", &path(&lcov)]),
argv: with(&["-m", "coverage", "lcov", "-o", &path(&lcov)]),
cwd: dir.to_path_buf().into(),
env: config.env.clone(),
lcov: lcov.into(),
-15
Переглянути файл
@@ -859,21 +859,6 @@ async fn connect_with_retries(
mod tests {
use super::*;
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
/// language (a template one) declares debugpy before Python.
#[test]
fn debugpy_comes_from_the_python_language() {
let dir = tempfile::tempdir().unwrap();
let python = include_str!("../../../languages/python.toml").replace(
"args = [\"-m\", \"debugpy.adapter\"]",
"args = [\"-X\", \"frozen_modules=off\", \"-m\", \"debugpy.adapter\"]",
);
assert!(python.contains("frozen_modules"));
std::fs::write(dir.path().join("python.toml"), python).unwrap();
let languages = LanguageRegistry::load(Some(dir.path())).unwrap();
assert_eq!(find_config(&languages, "debugpy").unwrap().args[0], "-X");
}
#[test]
fn adapters_run_on_the_tool_search_path() {
let search = ide_core::tool_path::search_path();
-114
Переглянути файл
@@ -1,114 +0,0 @@
//! Python Debug Server (`attach` with `listen`): the program connects with its own debugpy,
//! which may differ from the IDE's adapter. Nothing in the protocol compares them.
use crate::session::Session;
use ide_core::IdeError;
use ide_core::event::DebugEvent;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
adapter == "debugpy" && request == "attach" && arguments.get("listen").is_some()
}
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
/// which would wait for the program forever: find out before starting it. Listening again right
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
const RELEASE: Duration = Duration::from_secs(5);
let listen = &arguments["listen"];
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
let deadline = tokio::time::Instant::now() + RELEASE;
loop {
match std::net::TcpListener::bind((host, port)) {
Ok(_) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))),
}
}
}
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
/// Evaluated in the stopped frame as a hover: without a frame, debugpy before 1.8 runs the
/// expression as a statement and prints its value into the program's output.
pub(crate) async fn check_version(s: Arc<Session>, thread: i64) {
const WAIT: Duration = Duration::from_secs(5);
let request = |command: &'static str, arguments: Value| s.conn.request_timeout(command, arguments, WAIT);
let Ok(info) = request("debugpySystemInfo", json!({})).await else { return };
let Some(ide) = info.pointer("/debugpy/version").and_then(Value::as_str) else { return };
let Ok(trace) = request("stackTrace", json!({ "threadId": thread, "levels": 1 })).await else { return };
let Some(frame) = trace.pointer("/stackFrames/0/id").and_then(Value::as_i64) else { return };
let expression = json!({ "expression": "__import__('debugpy').__version__", "frameId": frame, "context": "hover" });
let Ok(reply) = request("evaluate", expression).await else { return };
let Some(program) = reply.get("result").and_then(Value::as_str) else { return };
if let Some(warning) = version_warning(ide, program) {
s.emit(DebugEvent::Output { category: "console".into(), output: warning });
}
}
fn version_warning(ide: &str, program: &str) -> Option<String> {
let program = program.trim_matches(|c| c == '\'' || c == '"');
(program != ide).then(|| {
format!(
"The program uses debugpy {program}, the IDE's debugger debugpy {ide}. If breakpoints or stepping \
misbehave, install the same version where the program runs: pip install debugpy=={ide}\n"
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn warns_only_when_versions_differ() {
assert_eq!(version_warning("1.8.22", "'1.8.22'"), None);
assert_eq!(version_warning("1.8.22", "1.8.22"), None);
let w = version_warning("1.8.22", "'1.8.0'").unwrap();
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
}
#[tokio::test(start_paused = true)]
async fn a_taken_port_is_reported_before_the_adapter_starts() {
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = taken.local_addr().unwrap().port();
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
let e = require_free_port(&listen).await.unwrap_err();
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
drop(taken);
assert!(require_free_port(&listen).await.is_ok());
}
#[tokio::test]
async fn an_address_the_machine_lacks_is_reported_at_once() {
// 192.0.2.0/24 is reserved for documentation, never a local address.
let started = std::time::Instant::now();
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
assert!(started.elapsed() < Duration::from_secs(1));
}
#[tokio::test]
async fn waits_for_the_previous_adapter_to_release_the_port() {
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = previous.local_addr().unwrap().port();
let released = tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(300)).await;
drop(previous);
});
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
released.await.unwrap();
}
#[test]
fn only_debugpy_listen_attaches_check() {
assert!(listens("debugpy", "attach", &json!({"listen": {"port": 5678}})));
assert!(!listens("debugpy", "attach", &json!({"connect": {"port": 5678}})));
assert!(!listens("debugpy", "launch", &json!({"listen": {}})));
}
}
-7
Переглянути файл
@@ -12,7 +12,6 @@ pub mod adapter;
pub mod attach;
mod cargo;
pub mod connection;
mod debugpy;
mod exception_classes;
pub mod jdwp;
mod js_cdp;
@@ -902,9 +901,6 @@ impl DebugManager {
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
) -> IdeResult<DebugSessionId> {
let mut arguments = launch_arguments(&config)?;
if debugpy::listens(&config.adapter, &config.request, &arguments) {
debugpy::require_free_port(&arguments).await?;
}
// An IDE-side marker (never sent to the adapter): the session is a Flutter
// one regardless of what the working directory holds.
let force_flutter =
@@ -1153,9 +1149,6 @@ impl DebugManager {
});
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
if debugpy::listens(&session.adapter, &session.request, &arguments) {
session.debugpy_version_unchecked.store(true, Ordering::Release);
}
let configured = tokio::select! {
biased;
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
-8
Переглянути файл
@@ -75,8 +75,6 @@ pub(crate) struct Session {
pub jdwp_port: std::sync::OnceLock<u16>,
/// The attach goes through the listen-mode relay of [`crate::jdwp::listen_for_jvm`].
pub listen_relay: AtomicBool,
/// A Python Debug Server session whose program's debugpy version is checked on its first stop.
pub(crate) debugpy_version_unchecked: AtomicBool,
pub suspended: Suspension,
/// Pids signalled for the current stop: the reported pid and everything it started (an
/// adapter may report the launcher shell, whose child is the program).
@@ -318,7 +316,6 @@ impl Session {
jvm_pid: AtomicI64::new(0),
jdwp_port: std::sync::OnceLock::new(),
listen_relay: AtomicBool::new(false),
debugpy_version_unchecked: AtomicBool::new(false),
suspended: Suspension::default(),
stop_pids: parking_lot::Mutex::new(Vec::new()),
#[cfg(windows)]
@@ -857,11 +854,6 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
all_threads_stopped: all,
});
});
if let Some(thread) = int("threadId")
&& s.debugpy_version_unchecked.swap(false, Ordering::AcqRel)
{
tokio::spawn(crate::debugpy::check_version(s.clone(), thread));
}
}
"continued" => {
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
+1 -4
Переглянути файл
@@ -127,10 +127,7 @@ mod tests {
fn schema(name: &str, tables: &[&str]) -> CatalogSchema {
CatalogSchema {
name: name.into(),
tables: tables
.iter()
.map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table, comment: None })
.collect(),
tables: tables.iter().map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table }).collect(),
}
}
+7 -12
Переглянути файл
@@ -655,7 +655,7 @@ impl DbManager {
}
}
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default, comment) by table.
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
for row in rows {
@@ -664,15 +664,12 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
let data_type = it.next().flatten().unwrap_or_default();
let nullable = it.next().flatten().as_deref() != Some("0");
let has_default = it.next().flatten().is_some();
// Bridges built before the comment column send five fields.
let comment = it.next().flatten().filter(|c| !c.trim().is_empty());
by_table.entry(table).or_default().push(crate::CompletionColumn {
name,
data_type,
nullable,
primary_key: false,
has_default,
comment,
});
}
by_table
@@ -687,18 +684,16 @@ mod tests {
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
};
let mut commented = row("orders", "note", "1", Some("'none'"));
commented.push(Some("free text".into()));
let mut blank = row("items", "sku", "1", None);
blank.push(Some(" ".into()));
let by_table =
schema_columns(vec![row("orders", "id", "0", None), commented, blank, vec![None, Some("orphan".into())]]);
let by_table = schema_columns(vec![
row("orders", "id", "0", None),
row("orders", "note", "1", Some("'none'")),
row("items", "sku", "1", None),
vec![None, Some("orphan".into())],
]);
let orders = &by_table["orders"];
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
assert_eq!((orders[0].comment.as_deref(), orders[1].comment.as_deref()), (None, Some("free text")));
assert_eq!(by_table["items"][0].comment, None);
assert_eq!(by_table["items"].len(), 1);
assert_eq!(by_table.len(), 2);
}
+10 -75
Переглянути файл
@@ -31,7 +31,7 @@ pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
@@ -146,10 +146,6 @@ pub struct SchemaObject {
pub struct TableInfo {
pub name: String,
pub kind: DbTableKind,
/// The table's or view's comment; `None` when it has none, or the engine keeps no comments.
#[serde(default)]
#[specta(optional)]
pub comment: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -161,10 +157,6 @@ pub struct ColumnInfo {
pub nullable: bool,
pub default: Option<String>,
pub primary_key: bool,
/// `None` when it has none, or the engine keeps no comments.
#[serde(default)]
#[specta(optional)]
pub comment: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -180,10 +172,6 @@ pub struct IndexInfo {
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTableDetails")]
pub struct TableDetails {
/// The table's comment; `None` when it has none, or the engine keeps no comments.
#[serde(default)]
#[specta(optional)]
pub comment: Option<String>,
pub columns: Vec<ColumnInfo>,
pub indexes: Vec<IndexInfo>,
pub foreign_keys: Vec<ForeignKey>,
@@ -212,10 +200,6 @@ pub struct CompletionColumn {
pub primary_key: bool,
/// Has a default (or is generated): optional in INSERT.
pub has_default: bool,
/// The column's comment; `None` when it has none, or the engine keeps no comments.
#[serde(default)]
#[specta(optional)]
pub comment: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -576,18 +560,6 @@ impl DbManager {
None => {}
}
source::save(&self.root, &project)?;
if let Ok(mut folders) = source::load_folders(&self.root) {
let known: std::collections::HashSet<&str> = sources.iter().map(|source| source.id.as_str()).collect();
let mut changed = false;
for folder in &mut folders {
let before = folder.sources.len();
folder.sources.retain(|id| known.contains(id.as_str()));
changed |= folder.sources.len() != before;
}
if changed {
source::save_folders(&self.root, &folders)?;
}
}
old
};
for o in old {
@@ -1123,11 +1095,7 @@ impl DbManager {
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
Some(TableInfo {
name,
kind: DbTableKind::from_catalog(it.next().flatten().as_deref()),
comment: it.next().flatten().filter(|comment| !comment.is_empty()),
})
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
})
.collect())
}
@@ -1151,18 +1119,11 @@ impl DbManager {
let nullable = flag(&it.next().flatten());
let default = it.next().flatten();
let primary_key = flag(&it.next().flatten());
let comment = it.next().flatten().filter(|c| !c.is_empty());
Some(ColumnInfo { name, data_type, nullable, default, primary_key, comment })
Some(ColumnInfo { name, data_type, nullable, default, primary_key })
})
.collect();
if driver == DbDriver::Jdbc {
return Ok(TableDetails {
comment: None,
columns,
indexes: vec![],
foreign_keys: vec![],
triggers: vec![],
});
return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] });
}
let mut indexes: Vec<IndexInfo> = Vec::new();
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
@@ -1214,17 +1175,7 @@ impl DbManager {
Some(TriggerInfo { name, timing, events })
})
.collect();
let comment = match sql::table_comment(driver, schema, table) {
Some(q) => pool.rows(&q, 1).await.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
),
None => None,
};
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
}
/// The object privileges granted on `table`; empty, without a query, on the engines
@@ -1434,13 +1385,10 @@ impl DbManager {
}
DbDriver::Postgres => {
let rel = pool.rows(&sql::postgres_relation(schema, name), 1).await?.into_iter().next();
let (oid, kind, owner, comment) = match rel.as_deref() {
Some([Some(oid), Some(kind), owner, comment]) => (
oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?,
kind.clone(),
owner.clone(),
comment.clone(),
),
let (oid, kind) = match rel.as_deref() {
Some([Some(oid), Some(kind)]) => {
(oid.parse::<u32>().map_err(|e| IdeError::invalid(e.to_string()))?, kind.clone())
}
_ => return Err(missing()),
};
if kind == "v" || kind == "m" {
@@ -1461,7 +1409,6 @@ impl DbManager {
data_type: it.next().flatten().unwrap_or_default(),
not_null: flag(&it.next().flatten()),
default: it.next().flatten(),
comment: it.next().flatten(),
})
})
.collect::<Vec<_>>();
@@ -1475,18 +1422,7 @@ impl DbManager {
})
.collect::<Vec<_>>();
let indexes = cells(pool.rows(&sql::postgres_ddl_indexes(oid), MAX_META_ROWS).await?, 0);
let grants = pool
.rows(&sql::postgres_ddl_grants(oid), MAX_META_ROWS)
.await?
.into_iter()
.filter_map(|r| {
let mut it = r.into_iter();
Some((it.next().flatten()?, it.next().flatten()?, flag(&it.next().flatten())))
})
.collect();
let triggers = cells(pool.rows(&sql::postgres_ddl_triggers(oid), MAX_META_ROWS).await?, 0);
let extras = sql::DdlExtras { comment, owner, grants, triggers };
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes, &extras))
Ok(sql::postgres_table_ddl(schema, name, &columns, &constraints, &indexes))
}
}
}
@@ -1534,7 +1470,6 @@ impl DbManager {
nullable: flag(&Some(next())),
primary_key: flag(&Some(next())),
has_default: flag(&Some(next())),
comment: Some(next()).filter(|c| !c.trim().is_empty()),
};
if name.is_empty() || column.name.is_empty() {
continue;
+3 -22
Переглянути файл
@@ -113,11 +113,7 @@ pub(crate) async fn tables(pool: &SnowflakePool, schema: &str) -> IdeResult<Vec<
Ok(shown
.records()
.filter_map(|r| {
Some(TableInfo {
name: r.get("name")?.to_owned(),
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
})
Some(TableInfo { name: r.get("name")?.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) })
})
.collect())
}
@@ -136,7 +132,6 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
nullable: yes(r.get("null?")),
default: r.get("default").filter(|d| !d.is_empty()).map(str::to_owned),
primary_key: yes(r.get("primary key")),
comment: r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned),
})
})
.collect();
@@ -145,16 +140,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
Ok(keys) => foreign_keys(&keys),
Err(_) => Vec::new(),
};
// `LIKE` matches without case and with wildcards: the exact name picks the row.
let like = format!("SHOW TABLES LIKE {} IN SCHEMA {}", quote_literal(DRIVER, table), schema_path(pool, schema));
let comment = match show(pool, &like).await {
Ok(shown) => shown
.records()
.find(|r| r.get("name") == Some(table))
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
Err(_) => None,
};
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
Ok(TableDetails { columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
}
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
@@ -242,11 +228,7 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
let (Some(&index), Some(name)) = (at.get(r.get("schema_name").unwrap_or_default()), r.get("name")) else {
continue;
};
out[index].tables.push(TableInfo {
name: name.to_owned(),
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
});
out[index].tables.push(TableInfo { name: name.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) });
}
for schema in &mut out {
schema.tables.sort_by(|a, b| a.name.cmp(&b.name));
@@ -455,7 +437,6 @@ pub(crate) async fn completion(pool: &SnowflakePool) -> IdeResult<Vec<Completion
primary_key: false,
has_default: r.get("default").is_some_and(|d| !d.is_empty())
|| r.get("autoincrement").is_some_and(|a| !a.is_empty()),
comment: r.get("comment").filter(|c| !c.trim().is_empty()).map(str::to_owned),
});
}
Ok(tables)
+2 -138
Переглянути файл
@@ -1,17 +1,15 @@
//! Data sources: per-project connection settings in `.openidea/data-sources.toml`, and
//! global ones (IDEA's Make Global: listed in every project) in `data-sources.toml` of the
//! app data directory. Project folder grouping is in `.openidea/data-source-folders.toml`.
//! Passwords never go there: saved ones live in [`crate::secrets`],
//! app data directory. Passwords never go there: saved ones live in [`crate::secrets`],
//! the others only in memory for the session.
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{BTreeMap, HashSet};
use std::collections::BTreeMap;
use std::path::Path;
pub(crate) const FILE: &str = "data-sources.toml";
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -699,108 +697,6 @@ fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
Ok(())
}
/// A user folder grouping data sources in one project's Database tree.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbSourceFolder {
pub id: String,
pub name: String,
/// Reserved for nested folders; the first UI version only creates root folders.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
pub order: i32,
pub sources: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct SourceFoldersFile {
#[serde(default = "folders_version")]
version: u32,
#[serde(default, rename = "folder")]
folders: Vec<DbSourceFolder>,
}
fn folders_version() -> u32 {
1
}
/// The project's data source folders and their members.
pub fn load_folders(root: &Path) -> IdeResult<Vec<DbSourceFolder>> {
let path = project_dir::path(root, FOLDERS_FILE);
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e.into()),
};
let file: SourceFoldersFile =
toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
if file.version > 1 {
return Err(IdeError::invalid(format!(
"{}: folder format version {} is newer than this OpenIDEA",
path.display(),
file.version
)));
}
Ok(file.folders)
}
/// Replaces the project's data source folders after validating ids, parents and memberships.
pub fn save_folders(root: &Path, folders: &[DbSourceFolder]) -> IdeResult<()> {
validate_folders(folders)?;
let path = project_dir::path(root, FOLDERS_FILE);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let file = SourceFoldersFile { version: folders_version(), folders: folders.to_vec() };
let text = toml::to_string_pretty(&file).map_err(|e| IdeError::internal(e.to_string()))?;
let tmp = path.with_file_name(format!(".{FOLDERS_FILE}.{}.tmp", uuid::Uuid::new_v4()));
std::fs::write(&tmp, text)?;
if let Err(e) = std::fs::rename(&tmp, &path) {
let _ = std::fs::remove_file(&tmp);
return Err(e.into());
}
Ok(())
}
fn validate_folders(folders: &[DbSourceFolder]) -> IdeResult<()> {
let mut ids = HashSet::new();
let mut members = HashSet::new();
for folder in folders {
if folder.id.trim().is_empty() || folder.name.trim().is_empty() {
return Err(IdeError::invalid("every data source folder needs an id and a name"));
}
if !ids.insert(folder.id.as_str()) {
return Err(IdeError::invalid(format!("duplicate data source folder id '{}'", folder.id)));
}
for source in &folder.sources {
if source.is_empty() {
return Err(IdeError::invalid(format!("folder '{}' has an empty data source id", folder.name)));
}
if !members.insert(source.as_str()) {
return Err(IdeError::invalid(format!("data source '{source}' belongs to more than one folder")));
}
}
}
for folder in folders {
let mut seen = HashSet::new();
let mut parent = folder.parent.as_deref();
while let Some(id) = parent {
if id == folder.id || !seen.insert(id) {
return Err(IdeError::invalid(format!("data source folder '{}' has a parent cycle", folder.name)));
}
parent =
folders.iter().find(|candidate| candidate.id == id).and_then(|candidate| candidate.parent.as_deref());
if parent.is_none() && !folders.iter().any(|candidate| candidate.id == id) {
return Err(IdeError::invalid(format!(
"data source folder '{}' has an unknown parent '{id}'",
folder.name
)));
}
}
}
Ok(())
}
/// Credential store access. Blocking (may show an OS prompt): call off the async runtime.
/// Keys are data source ids; [`secrets::ssh_key`] names the SSH password / passphrase.
#[cfg(test)]
@@ -828,38 +724,6 @@ mod tests {
assert!(save(tmp.path(), &[DataSource::default()]).is_err());
}
#[test]
fn source_folders_round_trip_and_reject_invalid_memberships() {
let tmp = tempfile::tempdir().unwrap();
let folders = vec![
DbSourceFolder {
id: "prod".into(),
name: "Production".into(),
parent: None,
order: 0,
sources: vec!["pg".into(), "mysql".into()],
},
DbSourceFolder { id: "empty".into(), name: "Empty".into(), parent: None, order: 1, sources: vec![] },
];
save_folders(tmp.path(), &folders).unwrap();
assert_eq!(load_folders(tmp.path()).unwrap(), folders);
let duplicate = vec![
DbSourceFolder { sources: vec!["pg".into()], ..folders[0].clone() },
DbSourceFolder { id: "other".into(), sources: vec!["pg".into()], ..folders[1].clone() },
];
assert!(save_folders(tmp.path(), &duplicate).is_err());
let cycle = vec![
DbSourceFolder { parent: Some("b".into()), ..folders[0].clone() },
DbSourceFolder { id: "b".into(), parent: Some("prod".into()), ..folders[1].clone() },
];
assert!(save_folders(tmp.path(), &cycle).is_err());
let missing = vec![DbSourceFolder { parent: Some("missing".into()), ..folders[0].clone() }];
assert!(save_folders(tmp.path(), &missing).is_err());
}
#[test]
fn reads_configs_written_before_the_new_settings() {
let tmp = tempfile::tempdir().unwrap();
+34 -205
Переглянути файл
@@ -95,52 +95,46 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
}
}
/// Rows: `name, kind, comment` where kind is `table`, `view` or `materialized view`.
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
pub fn tables(driver: DbDriver, schema: &str) -> String {
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => format!(
"SELECT name, CASE engine WHEN 'View' THEN 'view' WHEN 'MaterializedView' THEN 'materialized view' \
WHEN 'WindowView' THEN 'view' ELSE 'table' END, comment FROM system.tables \
WHEN 'WindowView' THEN 'view' ELSE 'table' END FROM system.tables \
WHERE database = {} AND is_temporary = 0 ORDER BY name",
quote_literal(driver, schema)
),
DbDriver::Sqlite => format!(
"SELECT name, type, NULL FROM {}.sqlite_master WHERE type IN ('table', 'view') \
"SELECT name, type FROM {}.sqlite_master WHERE type IN ('table', 'view') \
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
quote_ident(driver, schema)
),
DbDriver::Snowflake => format!(
"SELECT table_name, CASE table_type WHEN 'VIEW' THEN 'view' WHEN 'MATERIALIZED VIEW' THEN 'materialized view' \
ELSE 'table' END, comment FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
ELSE 'table' END FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Oracle => format!(
"SELECT table_name, CASE WHEN table_type = 'VIEW' THEN 'view' ELSE 'table' END, comments \
FROM all_tab_comments WHERE owner = {} ORDER BY 1",
"SELECT table_name, 'table' FROM all_tables WHERE owner = {} \
UNION ALL SELECT view_name, 'view' FROM all_views WHERE owner = {} ORDER BY 1",
quote_literal(driver, schema),
quote_literal(driver, schema)
),
DbDriver::Postgres => format!(
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, \
obj_description(c.oid, 'pg_class') \
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = {} AND c.relkind IN ('r', 'v', 'm', 'p', 'f') ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Mysql => format!(
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
CASE WHEN table_type LIKE '%VIEW%' THEN NULL ELSE NULLIF(table_comment, '') END \
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::SqlServer => format!(
"SELECT t.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
CAST(ep.value AS nvarchar(max)) \
FROM INFORMATION_SCHEMA.TABLES t \
LEFT JOIN sys.extended_properties ep \
ON ep.major_id = OBJECT_ID(QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)) \
AND ep.minor_id = 0 AND ep.name = 'MS_Description' \
WHERE t.TABLE_SCHEMA = {} ORDER BY 1",
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
quote_literal(driver, schema)
),
}
@@ -151,8 +145,7 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n
WHEN data_type = 'TEXT' THEN 'VARCHAR(' || character_maximum_length || ')' \
WHEN data_type LIKE 'TIME%' THEN data_type || '(' || datetime_precision || ')' ELSE data_type END";
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`, and the column's
/// comment on the engines that keep one (PostgreSQL, MySQL, Oracle, ClickHouse).
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`.
pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
@@ -160,7 +153,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
DbDriver::Clickhouse => format!(
"SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \
OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \
if(default_kind = '', NULL, default_expression), is_in_primary_key, comment \
if(default_kind = '', NULL, default_expression), is_in_primary_key \
FROM system.columns WHERE database = {s} AND table = {t} ORDER BY position"
),
DbDriver::Sqlite => format!(
@@ -173,14 +166,13 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
col_description(format('%I.%I', c.table_schema, c.table_name)::regclass, c.ordinal_position::int) \
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
ORDER BY c.ordinal_position"
),
DbDriver::Mysql => format!(
"SELECT column_name, column_type, is_nullable, column_default, \
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END, column_comment \
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END \
FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \
ORDER BY ordinal_position"
),
@@ -200,10 +192,8 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
),
DbDriver::Oracle => format!(
"SELECT c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), c.data_default, \
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END \
FROM all_tab_columns c \
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
AND cc.column_name = c.column_name \
LEFT JOIN (SELECT kc.column_name FROM all_constraints con \
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
AND kc.constraint_name = con.constraint_name \
@@ -214,28 +204,6 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
}
}
/// One row, one column: the table's comment (`NULL` or empty for none). `None` for the
/// engines whose comments the IDE doesn't read here (Snowflake reads it with `SHOW`).
pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
DbDriver::Postgres => Some(format!(
"SELECT obj_description(c.oid, 'pg_class') FROM pg_class c \
JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = {s} AND c.relname = {t}"
)),
// A view's `table_comment` is the word `VIEW`.
DbDriver::Mysql => Some(format!(
"SELECT CASE WHEN table_type = 'VIEW' THEN NULL ELSE table_comment END \
FROM information_schema.tables WHERE table_schema = {s} AND table_name = {t}"
)),
DbDriver::Oracle => {
Some(format!("SELECT comments FROM all_tab_comments WHERE owner = {s} AND table_name = {t}"))
}
DbDriver::Clickhouse => Some(format!("SELECT comment FROM system.tables WHERE database = {s} AND name = {t}")),
_ => None,
}
}
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
// most columns an index or key has): unlike a series per catalog row, it lets the planner find the
@@ -307,7 +275,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1, c.comment \
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
"c.database",
@@ -318,7 +286,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END, NULL \
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
"'main'",
@@ -331,7 +299,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
AND a.attnum = ANY(i.indkey)) THEN 1 ELSE 0 END, \
CASE WHEN a.atthasdef OR EXISTS (SELECT 1 FROM pg_depend d WHERE d.refclassid = 'pg_class'::regclass \
AND d.refobjid = c.oid AND d.refobjsubid = a.attnum AND d.classid = 'pg_class'::regclass \
AND d.deptype = 'i') THEN 1 ELSE 0 END, col_description(c.oid, a.attnum) \
AND d.deptype = 'i') THEN 1 ELSE 0 END \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
@@ -342,7 +310,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
DbDriver::Mysql => (
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END, c.column_comment \
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
@@ -357,7 +325,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA AND k.TABLE_NAME = tc.TABLE_NAME \
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY' AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA \
AND tc.TABLE_NAME = c.TABLE_NAME AND k.COLUMN_NAME = c.COLUMN_NAME) THEN 1 ELSE 0 END, \
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END, NULL \
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
@@ -367,7 +335,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
DbDriver::Snowflake => (
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END, c.comment \
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
@@ -378,10 +346,8 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END \
FROM all_tab_columns c \
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
AND cc.column_name = c.column_name \
LEFT JOIN all_views v ON v.owner = c.owner AND v.view_name = c.table_name \
LEFT JOIN (SELECT con.owner, con.table_name, kc.column_name FROM all_constraints con \
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
@@ -666,22 +632,21 @@ pub fn sqlite_ddl(schema: &str, name: &str) -> String {
)
}
/// Rows: `oid, relkind, owner, comment` of a PostgreSQL relation.
/// Rows: `oid, relkind` of a PostgreSQL relation.
pub fn postgres_relation(schema: &str, name: &str) -> String {
format!(
"SELECT c.oid::text, c.relkind::text, pg_get_userbyid(c.relowner), obj_description(c.oid, 'pg_class') \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
"SELECT c.oid::text, c.relkind::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = {} AND c.relname = {}",
quote_literal(DbDriver::Postgres, schema),
quote_literal(DbDriver::Postgres, name)
)
}
/// Rows: `name, type, not null (0/1), default, comment` of relation `oid`.
/// Rows: `name, type, not null (0/1), default` of relation `oid`.
pub fn postgres_ddl_columns(oid: u32) -> String {
format!(
"SELECT a.attname, format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 1 ELSE 0 END, \
pg_get_expr(d.adbin, d.adrelid), col_description(a.attrelid, a.attnum) FROM pg_attribute a \
pg_get_expr(d.adbin, d.adrelid) FROM pg_attribute a \
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
WHERE a.attrelid = {oid} AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum"
)
@@ -704,27 +669,6 @@ pub fn postgres_ddl_indexes(oid: u32) -> String {
)
}
/// Rows: `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), grantable (0/1) of
/// the privileges relation `oid` grants beyond its owner's. A relation whose ACL was never
/// changed (`relacl` null) grants none.
pub fn postgres_ddl_grants(oid: u32) -> String {
format!(
"SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END, \
string_agg(lower(a.privilege_type), ', ' ORDER BY a.privilege_type), \
CASE WHEN a.is_grantable THEN 1 ELSE 0 END \
FROM pg_class c CROSS JOIN LATERAL aclexplode(c.relacl) a \
WHERE c.oid = {oid} AND a.grantee <> c.relowner GROUP BY 1, 3 ORDER BY 1, 3"
)
}
/// Rows: `CREATE TRIGGER …` of the user triggers of relation `oid`.
pub fn postgres_ddl_triggers(oid: u32) -> String {
format!(
"SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = {oid} AND NOT tgisinternal \
ORDER BY tgname"
)
}
/// Rows: `name, timing, events` of the triggers of a table (SQLite: `name, sql`).
pub fn triggers(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
@@ -964,18 +908,6 @@ pub struct DdlColumn {
pub data_type: String,
pub not_null: bool,
pub default: Option<String>,
pub comment: Option<String>,
}
/// What [`postgres_table_ddl`] adds after `create table` so the script rebuilds the table.
#[derive(Default)]
pub struct DdlExtras {
pub comment: Option<String>,
pub owner: Option<String>,
/// `grantee` (`PUBLIC` for everyone), privileges (`insert, select`), with grant option.
pub grants: Vec<(String, String, bool)>,
/// `CREATE TRIGGER …` statements.
pub triggers: Vec<String>,
}
/// `create table` of a PostgreSQL table from its catalog (the server has no `SHOW CREATE`).
@@ -985,7 +917,6 @@ pub fn postgres_table_ddl(
columns: &[DdlColumn],
constraints: &[(String, String)],
indexes: &[String],
extras: &DdlExtras,
) -> String {
let d = DbDriver::Postgres;
let mut items: Vec<String> = columns
@@ -1002,31 +933,9 @@ pub fn postgres_table_ddl(
})
.collect();
items.extend(constraints.iter().map(|(name, def)| format!(" constraint {} {def}", quote_ident(d, name))));
let target = qualified(d, schema, table);
let mut out = format!("create table {target}\n(\n{}\n);\n", items.join(",\n"));
// The order a script runs in: comments, owner and privileges, then indexes and triggers.
if let Some(comment) = &extras.comment {
out.push_str(&format!("\ncomment on table {target} is {};\n", quote_literal(d, comment)));
}
for c in columns {
if let Some(comment) = &c.comment {
let column = format!("{target}.{}", quote_ident(d, &c.name));
out.push_str(&format!("\ncomment on column {column} is {};\n", quote_literal(d, comment)));
}
}
if let Some(owner) = &extras.owner {
out.push_str(&format!("\nalter table {target}\n owner to {};\n", quote_ident(d, owner)));
}
if !extras.grants.is_empty() {
out.push('\n');
}
for (grantee, privileges, grantable) in &extras.grants {
let to = if grantee == "PUBLIC" { "public".to_owned() } else { quote_ident(d, grantee) };
let option = if *grantable { " with grant option" } else { "" };
out.push_str(&format!("grant {privileges} on {target} to {to}{option};\n"));
}
for statement in indexes.iter().chain(&extras.triggers) {
out.push_str(&format!("\n{};\n", statement.trim_end().trim_end_matches(';')));
let mut out = format!("create table {}\n(\n{}\n);\n", qualified(d, schema, table), items.join(",\n"));
for i in indexes {
out.push_str(&format!("\n{i};\n"));
}
out
}
@@ -1047,40 +956,6 @@ mod tests {
assert_eq!(quote_literal(DbDriver::Mysql, "it's \\"), "'it''s \\\\'");
}
#[test]
fn comments_are_read_where_the_engine_keeps_them() {
assert!(columns(DbDriver::Postgres, "public", "t").contains("col_description("));
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
assert!(tables(DbDriver::Postgres, "public").contains("obj_description(c.oid, 'pg_class')"));
assert!(tables(DbDriver::Mysql, "db").contains("table_comment"));
assert!(tables(DbDriver::Oracle, "S").contains("all_tab_comments"));
assert!(tables(DbDriver::Clickhouse, "db").contains("END, comment FROM system.tables"));
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
// Completion (the hover card of a table or column) carries them too, as the ninth field.
let completion = |driver| completion_columns(driver, CompletionScope::All);
assert!(completion(DbDriver::Postgres).contains("col_description(c.oid, a.attnum)"));
assert!(completion(DbDriver::Mysql).contains("ELSE 0 END, c.column_comment"));
assert!(
completion(DbDriver::Oracle).contains("cc.comments")
&& completion(DbDriver::Oracle).contains("all_col_comments")
);
assert!(completion(DbDriver::Clickhouse).contains("c.is_in_primary_key, 1, c.comment"));
assert!(completion(DbDriver::Snowflake).contains("ELSE 0 END, c.comment"));
for driver in [DbDriver::Sqlite, DbDriver::SqlServer] {
assert!(completion(driver).contains("ELSE 0 END, NULL"), "{driver:?}");
}
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
assert!(table_comment(DbDriver::Oracle, "S", "T").unwrap().contains("all_tab_comments"));
assert!(table_comment(DbDriver::Clickhouse, "db", "t").unwrap().contains("system.tables"));
for driver in [DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Snowflake] {
assert_eq!(table_comment(driver, "s", "t"), None);
}
}
#[test]
fn clickhouse_escapes_backslashes_and_delimiters() {
let driver = DbDriver::Clickhouse;
@@ -1098,7 +973,6 @@ mod tests {
assert_eq!(current_schema(driver), Some("SELECT currentDatabase()"));
let relations = tables(driver, "event's\\db");
assert!(relations.contains("WHEN 'MaterializedView' THEN 'materialized view'"));
assert!(relations.contains(r"END, comment FROM system.tables"));
assert!(relations.contains(r"WHERE database = 'event''s\\db' AND is_temporary = 0"));
let fields = columns(driver, "default", "events");
assert!(fields.starts_with("SELECT name, type, CASE WHEN startsWith(type, 'Nullable(')"));
@@ -1214,7 +1088,6 @@ mod tests {
#[test]
fn sqlserver_introspection_queries() {
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
@@ -1291,10 +1164,8 @@ mod tests {
assert_eq!(DbDriver::Oracle.default_port(), Some(1521));
assert!(schemas(DbDriver::Oracle, true).contains("all_users"));
assert!(schemas(DbDriver::Oracle, false).contains("'MDSYS'"));
let relations = tables(DbDriver::Oracle, "hr");
assert!(relations.contains("all_tab_comments"));
assert!(relations.contains("table_type = 'VIEW'"));
assert!(relations.contains("comments"));
assert!(tables(DbDriver::Oracle, "hr").contains("all_tables"));
assert!(tables(DbDriver::Oracle, "hr").contains("all_views"));
let cols = columns(DbDriver::Oracle, "hr", "employees");
assert!(cols.contains("all_tab_columns"));
assert!(cols.contains("DECODE(c.nullable, 'Y', 'YES', 'NO')"));
@@ -1383,13 +1254,12 @@ mod tests {
#[test]
fn postgres_ddl() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None },
DdlColumn {
name: "name".into(),
data_type: "character varying(40)".into(),
not_null: false,
default: Some("'x'::character varying".into()),
comment: None,
},
];
assert_eq!(
@@ -1398,53 +1268,12 @@ mod tests {
"t",
&cols,
&[("t_pkey".into(), "PRIMARY KEY (id)".into())],
&["CREATE INDEX t_name ON public.t USING btree (name)".into()],
&DdlExtras::default(),
&["CREATE INDEX t_name ON public.t USING btree (name)".into()]
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"name\" character varying(40) default 'x'::character varying,\n constraint \"t_pkey\" PRIMARY KEY (id)\n);\n\nCREATE INDEX t_name ON public.t USING btree (name);\n"
);
}
#[test]
fn postgres_ddl_rebuilds_comments_owner_grants_and_triggers() {
let cols = [
DdlColumn { name: "id".into(), data_type: "integer".into(), not_null: true, default: None, comment: None },
DdlColumn {
name: "note".into(),
data_type: "text".into(),
not_null: false,
default: None,
comment: Some("what's this".into()),
},
];
let extras = DdlExtras {
comment: Some("Orders".into()),
owner: Some("app owner".into()),
grants: vec![("PUBLIC".into(), "select".into(), false), ("reader".into(), "insert, select".into(), true)],
triggers: vec![
"CREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit()".into(),
],
};
assert_eq!(
postgres_table_ddl(
"public",
"t",
&cols,
&[],
&["CREATE INDEX t_note ON public.t USING btree (note)".into()],
&extras
),
"create table \"public\".\"t\"\n(\n \"id\" integer not null,\n \"note\" text\n);\n\
\ncomment on table \"public\".\"t\" is 'Orders';\n\
\ncomment on column \"public\".\"t\".\"note\" is 'what''s this';\n\
\nalter table \"public\".\"t\"\n owner to \"app owner\";\n\
\ngrant select on \"public\".\"t\" to public;\n\
grant insert, select on \"public\".\"t\" to \"reader\" with grant option;\n\
\nCREATE INDEX t_note ON public.t USING btree (note);\n\
\nCREATE TRIGGER t_audit AFTER INSERT ON public.t FOR EACH ROW EXECUTE FUNCTION audit();\n"
);
}
#[test]
fn snowflake_quotes_names_and_reads_its_information_schema() {
let driver = DbDriver::Snowflake;
+6 -10
Переглянути файл
@@ -1,9 +1,9 @@
//! Data source and data source folder files edited outside the Database tool window
//! (by hand, by a coding agent, by `git checkout`) are picked up while the project is open, as IDEA does
//! Data source files edited outside the Database tool window (by hand, by a coding
//! agent, by `git checkout`) are picked up while the project is open, as IDEA does
//! for `dataSources.xml`. The project file tree's watcher is no help here: it never
//! reports a modification inside a gitignored `.openidea/`.
use crate::source::{FILE, FOLDERS_FILE};
use crate::source::FILE;
use ide_core::{IdeError, IdeResult, project_dir};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use parking_lot::Mutex;
@@ -15,8 +15,8 @@ use std::time::Duration;
/// the files are read.
const SETTLE: Duration = Duration::from_millis(200);
/// Watches `<root>/.openidea/data-sources.toml`, `data-source-folders.toml` and
/// `<global>/data-sources.toml`; stops when dropped.
/// Watches `<root>/.openidea/data-sources.toml` and `<global>/data-sources.toml`;
/// stops when dropped.
pub struct SourcesWatch {
_watcher: Arc<Mutex<RecommendedWatcher>>,
}
@@ -29,7 +29,7 @@ impl SourcesWatch {
let (tx, rx) = mpsc::channel::<()>();
let relevant = {
let config = config.clone();
move |p: &Path| p.file_name().is_some_and(|n| n == FILE || n == FOLDERS_FILE) || p == config
move |p: &Path| p.file_name().is_some_and(|n| n == FILE) || p == config
};
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
if let Ok(e) = res
@@ -131,10 +131,6 @@ mod tests {
std::fs::write(project.join(".openidea/data-sources.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "project file");
let seen = count.load(Ordering::SeqCst);
std::fs::write(project.join(".openidea/data-source-folders.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "project folders file");
let seen = count.load(Ordering::SeqCst);
std::fs::write(global.join("data-sources.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "global file");
+1 -6
Переглянути файл
@@ -40,8 +40,7 @@ async fn create_schemas(db: &DbManager) {
format!("DROP DATABASE IF EXISTS `{s}`"),
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
format!(
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin COMMENT '名字', \
raw VARBINARY(4)) COMMENT = '用户表'"
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
),
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
@@ -57,13 +56,9 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
assert!(schemas.iter().any(|n| n == s), "{s} missing from {schemas:?}");
let tables = db.tables("m", s).await?;
assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["用户"], "tables of {s}");
assert_eq!(tables[0].comment.as_deref(), Some("用户表"));
let d = db.table_details("m", s, "用户").await?;
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
assert_eq!(cols, ["id", "name", "raw"]);
assert_eq!(d.comment.as_deref(), Some("用户表"));
let comments: Vec<_> = d.columns.iter().map(|c| c.comment.as_deref()).collect();
assert_eq!(comments, [None, Some("名字"), None]);
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
}
+1 -32
Переглянути файл
@@ -338,8 +338,6 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
"CREATE TABLE oi_meta.lines (n INT PRIMARY KEY, o_region INT, o_id INT, \
FOREIGN KEY (o_region, o_id) REFERENCES oi_meta.orders (region, id))",
"CREATE INDEX lines_order ON oi_meta.lines (o_id, o_region)",
"COMMENT ON TABLE oi_meta.orders IS 'Customer''s orders'",
"COMMENT ON COLUMN oi_meta.orders.note IS 'Free text'",
"CREATE FUNCTION oi_meta.twice(v INT) RETURNS INT AS 'SELECT v * 2' LANGUAGE sql",
] {
db.execute("p", stmt, 10, &c).await?;
@@ -352,13 +350,6 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
assert_eq!(details.foreign_keys[0].columns, ["o_region", "o_id"]);
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
let orders = db.table_details("p", "oi_meta", "orders").await?;
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
let listed = db.tables("p", "oi_meta").await?;
let listed_orders = listed.iter().find(|table| table.name == "orders").expect("orders in the table list");
assert_eq!(listed_orders.comment.as_deref(), Some("Customer's orders"));
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
assert_eq!(comments, [None, None, Some("Free text")]);
assert_eq!(details.comment, None);
let key = orders.indexes.iter().find(|i| i.unique).expect("primary key index");
assert_eq!(key.columns, ["region", "id"]);
@@ -423,29 +414,7 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
db.execute("p", "CREATE SEQUENCE oi_keys.seq", 10, &c).await?;
let objects = db.schema_objects("p", "oi_keys").await?;
assert_eq!(objects.sequences.len(), 1);
let plain = db.ddl("p", "oi_keys", "refs").await?;
assert!(plain.contains("FOREIGN KEY"), "{plain}");
assert!(plain.contains("\n owner to "), "{plain}");
assert!(!plain.contains("comment on") && !plain.contains("grant ") && !plain.contains("TRIGGER"), "{plain}");
// Comments, privileges and triggers come back too, so the script rebuilds the table.
for statement in [
"COMMENT ON TABLE oi_keys.refs IS 'Refs'",
"COMMENT ON COLUMN oi_keys.refs.x IS 'it''s x'",
"GRANT SELECT, INSERT ON oi_keys.refs TO PUBLIC",
"CREATE FUNCTION oi_keys.touch() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RETURN NEW; END'",
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch()",
] {
db.execute("p", statement, 10, &c).await?;
}
let full = db.ddl("p", "oi_keys", "refs").await?;
for part in [
"comment on table \"oi_keys\".\"refs\" is 'Refs';",
"comment on column \"oi_keys\".\"refs\".\"x\" is 'it''s x';",
"grant insert, select on \"oi_keys\".\"refs\" to public;",
"CREATE TRIGGER refs_touch BEFORE UPDATE ON oi_keys.refs FOR EACH ROW EXECUTE FUNCTION oi_keys.touch();",
] {
assert!(full.contains(part), "{part}\n{full}");
}
assert!(db.ddl("p", "oi_keys", "refs").await?.contains("FOREIGN KEY"));
db.execute("p", "DROP SCHEMA oi_keys CASCADE", 10, &c).await?;
Ok(())
}
+13 -22
Переглянути файл
@@ -27,24 +27,18 @@ const QUICK: Duration = Duration::from_secs(20);
/// Stop / restart wait for the container's grace period (10 s by default).
const LIFECYCLE: Duration = Duration::from_secs(90);
/// Locates the docker executable. GUI apps on macOS start with a minimal `PATH`, so
/// the login/reloaded `PATH` and usual install locations are probed after the lookup.
/// Only a found path is cached, so installing Docker while the backend runs is picked up.
/// Locates the docker executable once per process. GUI apps on macOS start with a
/// minimal `PATH`, so the usual install locations are probed after the lookup.
pub fn docker_executable() -> Option<PathBuf> {
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
static DOCKER: OnceLock<PathBuf> = OnceLock::new();
if let Some(cached) = DOCKER.get().filter(|p| p.is_file()) {
return Some(cached.clone());
}
let found = which::which("docker")
.ok()
.or_else(|| {
let path = ide_core::process::host_var_os("PATH")?;
which::which_in("docker", Some(path), ".").ok()
})
.or_else(|| {
static DOCKER: OnceLock<Option<PathBuf>> = OnceLock::new();
DOCKER
.get_or_init(|| {
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
if let Ok(found) = which::which("docker") {
return Some(found);
}
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
let mut candidates: Vec<PathBuf> = if cfg!(windows) {
vec![PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin\docker.exe")]
@@ -66,11 +60,8 @@ pub fn docker_executable() -> Option<PathBuf> {
candidates.push(home.join(".docker/bin/docker"));
}
candidates.into_iter().find(|p| p.is_file())
});
if let Some(ref path) = found {
let _ = DOCKER.set(path.clone());
}
found
})
.clone()
}
/// Environment for docker command lines a run configuration launches: the endpoint's
+1
Переглянути файл
@@ -12,3 +12,4 @@ serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
which = "8"
+18 -37
Переглянути файл
@@ -16,15 +16,30 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::time::Duration;
/// API calls normally answer within a few seconds.
const QUICK: Duration = Duration::from_secs(60);
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
/// install or remove a managed copy in its tools directory at runtime).
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
pub fn gh_executable() -> Option<PathBuf> {
ide_core::tool_path::find_gh_executable()
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
GH.get_or_init(|| {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
if let Ok(found) = which::which("gh") {
return Some(found);
}
let candidates: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
})
.clone()
}
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
@@ -371,37 +386,3 @@ pub fn prepare_diff(
let files = repo.diff_files(&base, head_oid)?;
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
}
#[cfg(test)]
mod tests {
#[test]
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let search = std::env::join_paths([&dir]).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
std::fs::remove_file(&gh).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let _ = std::fs::remove_dir_all(&dir);
}
}
-5
Переглянути файл
@@ -82,11 +82,6 @@ impl Environment {
}
}
/// True on `openidea-server`, where the backend runs on a remote/headless host rather than the desktop shell.
pub fn is_remote(&self) -> bool {
self.project_env
}
/// A trusted project at `root` opened or became trusted: loads its direnv environment in
/// the background, unless another window of it already did. Its language servers wait.
pub(crate) fn direnv_opened(&self, root: &Path, sink: &SharedSink) {
+1 -26
Переглянути файл
@@ -261,12 +261,6 @@ 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,
@@ -301,8 +295,7 @@ fn external_tool(
)))
};
}
let id = formatter_language(language.id.as_str());
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
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)
@@ -904,24 +897,6 @@ 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();
-340
Переглянути файл
@@ -1,340 +0,0 @@
//! 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);
}
}
+4 -97
Переглянути файл
@@ -2,7 +2,7 @@
use ide_build::kotlin_bridge::{self, Outcome, ProjectLibraries};
use ide_core::event::NotifyLevel;
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink, TaskId};
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink};
use ide_lsp::LspManager;
use ide_workspace::SettingsStore;
use ide_workspace::documents::DocumentObserver;
@@ -223,15 +223,9 @@ impl KotlinBridge {
let staging = directory.clone();
let root = self.root.clone();
let token = cancel.clone();
// The build runs Maven over the Kotlin modules, which can take a minute: it shows in
// the status bar and can be stopped there (the next saved change builds again).
let task = BuildTask::start(self.sink.clone(), &cancel);
let progress = task.reporter();
let result = tokio::task::spawn_blocking(move || {
kotlin_bridge::build(&root, &model, &bundle, &staging, &token, &progress)
})
.await;
drop(task);
let result =
tokio::task::spawn_blocking(move || kotlin_bridge::build(&root, &model, &bundle, &staging, &token))
.await;
if !self.revision.lock().current(generation) || self.lifetime.is_cancelled() {
remove_directory(directory).await;
continue;
@@ -312,58 +306,6 @@ impl KotlinBridge {
}
}
/// The status bar's background task for one bridge build; ends when dropped.
struct BuildTask {
id: TaskId,
sink: SharedSink,
_cancel: ide_core::task::CancelHandle,
}
impl BuildTask {
const TITLE: &str = "Compiling Kotlin for Java";
fn start(sink: SharedSink, cancel: &CancellationToken) -> Self {
let id = TaskId::next();
let cancel = cancel.clone();
let handle = ide_core::task::on_cancel(id, move || cancel.cancel());
let task = Self { id, sink, _cancel: handle };
task.emit(None, None, false);
task
}
fn emit(&self, message: Option<String>, fraction: Option<f32>, done: bool) {
self.sink.emit(IdeEvent::Task {
id: self.id,
title: Self::TITLE.into(),
message,
fraction,
done,
cancellable: !done,
});
}
/// Forwards Maven's progress to the task.
fn reporter(&self) -> impl Fn(&str, Option<f32>) + Send + Sync + 'static {
let (id, sink) = (self.id, self.sink.clone());
move |message: &str, fraction| {
sink.emit(IdeEvent::Task {
id,
title: Self::TITLE.into(),
message: Some(message.to_owned()),
fraction,
done: false,
cancellable: true,
})
}
}
}
impl Drop for BuildTask {
fn drop(&mut self) {
self.emit(None, None, true);
}
}
/// The error text of a failed bridge build, and whether to notify about it. Compiler errors
/// in the user's own Kotlin already show in its editor and stay in Problems; only a build
/// that failed without one (Maven itself, a missing plugin) is worth a notification.
@@ -427,41 +369,6 @@ impl DocumentObserver for KotlinBridge {
mod tests {
use super::*;
#[test]
fn a_build_shows_as_a_cancellable_background_task() {
let events = Arc::new(Mutex::new(Vec::new()));
let sink: SharedSink = Arc::new({
let events = events.clone();
move |e: IdeEvent| events.lock().push(e)
});
let cancel = CancellationToken::new();
let task = BuildTask::start(sink, &cancel);
let progress = task.reporter();
progress("Building app 1.0 [2/3]", Some(0.5));
assert!(ide_core::task::cancel(task.id), "the status bar can stop it");
assert!(cancel.is_cancelled());
drop(task);
let seen: Vec<_> = events
.lock()
.iter()
.map(|e| match e {
IdeEvent::Task { title, message, fraction, done, cancellable, .. } => {
assert_eq!(title, "Compiling Kotlin for Java");
(message.clone(), *fraction, *done, *cancellable)
}
other => panic!("{other:?}"),
})
.collect();
assert_eq!(
seen,
[
(None, None, false, true),
(Some("Building app 1.0 [2/3]".into()), Some(0.5), false, true),
(None, None, true, false),
]
);
}
#[test]
fn target_package_directory_does_not_trigger() {
let dir = tempfile::tempdir().unwrap();
-4
Переглянути файл
@@ -12,7 +12,6 @@ pub mod diagnostics_store;
mod direnv;
pub mod environment;
mod formatter;
pub mod github_auth;
mod java_runtime;
mod kotlin_bridge;
pub mod mcp;
@@ -125,7 +124,6 @@ pub struct Host {
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
/// The IDE's Java build: resident javac processes shared by every window's launches.
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
pub(crate) metrics_sampler: Mutex<ops::host_metrics::HostMetricsSampler>,
/// SSH connections of Settings › SSH Configurations.
pub ssh: Arc<ide_ssh::SshManager>,
/// SFTP deployment, remote file editing and runs on run targets.
@@ -256,7 +254,6 @@ impl Host {
heap_requests: Default::default(),
rebase_editors: Default::default(),
java_build: Default::default(),
metrics_sampler: Default::default(),
languages,
syntax,
config_dir,
@@ -422,7 +419,6 @@ 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 {
-5
Переглянути файл
@@ -38,11 +38,6 @@ impl Requests {
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
Ok(())
}
/// Whether `window` answers requests (a project loaded for MCP alone has no window).
pub(super) fn window_ready(&self, window: &str) -> bool {
self.0.lock().ready.contains(window)
}
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
let id = super::tool::request_id().0;
let (tx, rx) = oneshot::channel();
+7 -87
Переглянути файл
@@ -15,9 +15,8 @@ use ide_core::{IdeError, IdeResult, RunId, Severity};
use ide_run::{OutputChunk, RunConfig};
use parking_lot::Mutex;
use serde_json::{Map, Value, json};
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};
@@ -287,79 +286,6 @@ workingDirectory, envs).",
/// not the user's own runs.
static STARTED: LazyLock<Mutex<HashSet<RunId>>> = LazyLock::new(Default::default);
/// Run configuration parameter naming the `execute_run_configuration` call a start belongs to.
pub const CONFIG_RUN_PARAM: &str = "mcp.configRun";
/// The `execute_run_configuration` calls waiting for the Run tool window to start their run.
struct ConfigLaunch {
output: Arc<Mutex<OutputCollector>>,
started: Option<Result<ide_run::RunInfo, String>>,
}
static LAUNCHES: LazyLock<Mutex<HashMap<u64, ConfigLaunch>>> = LazyLock::new(Default::default);
static NEXT_LAUNCH: AtomicU64 = AtomicU64::new(1);
/// The Run tool window's start of an `execute_run_configuration` run: its output also goes to
/// the call's output file, and the call learns the run it started.
pub(crate) struct ConfigRunLaunch {
token: u64,
output: Arc<Mutex<OutputCollector>>,
}
/// The call `config` was started for (its first start only; a rerun from the tab is the user's).
pub(crate) fn config_run_launch(config: &RunConfig) -> Option<ConfigRunLaunch> {
let token = config.extras.params.get(CONFIG_RUN_PARAM)?.parse().ok()?;
let launches = LAUNCHES.lock();
let launch = launches.get(&token).filter(|l| l.started.is_none())?;
Some(ConfigRunLaunch { token, output: launch.output.clone() })
}
impl ConfigRunLaunch {
pub(crate) fn wrap_output(&self, on_output: crate::ops::Emit<OutputChunk>) -> crate::ops::Emit<OutputChunk> {
let output = self.output.clone();
Arc::new(move |chunk: OutputChunk| {
// As JetBrains skips `ProcessOutputType.SYSTEM` (`Process finished…`).
if let OutputChunk::Stdout { text } | OutputChunk::Stderr { text } = &chunk {
output.lock().append(text);
}
on_output(chunk);
})
}
pub(crate) fn started(&self, result: &IdeResult<ide_run::RunInfo>) {
if let Some(launch) = LAUNCHES.lock().get_mut(&self.token) {
launch.started = Some(result.clone().map_err(|e| e.message));
}
}
}
/// Starts `config` in the Run tool window, as the user's Run would: a tab with its console and
/// Stop. Its before launch tasks already ran.
async fn start_in_run_window(
call: &Call,
mut config: RunConfig,
output: Arc<Mutex<OutputCollector>>,
) -> IdeResult<ide_run::RunInfo> {
struct Forget(u64);
impl Drop for Forget {
fn drop(&mut self) {
LAUNCHES.lock().remove(&self.0);
}
}
let token = NEXT_LAUNCH.fetch_add(1, Ordering::Relaxed);
LAUNCHES.lock().insert(token, ConfigLaunch { output, started: None });
let _forget = Forget(token);
config.extras.params.insert(CONFIG_RUN_PARAM.into(), token.to_string());
let config = serde_json::to_value(&config).map_err(|e| IdeError::invalid(e.to_string()))?;
let asked = call.ask(ide_core::event::McpUiRequest::RunConfiguration { config }).await;
let started = LAUNCHES.lock().get_mut(&token).and_then(|l| l.started.take());
match (asked, started) {
(_, Some(Ok(info))) => Ok(info),
(_, Some(Err(message))) => Err(IdeError::invalid(message)),
(Err(e), None) => Err(e),
(Ok(()), None) => Err(IdeError::invalid("the run did not start")),
}
}
pub(super) fn started_by_mcp(id: RunId) -> bool {
STARTED.lock().contains(&id)
}
@@ -827,9 +753,9 @@ Behavior:
Returns the execution result including current output snapshot, optional exit code, and optional `fullOutputPath`.
In OpenIDEA the user is asked first for every call; `programArguments` replace the configuration's \
arguments (appended to a command that is one shell line, such as `npm run dev`); the run appears in the Run tool \
window like a run the user started, with its console and Stop; while it is still running, the result carries `runId`, \
which `stop_run` stops; output files are private and deleted after a day.",
arguments (appended to a command that is one shell line, such as `npm run dev`); the run does not appear in the Run \
tool window: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \
and deleted after a day.",
|call| async move {
let target = execution_target(
call.opt_str("configurationName")?,
@@ -885,15 +811,9 @@ one by one",
};
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
let output_path = collector.lock().path.clone();
let started = if call.has_window() {
start_in_run_window(&call, config, collector.clone()).await
} else {
// A project loaded for MCP alone has no Run tool window to show it in.
let sink = collector.clone();
let emit = process_output(move |text| sink.lock().append(text));
crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await
};
let info = match started {
let sink = collector.clone();
let emit = process_output(move |text| sink.lock().append(text));
let info = match crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await {
Ok(info) => info,
Err(e) => {
let _ = std::fs::remove_file(&output_path);
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@
pub(crate) mod agent;
mod agent_tools;
mod build;
pub(crate) mod configs;
mod configs;
mod output;
mod process;
mod targets;
+1 -35
Переглянути файл
@@ -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", "unittest", "python"]
&["pytest", "python"]
} else if rel.ends_with(".go") {
&["go"]
} else if rel.ends_with(".rs") {
@@ -644,11 +644,6 @@ 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}") };
@@ -795,11 +790,6 @@ 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"));
@@ -931,30 +921,6 @@ 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");
-4
Переглянути файл
@@ -70,10 +70,6 @@ impl Call {
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
self.host.mcp_requests.ask(self, request).await
}
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
pub fn has_window(&self) -> bool {
self.host.mcp_requests.window_ready(&self.window)
}
/// Asks the user before a tool changes the project or starts a process, unless brave mode
/// is on — read from the IDE's own settings only, which a project's settings can't set.
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
-2
Переглянути файл
@@ -754,8 +754,6 @@ 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,
+5 -180
Переглянути файл
@@ -6,11 +6,11 @@ use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
RemoteSkillPreview, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -80,19 +80,6 @@ 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)]
@@ -121,141 +108,6 @@ pub fn agent_set_env(
host.project(window)?.agents.set_builtin_env(&id, env)
}
/// Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`.
#[command(trust = outside_restricted)]
pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult<CopilotAuthStatus> {
host.require_trust_if_project(window)?;
match host.project(window) {
Ok(project) => Ok(project.agents.copilot_auth_status().await),
Err(_) => {
let custom_dir = host.config_dir.join("agents");
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
Ok(ide_agent::copilot_auth_status_with(Some(&custom_dir), None, &cwd).await)
}
}
}
const REMOTE_SESSION_ENV_VARS: [&str; 5] =
["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "CODESPACES", "REMOTE_CONTAINERS"];
fn prepare_login_launch_env(
is_remote: bool,
target_is_gh: bool,
env: &mut std::collections::BTreeMap<String, String>,
host_has: impl Fn(&str) -> bool,
) {
if !is_remote {
return;
}
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
};
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
if !REMOTE_SESSION_ENV_VARS.iter().any(|key| has_non_empty(env, key)) {
env.insert("REMOTE_CONTAINERS".into(), "1".into());
}
if target_is_gh && !has_non_empty(env, "GH_BROWSER") && !has_non_empty(env, "BROWSER") {
env.insert("GH_BROWSER".into(), "true".into());
}
}
fn apply_remote_login_env(host: &Host, cwd: &std::path::Path, target_is_gh: bool, launch: &mut LoginLaunch) {
let cwd = if cwd.is_dir() { cwd.to_path_buf() } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
prepare_login_launch_env(host.environment.is_remote(), target_is_gh, &mut launch.env, |key| {
ide_core::process::host_var_os_in(&cwd, key).is_some_and(|v| !v.is_empty())
});
}
fn spawn_login_pty(
host: &Host,
window: &str,
cwd: std::path::PathBuf,
launch: LoginLaunch,
cols: u16,
rows: u16,
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
crate::ops::term::apply_output_rate(host, window);
let cwd = if cwd.is_dir() { cwd } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
let options = ide_terminal::TerminalOptions {
cwd: cwd.into(),
shell: Some(launch.program.to_string_lossy().into_owned()),
args: launch.args,
env: launch.env,
cols: if cols == 0 { 80 } else { cols },
rows: if rows == 0 { 20 } else { rows },
shell_integration: false,
};
let exit_channel = on_event.clone();
host.terminals.spawn_program(
options,
format!("agent-login:{window}"),
host.window_sink(window),
Box::new(move |data| {
let _ = on_event.send(AgentLoginEvent::Output { data });
}),
Some(std::sync::Arc::new(move |code| {
let _ = exit_channel.send(AgentLoginEvent::Exited { code });
})),
)
}
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
#[command(trust = outside_restricted)]
pub async fn agent_login_spawn(
host: &Host,
window: &str,
id: String,
cols: u16,
rows: u16,
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
host.require_trust_if_project(window)?;
let (cwd, mut launch) = match host.project(window) {
Ok(project) => {
let root = project.root.clone();
let agents = project.agents.clone();
let launch = host.blocking(move || agents.login_launch(&id)).await?;
(root, launch)
}
Err(_) => {
let custom_dir = host.config_dir.join("agents");
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
let cwd_for_lookup = cwd.clone();
let launch = host
.blocking(move || {
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &id)
})
.await?;
(cwd, launch)
}
};
apply_remote_login_env(host, &cwd, false, &mut launch);
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
}
/// Starts `gh auth login --hostname github.com` in an IDE-managed PTY (with ambient token
/// variables cleared) and streams its output and exit code.
#[command(trust = outside_restricted)]
pub async fn agent_gh_login_spawn(
host: &Host,
window: &str,
cols: u16,
rows: u16,
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
host.require_trust_if_project(window)?;
let cwd = host
.project(window)
.map(|p| p.root.clone())
.unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir));
let mut launch = host.blocking(ide_agent::gh_login_launch).await?;
apply_remote_login_env(host, &cwd, true, &mut launch);
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)?;
@@ -1597,29 +1449,6 @@ mod tests {
assert!(reloaded.approved(&root, "extra", &extra));
assert!(!reloaded.approved(&tmp.path().join("other"), "extra", &extra));
}
#[test]
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
let mut desktop_env = std::collections::BTreeMap::new();
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
assert!(desktop_env.is_empty());
let mut remote_agent_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
let mut remote_gh_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
// Preserves existing SSH/remote indicators and explicit browser settings.
let mut ssh_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
assert!(!ssh_env.contains_key("GH_BROWSER"));
}
}
ide_command::domain!(
@@ -1634,18 +1463,15 @@ ide_command::domain!(
agent_cli_update,
agent_cli_update_check,
agent_commands,
agent_copilot_auth_status,
agent_create,
agent_delete,
agent_entries,
agent_external_sessions,
agent_fork,
agent_fork_session,
agent_gh_login_spawn,
agent_grouped_changes,
agent_hermes_profiles,
agent_import_session,
agent_login_spawn,
agent_mcp_discover_sources,
agent_mcp_import,
agent_mcp_import_selected,
@@ -1655,7 +1481,6 @@ ide_command::domain!(
agent_mcp_save_json,
agent_mcp_set_enabled,
agent_mcp_test,
agent_preview_copilot_models,
agent_probe,
agent_prompt,
agent_providers,
+4 -25
Переглянути файл
@@ -3,7 +3,7 @@ use crate::Host;
use ide_command::command;
use super::blocking;
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_core::{IdeResult, IpcPath};
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
use ide_run::RunConfig;
@@ -35,30 +35,9 @@ pub async fn coverage_collect(host: &Host, window: &str, report: CoverageReportS
/// with paths mapped into this project.
#[command(trust = always)]
pub async fn coverage_import(host: &Host, window: &str, path: IpcPath) -> IdeResult<CoverageSuite> {
// Also reads Cobertura XML, a SimpleCov resultset and coverage.py data files.
let project = host.project(window)?;
let (root, cache, config_dir) =
(project.root.clone(), project.cache_dir.join("coverage-import"), host.config_dir.clone());
let trusted = project.require_trust();
blocking(move || {
if !ide_coverage::is_data_file(&path) {
return ide_coverage::import(&path, &root);
}
// coverage.py analyses the sources with the project's interpreter: that runs project code.
trusted.map_err(|_| {
IdeError::unavailable(
"Reading a .coverage data file runs the project's Python. Trust the project, or import the output of `coverage xml`.",
)
})?;
let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| {
IdeError::unavailable(
"Reading a .coverage data file needs the project's Python interpreter. Choose one, or import the output of `coverage xml`.",
)
})?;
let out = ide_run::wrap::new_output_dir(&cache, KEEP_RUNS)?;
ide_coverage::import_data(&path, &root, &python, &out)
})
.await
// Also reads a SimpleCov resultset.
let root = host.project(window)?.root.clone();
blocking(move || ide_coverage::import(&path, &root)).await
}
ide_command::domain!(coverage: coverage_collect, coverage_import, coverage_prepare);
+3 -29
Переглянути файл
@@ -8,8 +8,8 @@ use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
use ide_db::split::SqlStatement;
use ide_db::{
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange, HistoryEntry,
PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode,
QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -75,20 +75,6 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
sources_changed(host, window)
}
#[command(trust = trusted)]
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
// The project's user-created folders and their data source members.
ide_db::source::load_folders(&host.project(window)?.root)
}
#[command(trust = trusted)]
pub fn db_save_source_folders(host: &Host, window: &str, folders: Vec<DbSourceFolder>) -> IdeResult<()> {
// Replaces the project's data source folders; only grouping changes, never a source.
let root = host.project(window)?.root.clone();
ide_db::source::save_folders(&root, &folders)?;
sources_changed(host, window)
}
#[command(trust = trusted)]
pub async fn db_save_source_visibility(
host: &Host,
@@ -626,16 +612,7 @@ pub fn db_consoles(host: &Host, id: String, create: bool) -> IdeResult<Vec<IpcPa
Ok(out)
}
/// The project view root for every data source's query consoles (`<dataDir>/consoles/db`).
#[command(trust = always)]
pub fn db_consoles_dir(host: &Host) -> IdeResult<IpcPath> {
let dir = host.data_dir.join("consoles").join("db");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database,
/// `<id>.<database>` for the others.
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
let (source, database) = ide_db::split_target(id);
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
@@ -693,7 +670,6 @@ ide_command::domain!(
db_connect,
db_connected,
db_console_path,
db_consoles_dir,
db_consoles,
db_create_database,
db_database_catalog,
@@ -716,7 +692,6 @@ ide_command::domain!(
db_result_row,
db_remove_history,
db_retain_catalog,
db_save_source_folders,
db_save_source_visibility,
db_save_sources,
db_saved_catalog,
@@ -726,7 +701,6 @@ ide_command::domain!(
db_set_manual_commit,
db_set_password,
db_set_ssh_secret,
db_source_folders,
db_sources,
db_statements,
db_table_details,
+3 -19
Переглянути файл
@@ -67,12 +67,7 @@ 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)?;
remember_saved_encodings(&project);
Ok(())
})
.await?;
host.blocking(move || project.documents.save(doc)).await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
@@ -88,13 +83,7 @@ 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 || {
let saved = project.documents.autosave(doc)?;
remember_saved_encodings(&project);
Ok(saved)
})
.await?;
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
if saved {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
}
@@ -104,12 +93,7 @@ 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 || {
let saved = project.documents.save_all();
remember_saved_encodings(&project);
saved
})
.await?;
host.blocking(move || project.documents.save_all()).await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
+4 -50
Переглянути файл
@@ -1,13 +1,11 @@
use crate::Host;
use crate::ops::blocking;
use crate::project::Project;
use ide_command::command;
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::settings::SettingsScope;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
use std::path::{Path, PathBuf};
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
use std::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.
@@ -68,49 +66,6 @@ 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.
@@ -163,7 +118,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
}
items
}
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
None => syntax(),
})
})
@@ -308,7 +263,6 @@ ide_command::domain!(
doc_outline,
doc_python_facts,
doc_rearrange,
doc_remember_encoding,
doc_selection_ranges,
doc_set_bom,
doc_set_encoding,
-95
Переглянути файл
@@ -221,98 +221,3 @@ 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);
}
+5 -267
Переглянути файл
@@ -1,14 +1,9 @@
//! Services tool window › Docker (`ide-docker`) and Docker run configurations: run on the
//! project host (`Host` locally, `openidea-server` in a remote window), with SSH connections
//! tunnelled through the host's own SSH client.
use super::Channel;
//! Docker run configurations: the environment their `docker` command line runs with; and Docker
//! connections through an SSH configuration, tunnelled with the IDE's own SSH client.
use crate::Host;
use ide_command::command;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
use ide_docker::{
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
};
use ide_core::{IdeError, IdeResult};
use ide_docker::DockerEndpoint;
use ide_ssh::Tunnel;
use std::collections::{BTreeMap, HashMap};
@@ -59,242 +54,6 @@ pub async fn disconnect(host: &Host, endpoint: &DockerEndpoint) {
host.ssh.release(id);
}
/// Runs a cancellable docker command (`request` → `cancel_request`) off the async workers.
async fn cancellable<T: Send + 'static>(
host: &Host,
request: RequestId,
f: impl FnOnce(&CancellationToken) -> IdeResult<T> + Send + 'static,
) -> IdeResult<T> {
let cancel = host.begin_request(request);
let result = host.blocking(move || f(&cancel)).await;
host.end_request(request);
result
}
/// Closes the connection's SSH tunnel and, when nothing else uses it, its SSH connection
/// (Services › Disconnect); other endpoints keep nothing open.
#[command(trust = always)]
pub async fn docker_disconnect(host: &Host, endpoint: DockerEndpoint) -> IdeResult<()> {
disconnect(host, &endpoint).await;
Ok(())
}
/// Availability plus containers, images, volumes and networks.
#[command(trust = trusted)]
pub async fn docker_snapshot(host: &Host, endpoint: DockerEndpoint) -> IdeResult<DockerSnapshot> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || Ok(ide_docker::snapshot(&endpoint))).await
}
#[command(trust = trusted)]
pub async fn docker_container_op(
host: &Host,
endpoint: DockerEndpoint,
ids: Vec<String>,
op: ContainerOp,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
}
#[command(trust = trusted)]
pub async fn docker_remove(
host: &Host,
endpoint: DockerEndpoint,
object: DockerObject,
ids: Vec<String>,
force: bool,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::remove(&endpoint, object, &ids, force)).await
}
/// Pretty-printed `docker inspect` JSON.
#[command(trust = trusted)]
pub async fn docker_inspect(
host: &Host,
endpoint: DockerEndpoint,
object: DockerObject,
id: String,
) -> IdeResult<String> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::inspect(&endpoint, object, &id)).await
}
/// Layers of an image (`docker image history`).
#[command(trust = trusted)]
pub async fn docker_image_history(
host: &Host,
endpoint: DockerEndpoint,
id: String,
) -> IdeResult<Vec<DockerImageLayer>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::image_history(&endpoint, &id)).await
}
/// Processes running inside a container (`docker top`).
#[command(trust = trusted)]
pub async fn docker_container_top(host: &Host, endpoint: DockerEndpoint, id: String) -> IdeResult<DockerProcessList> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_top(&endpoint, &id)).await
}
/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`).
#[command(trust = trusted)]
pub async fn docker_container_stats(
host: &Host,
endpoint: DockerEndpoint,
id: String,
) -> IdeResult<DockerContainerStats> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await
}
/// Disk usage per volume name (`docker system df -v`).
#[command(trust = trusted)]
pub async fn docker_volume_sizes(host: &Host, endpoint: DockerEndpoint) -> IdeResult<BTreeMap<String, String>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::volume_sizes(&endpoint)).await
}
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
#[command(trust = trusted)]
#[allow(clippy::too_many_arguments)]
pub async fn docker_logs(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
id: String,
tail: u32,
follow: bool,
timestamps: bool,
on_lines: Channel<Vec<DockerLogLine>>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| {
let _ = on_lines.send(lines);
})
})
.await
}
/// Follows `docker events` until the daemon goes away or the request is cancelled.
#[command(trust = trusted)]
pub async fn docker_events(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
on_event: Channel<DockerEvent>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::watch_events(&endpoint, cancel, &|e| {
let _ = on_event.send(e);
})
})
.await
}
/// `docker pull`, logging in first when a saved registry with a password serves the image.
#[command(trust = trusted)]
pub async fn docker_pull(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
reference: String,
on_output: Channel<String>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
let data_dir = host.data_dir.clone();
cancellable(host, request, move |cancel| {
let auth = ide_docker::auth_for(&data_dir, &reference);
ide_docker::pull(&endpoint, &reference, auth.as_ref(), cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
}
#[command(trust = trusted)]
pub async fn docker_prune(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
target: PruneTarget,
on_output: Channel<String>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::prune(&endpoint, target, cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
}
/// `docker compose` start / stop / restart / down of a project found through labels.
#[command(trust = trusted)]
#[allow(clippy::too_many_arguments)]
pub async fn docker_compose_op(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
project: String,
files: Vec<String>,
working_dir: Option<String>,
op: ComposeOp,
on_output: Channel<String>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::compose_op(&endpoint, &project, &files, working_dir.as_deref(), op, cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
}
/// Docker connections and registries of the project host.
#[command(trust = always)]
pub async fn docker_settings(host: &Host) -> IdeResult<DockerSettings> {
let data_dir = host.data_dir.clone();
host.blocking(move || Ok(ide_docker::load_settings(&data_dir))).await
}
#[command(trust = always)]
pub async fn docker_save_settings(host: &Host, settings: DockerSettings) -> IdeResult<()> {
let data_dir = host.data_dir.clone();
host.blocking(move || ide_docker::save_settings(&data_dir, &settings)).await
}
/// Saves (`None`: forgets) a registry's password.
#[command(trust = always)]
pub async fn docker_set_registry_password(host: &Host, id: String, password: Option<String>) -> IdeResult<()> {
let data_dir = host.data_dir.clone();
host.blocking(move || ide_docker::set_registry_password(&data_dir, &id, password.as_deref())).await
}
/// Test login to `registry` (`password`, else the saved one) through `endpoint`'s daemon.
#[command(trust = trusted)]
pub async fn docker_registry_login(
host: &Host,
endpoint: DockerEndpoint,
registry: DockerRegistry,
password: Option<String>,
) -> IdeResult<String> {
let endpoint = resolve(host, endpoint).await?;
let data_dir = host.data_dir.clone();
host.blocking(move || {
let password = password
.or_else(|| ide_docker::registry_password(&data_dir, &registry.id))
.ok_or_else(|| IdeError::invalid("enter the registry password"))?;
let auth = RegistryAuth { address: registry.address, username: registry.username, password };
ide_docker::login(&endpoint, &auth)
})
.await
}
/// Environment for a Docker run configuration's command line: selects `endpoint`'s
/// daemon and puts the docker executable on `PATH`.
#[command(trust = always)]
@@ -305,25 +64,4 @@ pub async fn docker_run_env(host: &Host, endpoint: DockerEndpoint) -> IdeResult<
host.blocking(move || Ok(ide_docker::run_env(&endpoint))).await
}
ide_command::domain!(
docker:
docker_compose_op,
docker_container_op,
docker_container_stats,
docker_container_top,
docker_disconnect,
docker_events,
docker_image_history,
docker_inspect,
docker_logs,
docker_prune,
docker_pull,
docker_registry_login,
docker_remove,
docker_run_env,
docker_save_settings,
docker_set_registry_password,
docker_settings,
docker_snapshot,
docker_volume_sizes,
);
ide_command::domain!(docker: docker_run_env);
-264
Переглянути файл
@@ -1,264 +0,0 @@
//! Host resource metrics (`host_metrics`, `host_end_process`) for the Remote Host
//! Resources status bar widget and popover dashboard.
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
use ide_workspace::system::SystemSampler;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
#[derive(Default)]
pub(crate) struct HostMetricsSampler {
system: SystemSampler,
cpu: CpuSampler,
}
/// One process outside OpenIDEA's own process tree on the host (read-only in the UI).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostProcess {
pub pid: u32,
pub name: String,
pub cpu_percent: Option<f32>,
pub memory_bytes: Option<u64>,
}
/// Snapshot of host-wide CPU, memory, network, disk and process usage.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostMetrics {
/// Overall CPU utilization across all logical cores (`0..=100`); `null` on the first sample.
pub cpu_percent: Option<f32>,
/// Logical CPU cores available to this host or container.
pub cpu_cores: u32,
/// Unix 1m, 5m, 15m load averages; `null` on Windows.
pub load_average: Option<[f32; 3]>,
/// Host or container memory in use, in bytes.
pub memory_used_bytes: Option<u64>,
/// Total physical (or container limit) memory, in bytes.
pub memory_total_bytes: Option<u64>,
/// Bytes/s received across non-loopback network interfaces; `null` on the first sample or unsupported OS.
pub net_rx_bytes_per_sec: Option<f64>,
/// Bytes/s sent across non-loopback network interfaces; `null` on the first sample or unsupported OS.
pub net_tx_bytes_per_sec: Option<f64>,
/// Bytes/s read from block storage; `null` on the first sample or unsupported OS.
pub disk_read_bytes_per_sec: Option<f64>,
/// Bytes/s written to block storage; `null` on the first sample or unsupported OS.
pub disk_write_bytes_per_sec: Option<f64>,
/// Free bytes available to the user on the project volume (or `$HOME` fallback).
pub disk_available_bytes: Option<u64>,
/// Total capacity in bytes of the project volume (or `$HOME` fallback).
pub disk_total_bytes: Option<u64>,
/// Uptime of the backend process in milliseconds.
pub uptime_ms: f64,
/// OpenIDEA backend, language servers, runs, terminals, debug adapters and agents (`includeProcesses = true`).
pub processes: Vec<ProcessMemory>,
/// Highest-usage processes on the host outside OpenIDEA's own process tree (`includeProcesses = true`).
pub external_processes: Vec<HostProcess>,
}
const MAX_EXTERNAL_PROCESSES: usize = 5;
const MIN_EXTERNAL_CPU_PERCENT: f32 = 0.5;
const MIN_EXTERNAL_MEMORY_BYTES: u64 = 32 << 20;
fn project_name(root: &Path) -> String {
root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string())
}
fn process_root(pid: u32, label: String, kind: &str) -> MemoryRoot {
MemoryRoot { pid, category: MemoryCategory::Process, label, detail: Some(kind.into()), with_children: true }
}
fn volume_path(host: &Host, window: &str) -> PathBuf {
if let Ok(p) = host.project(window) {
return p.root.clone();
}
if let Some(p) = host.projects().into_iter().next() {
return p.root.clone();
}
dirs::home_dir().unwrap_or_else(|| host.data_dir.clone())
}
fn disk_space(path: &Path) -> Option<(u64, u64)> {
#[cfg(unix)]
#[allow(clippy::unnecessary_cast)]
{
let stat = rustix::fs::statvfs(path).ok()?;
let frsize = stat.f_frsize as u64;
let total = (stat.f_blocks as u64).saturating_mul(frsize);
let avail = (stat.f_bavail as u64).saturating_mul(frsize);
(total > 0).then_some((avail.min(total), total))
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64);
// SAFETY: `wide` is NUL-terminated and all three u64 out-pointers are writable.
let ok = unsafe {
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
wide.as_ptr(),
&mut avail,
&mut total,
&mut free,
)
};
(ok != 0 && total > 0).then_some((avail.min(total), total))
}
#[cfg(not(any(unix, windows)))]
{
let _ = path;
None
}
}
fn collect_roots(host: &Host) -> Vec<MemoryRoot> {
let mut roots = Vec::new();
for p in host.projects() {
for s in p.lsp.servers() {
if let Some(pid) = s.pid {
roots.push(MemoryRoot {
pid,
category: MemoryCategory::LanguageServer,
label: s.name,
detail: Some(project_name(s.root.as_ref())),
with_children: true,
});
}
}
}
for r in host.processes.list().into_iter().filter(|r| r.running) {
if let Some(pid) = r.pid {
roots.push(process_root(pid, r.name, "Run"));
}
}
for t in host.terminals.list() {
if let Some(pid) = t.pid {
roots.push(process_root(pid, t.title, "Terminal"));
}
}
roots
}
fn resource_share(p: &HostProcess, cores: u32, total_memory: Option<u64>) -> f64 {
let cpu_share = p.cpu_percent.map(|c| c as f64 / (cores.max(1) as f64 * 100.0)).unwrap_or(0.0);
let mem_share = match (p.memory_bytes, total_memory.filter(|&t| t > 0)) {
(Some(b), Some(t)) => b as f64 / t as f64,
_ => 0.0,
};
cpu_share.max(mem_share)
}
/// Snapshot of host-wide resource counters (CPU, memory, network, disk) and, when
/// `include_processes` is true, the process breakdown of OpenIDEA and top host processes.
#[command(trust = always)]
pub async fn host_metrics(host: &Arc<Host>, window: &str, include_processes: bool) -> IdeResult<HostMetrics> {
let disk_target = volume_path(host, window);
let roots = if include_processes { collect_roots(host) } else { Vec::new() };
let h = host.clone();
host.blocking(move || {
let table = include_processes.then(ProcessTable::snapshot);
let (disk_available_bytes, disk_total_bytes) = match disk_space(&disk_target) {
Some((a, t)) => (Some(a), Some(t)),
None => (None, None),
};
let uptime_ms =
ide_workspace::process::process_age().unwrap_or_else(ide_workspace::process::uptime).as_secs_f64() * 1000.0;
let mut sampler = h.metrics_sampler.lock();
let rates = sampler.system.sample();
let (processes, external_processes) = if let Some(table) = table {
sampler.cpu.retain(&table);
let me = std::process::id();
let processes =
memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| sampler.cpu.percent(pid));
let claimed: HashSet<u32> = table.tree(me).into_iter().collect();
let mut external: Vec<HostProcess> = table
.entries()
.filter(|e| e.pid != 0 && !claimed.contains(&e.pid))
.filter_map(|e| {
let cpu_percent = sampler.cpu.percent(e.pid);
let memory_bytes = memory::fast_resident_bytes(e.pid);
let active = cpu_percent.unwrap_or(0.0) >= MIN_EXTERNAL_CPU_PERCENT
|| memory_bytes.unwrap_or(0) >= MIN_EXTERNAL_MEMORY_BYTES;
active.then(|| HostProcess { pid: e.pid, name: e.name.clone(), cpu_percent, memory_bytes })
})
.collect();
external.sort_by(|a, b| {
resource_share(b, rates.cpu_cores, rates.memory_total_bytes)
.total_cmp(&resource_share(a, rates.cpu_cores, rates.memory_total_bytes))
.then_with(|| b.memory_bytes.unwrap_or(0).cmp(&a.memory_bytes.unwrap_or(0)))
.then_with(|| a.pid.cmp(&b.pid))
});
external.truncate(MAX_EXTERNAL_PROCESSES);
(processes, external)
} else {
(Vec::new(), Vec::new())
};
Ok(HostMetrics {
cpu_percent: rates.cpu_percent,
cpu_cores: rates.cpu_cores,
load_average: rates.load_average,
memory_used_bytes: rates.memory_used_bytes,
memory_total_bytes: rates.memory_total_bytes,
net_rx_bytes_per_sec: rates.net_rx_bytes_per_sec,
net_tx_bytes_per_sec: rates.net_tx_bytes_per_sec,
disk_read_bytes_per_sec: rates.disk_read_bytes_per_sec,
disk_write_bytes_per_sec: rates.disk_write_bytes_per_sec,
disk_available_bytes,
disk_total_bytes,
uptime_ms,
processes,
external_processes,
})
})
.await
}
/// Ends a child process started by this OpenIDEA host (language server, run, terminal,
/// debug adapter or agent) and its descendants; refuses processes outside this host's tree.
#[command(trust = trusted)]
pub async fn host_end_process(host: &Arc<Host>, pid: u32) -> IdeResult<bool> {
host.blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, Duration::from_secs(3)))).await
}
ide_command::domain!(host_metrics: host_metrics, host_end_process);
#[cfg(test)]
mod tests {
use super::*;
use crate::HostConfig;
#[tokio::test]
async fn collects_light_and_detailed_host_metrics() {
let dir = tempfile::tempdir().unwrap();
let host = Arc::new(Host::new(HostConfig::for_test(dir.path())));
let light = host_metrics(&host, "main", false).await.unwrap();
assert!(light.cpu_cores >= 1);
assert!(light.processes.is_empty());
assert!(light.external_processes.is_empty());
if cfg!(any(unix, windows)) {
let avail = light.disk_available_bytes.expect("disk_available_bytes");
let total = light.disk_total_bytes.expect("disk_total_bytes");
assert!(total > 0 && avail <= total, "{avail} / {total}");
}
let detailed = host_metrics(&host, "main", true).await.unwrap();
assert!(!detailed.processes.is_empty());
assert_eq!(detailed.processes[0].label, "Backend");
assert!(detailed.external_processes.len() <= MAX_EXTERNAL_PROCESSES);
// Refuses to terminate the backend itself or PID 1.
assert!(!host_end_process(&host, std::process::id()).await.unwrap());
assert!(!host_end_process(&host, 1).await.unwrap());
}
}
-24
Переглянути файл
@@ -1881,29 +1881,6 @@ pub async fn lsp_snapshot_diagnostics(
result
}
#[command(trust = trusted)]
pub async fn lsp_snapshot_completion(
host: &Host,
window: &str,
path: std::path::PathBuf,
text: String,
pos: Pos,
request: RequestId,
) -> IdeResult<Vec<CompletionItem>> {
let project = host.project(window)?;
if !path.is_absolute() || path.file_name().is_none() {
return Err(IdeError::invalid("a text snapshot requires a file path"));
}
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
return Ok(Vec::new());
}
let language = project.documents.language_of(&path, text.lines().next()).language;
let cancel = host.begin_project_read_request(window, request);
let result = project.lsp.snapshot_completion(&path, &language, &text, pos, &cancel).await;
host.end_request(request);
result
}
#[command(trust = trusted)]
pub async fn lsp_inlay_hints(host: &Host, window: &str, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
let lsp = host.project(window)?.lsp.clone();
@@ -3259,7 +3236,6 @@ ide_command::domain!(
lsp_extract_interface_info,
lsp_format,
lsp_format_text,
lsp_snapshot_completion,
lsp_snapshot_diagnostics,
lsp_source_action_text,
lsp_goto,
-3
Переглянути файл
@@ -19,7 +19,6 @@ pub mod flutter;
pub mod fs;
pub mod heap;
pub mod history;
pub mod host_metrics;
pub mod http;
pub mod java;
pub mod jvm_icons;
@@ -28,7 +27,6 @@ pub mod maven_placeholder;
pub mod nav;
pub mod notebook;
pub mod project;
pub mod pytest_fixtures;
mod python;
pub mod python_stubs;
pub mod refactor;
@@ -95,7 +93,6 @@ ide_command::domains!(
fs: crate::ops::fs,
heap: crate::ops::heap,
history: crate::ops::history,
host_metrics: crate::ops::host_metrics,
http: crate::ops::http,
java: crate::ops::java,
jvm_icons: crate::ops::jvm_icons,
-19
Переглянути файл
@@ -1,5 +1,4 @@
use super::blocking;
use super::pytest_fixtures::{PytestFixtureAt, fixture_at};
use super::python_stubs::{
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
};
@@ -479,23 +478,6 @@ pub async fn nav_python_stubs(host: &Host, window: &str, doc: DocId) -> IdeResul
.await
}
/// pytest fixtures at `pos` of a Python document: the definition pytest uses for the fixture
/// named there (a test's parameter, a `usefixtures` / `getfixturevalue` string), and the
/// fixtures visible where a fixture name goes, for completion.
#[command(trust = always)]
pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeResult<PytestFixtureAt> {
let project = host.project(window)?;
let syntax = host.syntax();
blocking(move || {
let snap = project.documents.snapshot(doc)?;
if snap.large || snap.language.as_str() != "python" {
return Ok(Default::default());
}
Ok(fixture_at(&project, &syntax, &snap.path, &snap.text, pos))
})
.await
}
ide_command::domain!(
nav:
find_dirs,
@@ -509,7 +491,6 @@ ide_command::domain!(
mark_recent,
nav_index_definitions,
nav_inheritance,
nav_pytest_fixtures,
nav_python_stubs,
nav_resolve_module,
path_completions,
+11 -70
Переглянути файл
@@ -110,22 +110,6 @@ 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.
@@ -138,7 +122,17 @@ pub fn settings_set(
value: String,
) -> IdeResult<Settings> {
let applied = set_settings(host, window, scope, &key, &value)?;
apply_setting(host, window, &key);
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);
}
let sink = host.window_sink(window);
sink.emit(IdeEvent::SettingsChanged { key });
if let Some(root) = applied.roots_changed {
@@ -454,14 +448,6 @@ 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() {
@@ -538,56 +524,11 @@ 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,
-255
Переглянути файл
@@ -1,255 +0,0 @@
//! pytest fixtures across files: the modules a test file sees, nearest first (the file, its
//! `conftest.py` files up to the project root, the modules `pytest_plugins` names, installed
//! plugins' `pytest11` entry points, pytest's own `_pytest` package), for Go to Declaration
//! and completion of fixture names.
use super::python_stubs::site_packages;
use crate::Project;
use ide_core::{IpcPath, LanguageId, Location, Pos, Range};
use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::SystemTime;
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PytestFixtureAt {
/// The fixture name at the position, and the definition pytest uses for it.
pub reference: Option<PytestFixtureReference>,
/// At a place a fixture name goes (a test's parameters, a `usefixtures` string): the
/// fixtures visible there, nearest first.
pub completions: Option<Vec<PytestFixtureItem>>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PytestFixtureReference {
pub name: String,
pub range: Range,
/// None when no visible module defines it (`request`, a fixture from a hook).
pub definition: Option<Location>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PytestFixtureItem {
pub name: String,
/// The file defining it.
pub path: IpcPath,
}
/// Fixtures at `pos` of the Python document `path` / `text`.
pub(crate) fn fixture_at(project: &Project, syntax: &Syntax, path: &Path, text: &str, pos: Pos) -> PytestFixtureAt {
let own = syntax.pytest_module(&python(), text);
let usage = own.use_at(pos).cloned();
let slot = own.slot_at(pos).cloned();
if usage.is_none() && slot.is_none() {
return PytestFixtureAt::default();
}
let layers = layers(project, syntax, path, Arc::new(own));
let modules: Vec<&PytestModule> = layers.iter().map(|(_, m)| m.as_ref()).collect();
let reference = usage.map(|u| {
let found = resolve_fixture(&modules, &u.name, u.class.as_deref(), u.in_fixture.as_deref() == Some(&u.name));
PytestFixtureReference {
definition: found.map(|(l, f)| Location {
path: IpcPath::from(layers[l].0.clone()),
range: modules[l].fixtures[f].selection,
uri: None,
}),
name: u.name,
range: u.range,
}
});
let completions = slot.map(|s| {
visible_fixtures(&modules, s.class.as_deref())
.into_iter()
// `_name` fixtures are internal, as `pytest --fixtures` hides them.
.filter(|&(l, f)| !modules[l].fixtures[f].name.starts_with('_'))
.map(|(l, f)| PytestFixtureItem {
name: modules[l].fixtures[f].name.clone(),
path: IpcPath::from(layers[l].0.clone()),
})
.collect()
});
PytestFixtureAt { reference, completions }
}
fn python() -> LanguageId {
LanguageId::new("python")
}
type Layer = (PathBuf, Arc<PytestModule>);
/// The modules `path` sees, nearest first, `own` being its own.
fn layers(project: &Project, syntax: &Syntax, path: &Path, own: Arc<PytestModule>) -> Vec<Layer> {
let mut out: Vec<Layer> = vec![(path.to_path_buf(), own)];
// conftest.py files from the file's folder up to the project root.
let mut dir = path.parent();
while let Some(d) = dir.filter(|d| d.starts_with(&project.root)) {
let conftest = d.join("conftest.py");
if conftest != path
&& let Some(m) = module_of(project, syntax, &conftest)
{
out.push((conftest, m));
}
dir = d.parent();
}
let packages = interpreter_site_packages(project);
let mut search = super::python::paths(project);
search.extend(packages.iter().cloned());
// `pytest_plugins = ["pytester"]` names pytest's own optional plugins by their short name.
search.extend(packages.iter().map(|p| p.join("_pytest")));
// Modules named by `pytest_plugins` in those files.
let named: Vec<String> = out.iter().flat_map(|(_, m)| m.plugins.clone()).collect();
let mut extra: Vec<PathBuf> = named.iter().filter_map(|module| module_file(module, &search)).collect();
// Installed plugins, then pytest's own fixtures.
for packages in &packages {
extra.extend(
entry_point_modules(packages).iter().filter_map(|m| module_file(m, std::slice::from_ref(packages))),
);
}
for packages in &packages {
extra.extend(builtin_modules(&packages.join("_pytest")));
}
for file in extra {
if !out.iter().any(|(p, _)| *p == file)
&& let Some(m) = module_of(project, syntax, &file)
{
out.push((file, m));
}
}
out
}
/// The `site-packages` of the project's interpreter: its virtualenv's, else its install prefix's.
fn interpreter_site_packages(project: &Project) -> Vec<PathBuf> {
let settings = project.settings.effective();
let Some(python) = ide_sdk::apply::python_interpreter(&project.root, &settings) else { return Vec::new() };
let prefix = ide_sdk::venv_of(&python).or_else(|| python.parent()?.parent().map(Path::to_path_buf));
prefix.map(|p| site_packages(&p)).unwrap_or_default()
}
/// `pkg.mod` → `pkg/mod.py` or `pkg/mod/__init__.py` in the first folder that has it.
fn module_file(module: &str, search: &[PathBuf]) -> Option<PathBuf> {
let rel: PathBuf = module.split('.').collect();
search.iter().find_map(|base| {
let file = base.join(&rel).with_extension("py");
let package = base.join(&rel).join("__init__.py");
[file, package].into_iter().find(|p| p.is_file())
})
}
/// The modules of the `[pytest11]` entry points of the distributions in `site_packages`.
fn entry_point_modules(site_packages: &Path) -> Vec<String> {
let Ok(entries) = std::fs::read_dir(site_packages) else { return Vec::new() };
let mut out = Vec::new();
for entry in entries.flatten() {
if !entry.file_name().to_string_lossy().ends_with(".dist-info") {
continue;
}
let Ok(text) = std::fs::read_to_string(entry.path().join("entry_points.txt")) else { continue };
out.extend(pytest11_modules(&text));
}
out.sort();
out
}
/// The modules of the `[pytest11]` section of an `entry_points.txt` (`name = module:attr`).
fn pytest11_modules(text: &str) -> Vec<String> {
let mut section = "";
let mut out = Vec::new();
for line in text.lines().map(str::trim) {
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
section = name;
} else if section == "pytest11"
&& let Some((_, value)) = line.split_once('=')
{
let module = value.trim().split(':').next().unwrap_or_default().trim();
if !module.is_empty() {
out.push(module.to_owned());
}
}
}
out
}
/// pytest's own plugins that are off unless `pytest_plugins` names them.
const OPTIONAL_BUILTINS: [&str; 2] = ["pytester.py", "pytester_assertions.py"];
/// pytest's own modules that may define fixtures: `_pytest/*.py`, one level of subpackages.
fn builtin_modules(dir: &Path) -> Vec<PathBuf> {
let mut out = Vec::new();
let Ok(entries) = std::fs::read_dir(dir) else { return out };
for entry in entries.flatten() {
let path = entry.path();
if OPTIONAL_BUILTINS.iter().any(|name| entry.file_name() == *name) {
continue;
}
if path.extension().is_some_and(|e| e == "py") {
out.push(path);
} else if path.is_dir() {
out.extend(
std::fs::read_dir(&path)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "py")),
);
}
}
out.sort();
out
}
/// A parsed file and the modification time and length it was read at.
type Cached = (SystemTime, u64, Arc<PytestModule>);
/// The fixtures of a file: from its open editor, else from disk, parsed once per modification.
fn module_of(project: &Project, syntax: &Syntax, path: &Path) -> Option<Arc<PytestModule>> {
if let Some(text) = project.documents.text_of(path) {
return Some(Arc::new(syntax.pytest_module(&python(), &text)));
}
static CACHE: LazyLock<Mutex<HashMap<PathBuf, Cached>>> = LazyLock::new(Default::default);
let meta = std::fs::metadata(path).ok().filter(|m| m.is_file())?;
if meta.len() > ide_vfs::LARGE_FILE_THRESHOLD {
return None;
}
let stamp = (meta.modified().ok()?, meta.len());
if let Some((time, len, m)) = CACHE.lock().ok()?.get(path)
&& (*time, *len) == stamp
{
return Some(m.clone());
}
let text = std::fs::read_to_string(path).ok()?;
let module = Arc::new(syntax.pytest_module(&python(), &ide_text::normalize_line_endings(&text)));
CACHE.lock().ok()?.insert(path.to_path_buf(), (stamp.0, stamp.1, module.clone()));
Some(module)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_pytest11_entry_points() {
let text =
"[console_scripts]\nx = a:b\n\n[pytest11]\nmock = pytest_mock\nasyncio = pytest_asyncio.plugin:main\n";
assert_eq!(pytest11_modules(text), ["pytest_mock", "pytest_asyncio.plugin"]);
}
#[test]
fn finds_module_files_and_packages() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("pkg/sub")).unwrap();
std::fs::write(dir.path().join("pkg/fixtures.py"), "").unwrap();
std::fs::write(dir.path().join("pkg/sub/__init__.py"), "").unwrap();
let search = [dir.path().to_path_buf()];
assert_eq!(module_file("pkg.fixtures", &search), Some(dir.path().join("pkg/fixtures.py")));
assert_eq!(module_file("pkg.sub", &search), Some(dir.path().join("pkg/sub/__init__.py")));
assert_eq!(module_file("pkg.none", &search), None);
}
}
+57 -173
Переглянути файл
@@ -6,9 +6,8 @@ use ide_command::command;
use ide_core::{FileEdit, IdeResult, RequestId, WorkspaceEdit};
use ide_language::Syntax;
use ide_lsp::types::FileRenameEdits;
use ide_workspace::Documents;
use ide_workspace::file_moves::{moved_path, read_text};
use ide_workspace::roots::{PYTHON_FILES, ProjectRoots, RootKind, SourceFolder};
use ide_workspace::file_moves::moved_path;
use ide_workspace::roots::{ProjectRoots, RootKind};
use ide_workspace::{FileMove, UndoOutcome};
use parking_lot::Mutex;
use std::path::{Path, PathBuf};
@@ -19,8 +18,7 @@ fn pairs(moves: &[FileMove]) -> Vec<(PathBuf, PathBuf)> {
moves.iter().map(|m| (m.from.to_path_buf(), m.to.to_path_buf())).collect()
}
/// `workspace/willRenameFiles` on every interested server (before the move), plus the
/// Python import updates the IDE makes itself. Cancellable.
/// `workspace/willRenameFiles` on every interested server (before the move). Cancellable.
#[command(trust = always)]
pub async fn refactor_file_move_edits(
host: &Host,
@@ -30,72 +28,46 @@ pub async fn refactor_file_move_edits(
) -> IdeResult<FileRenameEdits> {
let project = host.project(window)?;
let token = host.begin_request(request);
let syntax = host.syntax();
let result = async {
let mut result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await?;
blocking(move || {
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
let python = python_import_edits(
&project.root,
&project.roots(),
&project.exclude_globs(),
&project.documents,
&syntax,
&moves,
&|| token.is_cancelled(),
);
result.edit.files.extend(python.files);
}
if token.is_cancelled() {
return Err(ide_core::IdeError::cancelled());
}
project.documents.prepare_workspace_edit(&mut result.edit)?;
Ok(result)
})
.await
}
.await;
let result = project.lsp.will_rename_files(&pairs(&moves), token.clone()).await;
host.end_request(request);
result
let mut result = result?;
let syntax = host.syntax();
blocking(move || {
// basedpyright has no `workspace/willRenameFiles`; a Python server that answered wins.
if !result.edit.files.iter().any(|f| matches!(f, FileEdit::Edit { path, .. } if is_python(path))) {
let python = python_import_edits(&project, &syntax, &moves, &|| token.is_cancelled());
result.edit.files.extend(python.files);
}
project.documents.prepare_workspace_edit(&mut result.edit)?;
Ok(result)
})
.await
}
fn is_python(path: &Path) -> bool {
path.extension().is_some_and(|e| e == "py" || e == "pyi")
}
/// The folders Python imports modules from: source and test roots of Python projects (or marked
/// by the user), else the project root. Other languages' roots (`frontend/src`) don't count.
fn python_root<'a>(roots: &'a ProjectRoots, rel: &str) -> &'a str {
let python = |r: &&SourceFolder| {
matches!(r.kind, RootKind::Source | RootKind::Test)
&& r.detected_from.as_deref().is_none_or(|f| PYTHON_FILES.iter().any(|p| f.rsplit('/').next() == Some(*p)))
};
let inside = |r: &&SourceFolder| r.path.is_empty() || rel == r.path || rel.starts_with(&format!("{}/", r.path));
roots.roots.iter().filter(python).filter(inside).max_by_key(|r| r.path.len()).map_or("", |r| r.path.as_str())
}
fn rel_path(root: &Path, path: &Path) -> Option<String> {
Some(path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/"))
}
/// The dotted name of a Python module file or package folder and the root it is imported from
/// (`src/a/b.py` → `a.b` from `src` in a `src` layout).
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<(String, String)> {
let rel = rel_path(root, path)?;
let base = python_root(roots, &rel);
/// The dotted name of a Python module file or package folder, from its project's Python roots
/// (`src/a/b.py` → `a.b` in a `src` layout).
fn python_module(root: &Path, roots: &ProjectRoots, path: &Path, is_dir: bool) -> Option<String> {
let rel = path.strip_prefix(root).ok()?.to_string_lossy().replace('\\', "/");
let base = roots
.root_for(&rel)
.filter(|r| matches!(r.kind, RootKind::Source | RootKind::Test))
.map_or("", |r| r.path.as_str());
let inner = if base.is_empty() { rel.as_str() } else { rel.strip_prefix(base)?.trim_start_matches('/') };
let inner = if is_dir { inner } else { inner.strip_suffix(".py").or_else(|| inner.strip_suffix(".pyi"))? };
let inner = inner.strip_suffix("/__init__").unwrap_or(inner);
let valid = |s: &str| {
s.chars().next().is_some_and(|c| !c.is_ascii_digit()) && s.chars().all(|c| c == '_' || c.is_alphanumeric())
};
(!inner.is_empty() && inner.split('/').all(valid)).then(|| (inner.replace('/', "."), base.to_owned()))
(!inner.is_empty() && inner.split('/').all(valid)).then(|| inner.replace('/', "."))
}
/// The package relative imports in `file` start from.
fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
let Some((module, _)) = python_module(root, roots, file, false) else { return String::new() };
let Some(module) = python_module(root, roots, file, false) else { return String::new() };
if file.file_stem().is_some_and(|s| s == "__init__") {
module
} else {
@@ -103,91 +75,52 @@ fn python_package(root: &Path, roots: &ProjectRoots, file: &Path) -> String {
}
}
/// Whether `dir` holds Python modules (a package or namespace package), at any depth.
fn has_python(dir: &Path) -> bool {
let Ok(entries) = std::fs::read_dir(dir) else { return false };
entries.flatten().any(|e| {
let path = e.path();
let name = e.file_name();
let name = name.to_string_lossy();
if e.file_type().is_ok_and(|t| t.is_dir()) {
!name.starts_with('.') && !matches!(name.as_ref(), "node_modules" | "__pycache__") && has_python(&path)
} else {
is_python(&path)
}
})
}
/// Import updates in the project's Python files for `moves` (paths before the move).
fn python_import_edits(
root: &Path,
roots: &ProjectRoots,
excludes: &[String],
documents: &Documents,
project: &crate::project::Project,
syntax: &Syntax,
moves: &[FileMove],
cancelled: &(dyn Fn() -> bool + Sync),
) -> WorkspaceEdit {
// (old, new, root the old module is imported from)
let mut renames: Vec<(String, String, String)> = Vec::new();
for m in moves {
let is_dir = m.from.is_dir();
let module = if is_dir {
has_python(&m.from)
} else {
let stub_only = m.from.extension().is_some_and(|e| e == "pyi")
&& !moves.iter().any(|o| *o.from == m.from.with_extension("py"));
// A stub may describe a compiled module that stays where it is.
is_python(&m.from) && !stub_only && m.from.file_stem().is_some_and(|s| s != "__init__")
};
if !module {
continue;
}
let (Some((old, base)), Some((new, _))) =
(python_module(root, roots, &m.from, is_dir), python_module(root, roots, &m.to, is_dir))
else {
continue;
};
if old != new && !renames.iter().any(|r| r.0 == old) {
renames.push((old, new, base));
}
}
let root = &project.root;
let roots = project.roots();
let renames: Vec<(String, String)> = moves
.iter()
.filter_map(|m| {
let is_dir = m.from.is_dir();
if !is_dir && (!is_python(&m.from) || m.from.file_stem().is_some_and(|s| s == "__init__")) {
return None;
}
let old = python_module(root, &roots, &m.from, is_dir)?;
let new = python_module(root, &roots, &m.to, is_dir)?;
(old != new).then_some((old, new))
})
.collect();
if renames.is_empty() {
return WorkspaceEdit::default();
}
// `import utils` in `backend/app.py` means `backend/utils.py`, not `backend/tests/utils.py`.
let shadowed = |base: &str, module: &str| {
let p = root.join(base).join(module.replace('.', "/"));
p.with_extension("py").is_file() || p.with_extension("pyi").is_file() || p.is_dir()
};
let names: Vec<&str> = renames.iter().map(|(old, ..)| old.rsplit('.').next().unwrap_or(old)).collect();
let names: Vec<&str> = renames.iter().map(|(old, _)| old.rsplit('.').next().unwrap_or(old)).collect();
let found: Mutex<Vec<(PathBuf, Vec<ide_core::TextEdit>)>> = Mutex::new(Vec::new());
ide_vfs::walk_files(root, excludes, |path| {
ide_vfs::walk_files(root, &project.exclude_globs(), |path| {
if cancelled() || !is_python(path) {
return;
}
let moved = moved_path(path, moves);
if moved == path {
let Ok(bytes) = std::fs::read(path) else { return };
let raw = String::from_utf8_lossy(&bytes);
if !names.iter().any(|n| raw.contains(n)) {
return;
}
let text = match project.documents.text_of(path) {
Some(t) => t,
None => match std::fs::read_to_string(path) {
Ok(t) => t,
Err(_) => return,
},
};
if moved == path && !names.iter().any(|n| text.contains(n)) {
return;
}
// Through the documents layer: unsaved edits, BOM and encodings as the edits will see them.
let Ok(text) = read_text(documents, path) else { return };
let Some(rel) = rel_path(root, path) else { return };
let base = python_root(roots, &rel);
let visible: Vec<(String, String)> = renames
.iter()
.filter(|(old, _, from)| from == base || !shadowed(base, old))
.map(|(old, new, _)| (old.clone(), new.clone()))
.collect();
let edits = syntax.python_import_edits(
&text,
&python_package(root, roots, path),
&python_package(root, roots, &moved),
&visible,
&python_package(root, &roots, path),
&python_package(root, &roots, &moved),
&renames,
);
if !edits.is_empty() {
found.lock().push((path.to_path_buf(), edits));
@@ -280,6 +213,7 @@ ide_command::domain!(
#[cfg(test)]
mod tests {
use super::*;
use ide_workspace::roots::SourceFolder;
#[test]
fn python_module_names_follow_the_roots() {
@@ -289,7 +223,7 @@ mod tests {
vec![folder("src", RootKind::Source), folder("tests", RootKind::Test)],
&Default::default(),
);
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir).map(|(m, _)| m);
let name = |p: &str, dir| python_module(root, &roots, &root.join(p), dir);
assert_eq!(name("src/tasks/models.py", false).as_deref(), Some("tasks.models"));
assert_eq!(name("src/tasks/__init__.py", false).as_deref(), Some("tasks"));
assert_eq!(name("src/tasks", true).as_deref(), Some("tasks"));
@@ -300,54 +234,4 @@ mod tests {
assert_eq!(python_package(root, &roots, &root.join("src/tasks/cli.py")), "tasks");
assert_eq!(python_package(root, &roots, &root.join("src/tasks/__init__.py")), "tasks");
}
#[test]
fn python_imports_in_a_mixed_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let write = |p: &str, text: &str| {
let path = root.join(p);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
};
write("backend/pyproject.toml", "[project]\nname = \"b\"\n");
write("backend/utils.py", "");
write("backend/app.py", "import utils\nfrom api import routes\n");
write("backend/api/__init__.py", "");
write("backend/api/routes.py", "");
write("backend/bom.py", "\u{feff}from api import routes\n");
write("backend/tests/utils.py", "");
write("backend/tests/test_a.py", "import utils\n");
write("backend/native/_ext.pyi", "");
write("backend/uses_ext.py", "from native import _ext\n");
write("frontend/package.json", "{}");
write("frontend/src/api/index.js", "");
let roots = ProjectRoots::compute(ide_workspace::roots::detect(root), &Default::default());
let documents = Documents::new(
std::sync::Arc::new(|_| {}),
Box::new(|_: &Path, _: Option<&str>| ide_core::LanguageId::new("python")),
);
let edits = |from: &str, to: &str| {
let moves = vec![FileMove { from: root.join(from).into(), to: root.join(to).into() }];
let edit = python_import_edits(root, &roots, &[], &documents, &Syntax::new(), &moves, &|| false);
edit.files
.into_iter()
.filter_map(|f| match f {
FileEdit::Edit { path, edits, .. } => Some((rel_path(root, &path).unwrap(), edits)),
_ => None,
})
.collect::<Vec<_>>()
};
// Not Python: a JavaScript folder of the same name.
assert!(edits("frontend/src/api", "frontend/src/client").is_empty());
// Same-named modules of different roots.
let files = edits("backend/tests/utils.py", "backend/tests/helpers.py");
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/tests/test_a.py"]);
// A BOM doesn't shift the edit.
let files = edits("backend/api", "backend/web");
assert_eq!(files.iter().map(|f| f.0.as_str()).collect::<Vec<_>>(), ["backend/app.py", "backend/bom.py"]);
assert_eq!(files[1].1[0].range.start, ide_core::Pos { line: 0, col: 5 });
// A stub without its module.
assert!(edits("backend/native/_ext.pyi", "backend/native/_ext2.pyi").is_empty());
}
}
+1 -10
Переглянути файл
@@ -334,19 +334,10 @@ pub async fn run_start(
Some(agent) => agent.wrap_output(on_output),
None => on_output,
};
// `execute_run_configuration` asked the Run tool window to start it.
let mcp = crate::mcp::run::configs::config_run_launch(&config);
let on_output = match &mcp {
Some(mcp) => mcp.wrap_output(on_output),
None => on_output,
};
let result = start_inner(host, window, config, on_output, agent.as_ref(), &cancel).await;
if let Some(agent) = &agent {
agent.started(&result);
}
if let Some(mcp) = &mcp {
mcp.started(&result);
}
if let Some(id) = request {
host.end_request(id);
}
@@ -502,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" | "unittest" | "doctest" | "django-test");
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "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));
+2 -2
Переглянути файл
@@ -110,8 +110,8 @@ pub(crate) fn search_project(
_ => true,
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
// 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 defaults = project.documents.file_defaults();
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
+1 -1
Переглянути файл
@@ -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", "mdx", "restructuredtext", "asciidoc", "latex"];
const PROSE: &[&str] = &["plaintext", "markdown", "restructuredtext", "asciidoc", "latex"];
/// Custom dictionary paths: `~/…` from home, relative ones from the project root.
fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
+3 -7
Переглянути файл
@@ -29,19 +29,15 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
&root,
&settings,
));
// Godot and GitHub CLI can live in app bundles / MSI / Snap folders outside the search path.
let mut found: std::collections::BTreeMap<_, _> =
ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p)).into_iter().collect();
if let Some(gh) = ide_core::tool_path::find_gh_outside_search_path() {
found.insert("gh".to_owned(), gh);
}
// Godot is usually an app bundle / Flatpak outside the search path.
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
Ok(Tools::new(&data)
.with_downloads(settings.tool_downloads.clone())
.with_runtime(runtime.commands, runtime.env)
.with_custom_paths(custom)
.with_found_paths(found)
.with_found_paths(found.into_iter().collect())
.with_work_dir(work_dir))
}
+15 -157
Переглянути файл
@@ -211,10 +211,6 @@ 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);
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
// 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
@@ -364,13 +360,8 @@ impl Host {
}
{
let settings = settings.clone();
let data_dir = self.local_data_dir.clone();
lsp.set_servers_hook(Box::new(move |language, defined| {
let mut servers = ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective());
if language.as_str() == "css" && ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit").is_none() {
ide_sdk::apply::drop_css_modules_route(&mut servers);
}
servers
ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective())
}));
}
{
@@ -461,9 +452,7 @@ 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))
|| ts_config_changed(changed.iter().chain(&batch.removed))
{
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
lsp.reconfigure_soon();
}
// Not while loading: a first `use flake` may write `flake.lock` itself.
@@ -773,12 +762,6 @@ 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)
}
@@ -1051,8 +1034,9 @@ fn db_sources_watch(
let Some(db) = weak.upgrade() else { return };
let sink = sink.clone();
runtime.spawn(async move {
db.reconcile_sources().await;
sink.emit(IdeEvent::DbSourcesChanged);
if db.reconcile_sources().await {
sink.emit(IdeEvent::DbSourcesChanged);
}
});
}))
.inspect_err(|e| tracing::warn!("{}", e.message))
@@ -1540,7 +1524,8 @@ impl Project {
}
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
let charset = self.documents.detect_encoding(path, bytes);
let defaults = self.documents.file_defaults();
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
self.vcs_text_encoding(path, charset)
}
@@ -1899,9 +1884,7 @@ 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))
|| ts_config_changed(changed.iter().chain(&batch.removed))
{
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
lsp.reconfigure_soon();
}
if let Some(bridge) = &kotlin_bridge {
@@ -1923,17 +1906,6 @@ 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 {
@@ -2043,9 +2015,7 @@ 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`);
/// their `detected_from` owner keeps its leading `/` or drive (`<project>/Gradle`) so
/// module lists still address them as absolute paths.
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`).
fn with_gradle_roots(
root: &Path,
build_cache: &Path,
@@ -2069,22 +2039,12 @@ 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 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);
// UI still finds the module after a sync. Projects outside the root stay `Gradle`:
// the UI reads the folder as project-relative.
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) });
@@ -2532,109 +2492,18 @@ 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 keeps its absolute owner so module lists still address it.
// A project outside the root is not a module the UI could address.
assert_eq!(
got,
[
("src/it/java".into(), RootKind::Test, Some("Gradle")),
(abs(svc.join("src/main/java")), RootKind::Source, Some(owner.as_str())),
(abs(svc.join("build")), RootKind::Excluded, Some(owner.as_str())),
(abs(svc.join("src/main/java")), RootKind::Source, Some("Gradle")),
(abs(svc.join("build")), RootKind::Excluded, Some("Gradle")),
("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)]
@@ -2759,20 +2628,9 @@ mod agent_worktree_tests {
#[cfg(test)]
mod composer_tests {
use super::{composer_changed, ts_config_changed};
use super::composer_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");
-7
Переглянути файл
@@ -282,18 +282,11 @@ 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();
+13 -81
Переглянути файл
@@ -1,4 +1,4 @@
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation, Imports) as the TypeScript
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) 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,7 +48,12 @@ 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);
layer.insert(language.into(), Value::Object(section));
if !section.is_empty() {
layer.insert(language.into(), Value::Object(section));
}
}
if layer.is_empty() {
return;
}
let mut merged = Value::Object(layer);
if let Some(own) = cfg.settings.take() {
@@ -91,30 +96,10 @@ fn section(
if !format.is_empty() {
section.insert("format".into(), Value::Object(format));
}
// vtsls reads VS Code's names (`quoteStyle`, `importModuleSpecifier`), typescript-language-server
// tsserver's (`quotePreference`, `importModuleSpecifierPreference`).
let mut preferences = Map::new();
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
if let Some(quotes) = quotes {
preferences.insert("quoteStyle".into(), json!(quotes));
preferences.insert("quotePreference".into(), json!(quotes));
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": 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
}
@@ -148,17 +133,9 @@ mod tests {
"typescript": {
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
// The server's own settings win.
"preferences": {
"quoteStyle": "double",
"quotePreference": "single",
"autoImportFileExcludePatterns": [],
"autoImportSpecifierExcludeRegexes": [],
},
},
"javascript": {
"format": { "semicolons": "insert" },
"preferences": { "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] },
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
},
"javascript": { "format": { "semicolons": "insert" } },
})
);
@@ -167,52 +144,7 @@ mod tests {
assert_eq!(eslint.settings, None);
let mut untouched = server("vtsls");
configure(&mut untouched, dir.path(), &Settings::default());
// 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": [],
} },
})
);
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
}
#[test]
@@ -246,6 +178,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["javascript"].get("format"), None);
assert_eq!(s.get("javascript"), None);
}
}
+1 -14
Переглянути файл
@@ -9,15 +9,12 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(common::host_config(base)));
let root = base.join("data/consoles/db/pg");
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
};
assert!(db::db_consoles(&host, "pg".into(), false).unwrap().is_empty());
// The first new console is the default one, then console_1, console_2…
let first = db::db_consoles(&host, "pg".into(), true).unwrap();
assert_eq!(names(first.clone()), ["console.sql"]);
assert_eq!(first[0].0, root.join("console.sql"));
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql"]);
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql", "console_1.sql"]);
let all = db::db_consoles(&host, "pg".into(), true).unwrap();
assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]);
@@ -29,13 +26,3 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
assert!(db::db_consoles(&host, "pg:other".into(), false).unwrap().is_empty());
assert!(db::db_consoles(&host, "../x".into(), true).is_err());
}
#[tokio::test]
async fn consoles_root_is_the_directory_listed_in_the_project_view() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(common::host_config(base)));
let root = db::db_consoles_dir(&host).unwrap();
assert_eq!(root.0, base.join("data/consoles/db"));
assert!(root.0.is_dir());
}
-83
Переглянути файл
@@ -542,23 +542,6 @@ 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();
@@ -713,73 +696,7 @@ 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>> {
events.lock().unwrap().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path: p, source, items } if source == "tsc" && **p == *path => {
-67
Переглянути файл
@@ -731,38 +731,6 @@ async fn reformat_uses_the_formatter_chain_and_preserves_a_dirty_buffer() {
assert!(p.documents.is_dirty(doc.id).unwrap());
}
/// Answers `execute_run_configuration`'s window requests the way the Run tool window does:
/// starts the configuration in a tab and says whether it started. Returns what it started.
fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>> {
let started = Arc::new(std::sync::Mutex::new(Vec::new()));
let (host, events, out) = (h.host.clone(), h.events.clone(), started.clone());
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|e| match e {
IdeEvent::McpRequest { id, request: ide_core::event::McpUiRequest::RunConfiguration { config } }
if !handled.contains(id) =>
{
Some((*id, config.clone()))
}
_ => None,
});
let Some((id, config)) = request else {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
continue;
};
handled.insert(id);
let config: ide_run::RunConfig = serde_json::from_value(config).unwrap();
out.lock().unwrap().push(config.clone());
let result =
ide_host::ops::run::run_start(&host, "main", config, ide_host::ops::Channel::new(|_| {}), None).await;
let error = result.err().map(|e| e.message);
let _ = host.mcp_requests.answer("main", id, error.is_none(), error);
}
});
started
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_reports_output_exit_code_and_requires_confirmation() {
let h = Harness::new();
@@ -797,7 +765,6 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
assert!(error.contains("denied by the user"));
assert!(h.host.processes.list().is_empty());
h.events.lock().unwrap().clear();
let tabs = config_run_window(&h);
let run = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
let allow = async {
let id = h.request().await;
@@ -806,39 +773,6 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
let (result, ()) = tokio::join!(run, allow);
assert_eq!(result["exitCode"], 7);
assert!(result["output"].as_str().unwrap().contains("captured-output"));
// It ran in a Run tool window tab, as the user's Run would.
let tabs = tabs.lock().unwrap();
assert_eq!(tabs.len(), 1);
assert_eq!(tabs[0].name, "MCP test");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
let h = Harness::new();
h.trust().await;
let config = ide_run::RunConfig {
id: "test".into(),
name: "MCP test".into(),
kind: "shell".into(),
command: if cfg!(windows) { "echo windowless& exit 3" } else { "echo windowless; exit 3" }.into(),
args: vec![],
cwd: None,
env: Default::default(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
ide_run::save_user_configs(&h.root, &[config]).unwrap();
h.host
.global_settings
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
.unwrap();
let result = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})).await;
assert_eq!(result["exitCode"], 3, "{result}");
assert!(result["output"].as_str().unwrap().contains("windowless"));
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
#[tokio::test(flavor = "multi_thread")]
@@ -861,7 +795,6 @@ async fn a_configuration_left_running_is_stopped_by_its_run_id() {
};
ide_run::save_user_configs(&h.root, &[config]).unwrap();
h.host.mcp_requests.set_ready("main", true);
let _tabs = config_run_window(&h);
let run = h.json("execute_run_configuration", json!({"configurationName":"Server","waitForExit":false}));
let allow = async {
let id = h.request().await;
+3 -4
Переглянути файл
@@ -429,10 +429,9 @@ fn gutter_actions_see_the_editors_window_project() {
assert_eq!(actions.len(), 1);
actions[0].1.argument.clone().unwrap()
};
// The outer project's window: the file is its, though the inner project holds it too. Compared
// as paths: the plugin sees Windows paths `/`-separated.
assert_eq!(Path::new(&argument(Some(&outer))), outer);
assert_eq!(Path::new(&argument(Some(&inner))), inner);
// The outer project's window: the file is its, though the inner project holds it too.
assert_eq!(argument(Some(&outer)), outer.to_string_lossy());
assert_eq!(argument(Some(&inner)), inner.to_string_lossy());
// No window, or a root that is no open project: no invoking project.
assert_eq!(argument(None), "gutter");
assert_eq!(argument(Some(&tmp.path().join("elsewhere"))), "gutter");
+1 -2
Переглянути файл
@@ -52,8 +52,7 @@ fn the_plugins_configuration_completes_only_the_argument_under_the_caret() {
let config = "plugin:test.run-anything:tasks";
// Not provided until its program is approved.
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 1).is_err());
// Any approved executable will do; the test binary exists on every host.
p.choose_program(ID, "process:task", Some(&root), Some(&std::env::current_exe().unwrap())).unwrap();
p.choose_program(ID, "process:task", Some(&root), Some(Path::new("/bin/echo"))).unwrap();
assert!(p.run_detection().detect(&root).iter().any(|c| c.id == config));
let complete = |text: &str, caret: u32| -> Vec<(String, String, u32, u32)> {
p.run_configuration_complete("main", &root, config, "arguments", text, caret)
+1 -1
Переглянути файл
@@ -6,6 +6,7 @@ use ide_host::{Host, HostConfig};
use ide_plugin::TextQuery;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
struct Harness {
host: Arc<Host>,
@@ -509,7 +510,6 @@ async fn plugin_run_output_mode_executes_pty_and_pipes_with_input_exit_and_stop(
use ide_host::plugins::{Consent, PluginEvent, PluginHost, WindowRequest};
use ide_plugin::{Invocation, Limits};
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
let f = Harness::new();
f.host.set_project_trust(&f.root, true, false).await.unwrap();
+1 -2
Переглянути файл
@@ -6794,8 +6794,6 @@ 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}",
@@ -6803,6 +6801,7 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
)
.as_bytes(),
);
seen.lock().push("served".into());
}
});
}
+8 -14
Переглянути файл
@@ -5,7 +5,7 @@ mod common;
use ide_core::{Pos, RequestId};
use ide_host::{Host, ops};
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery, SearchScope};
use ide_search::{ReplaceEvent, ReplaceSummary, ReplaceTarget, SearchQuery};
use std::sync::{Arc, Mutex};
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
@@ -145,10 +145,9 @@ async fn replace_all_covers_matches_past_the_limit() {
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let scope = base.join("scope");
let root = scope.join("project");
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
for name in ["previewed.txt", "edited.txt", "closed.txt", "stale.txt"] {
std::fs::write(root.join(name), "TOKEN\n").unwrap();
}
let host = Host::new(common::host_config(&base));
@@ -158,18 +157,14 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
project.documents.open(&root.join("previewed.txt")).unwrap();
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
// Search the parent folder so Replace All also covers a clean buffer outside the project watch.
let stale_path = scope.join("stale.txt");
std::fs::write(&stale_path, "TOKEN\n").unwrap();
let stale = project.documents.open(&stale_path).unwrap().id;
std::fs::write(&stale_path, "TOKEN\nexternal\n").unwrap();
let mut search = query("TOKEN", false);
search.scope = SearchScope::Directory { path: scope.into() };
// Open and clean, but changed on disk before the watcher reported it.
let stale = project.documents.open(&root.join("stale.txt")).unwrap().id;
std::fs::write(root.join("stale.txt"), "TOKEN\nexternal\n").unwrap();
ops::search::replace_in_files(
&host,
"main",
RequestId::next(),
search,
query("TOKEN", false),
"DONE".into(),
false,
vec![],
@@ -183,8 +178,7 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
assert_eq!(disk("closed.txt"), "DONE\n");
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
assert_eq!(std::fs::read_to_string(&stale_path).unwrap(), "TOKEN\nexternal\n", "the external change is kept");
assert_eq!(project.documents.text_snapshot(stale).unwrap().text, "DONE\n");
assert_eq!(disk("stale.txt"), "TOKEN\nexternal\n", "the external change is kept");
assert!(project.documents.is_dirty(stale).unwrap(), "the replacement stays unsaved");
host.close_project("main");
}
+4 -19
Переглянути файл
@@ -80,23 +80,14 @@ async fn serves_projects_files_documents_search_and_runs() {
assert_eq!(opened["name"], "demo");
assert_eq!(opened["trusted"], false);
invoke(&peer, "index_status", json!({})).await.unwrap();
let metrics = invoke(&peer, "host_metrics", json!({ "includeProcesses": true })).await.unwrap();
assert!(metrics["cpuCores"].as_u64().unwrap() >= 1);
assert_eq!(metrics["processes"][0]["label"], "Backend");
assert_eq!(invoke(&peer, "lsp_servers", json!({})).await.unwrap(), json!([]));
invoke(&peer, "lsp_resend_diagnostics", json!({})).await.unwrap();
let files = invoke(&peer, "find_files", json!({"query": "main", "limit": 10})).await.unwrap();
assert!(files.is_array());
for (command, args) in [
("build_sync", json!({})),
("run_start", json!({})),
("sdk_locate_tools", json!({})),
("notebook_execute", json!({})),
("debug_start", json!({})),
("agent_refresh_models", json!({})),
("host_end_process", json!({ "pid": 1 })),
] {
let error = invoke(&peer, command, args).await.unwrap_err();
for command in
["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start", "agent_refresh_models"]
{
let error = invoke(&peer, command, json!({})).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
}
let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) };
@@ -280,9 +271,6 @@ async fn serves_projects_files_documents_search_and_runs() {
.await
.unwrap();
assert_eq!(env["DOCKER_HOST"], "unix:///run/user/1/docker.sock");
// Services › Docker commands are served by the project host too.
assert!(Dispatcher::standard().commands().contains(&"docker_snapshot"));
assert_eq!(invoke(&peer, "docker_settings", json!({})).await.unwrap()["connections"], json!([]));
// Real project-host ignore writes travel through the remote command dispatcher.
assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
@@ -403,8 +391,6 @@ async fn local_deployment_runs_on_the_project_host() {
"http_curl",
"http_environment_file",
"http_variable_definitions",
"db_source_folders",
"db_save_source_folders",
"db_sources",
"db_save_sources",
"db_set_password",
@@ -434,7 +420,6 @@ async fn local_deployment_runs_on_the_project_host() {
"db_table_page",
"db_apply_edits",
"db_console_path",
"db_consoles_dir",
"db_consoles",
"ssh_test",
"ssh_set_secret",
-22
Переглянути файл
@@ -50,25 +50,3 @@ 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");
}
+1 -3
Переглянути файл
@@ -29,9 +29,7 @@ pub use syntax::{
set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{
MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule,
PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases, resolve_fixture,
visible_fixtures,
MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases,
};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
+5 -57
Переглянути файл
@@ -89,42 +89,12 @@ fn has_toml_table(file: &Path, table: &str) -> bool {
table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table)
}
/// `file` parses as JSON (with comments: `tsconfig.json`) and has the dotted `key` with a value
/// other than `null` or `false`: an object (`eslintConfig`), a dependency's version
/// (`dependencies.tailwindcss`) or a switch that is on (`cmkOptions.enabled`).
/// `file` parses as JSON and has the dotted `key` with a value other than `null`:
/// an object (`eslintConfig`) or a dependency's version (`dependencies.tailwindcss`).
fn has_json_key(file: &Path, key: &str) -> bool {
json_key(file, key, 0).is_some_and(|v| !v.is_null() && v != serde_json::Value::Bool(false))
}
/// The dotted `key` of the JSON `file`. A tsconfig.json / jsconfig.json without it inherits it
/// through `extends` from a local file (`./base`, `../tsconfig.base.json`), the first one defining
/// it winning, as CSS Modules Kit reads `cmkOptions`.
fn json_key(file: &Path, key: &str, depth: usize) -> Option<serde_json::Value> {
// ponytail: package `extends` (`@tsconfig/node20`) are not resolved; only local files.
const MAX_DEPTH: usize = 8;
let text = std::fs::read_to_string(file).ok()?;
let value = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text)).ok()?;
if let Some(v) = key.split('.').try_fold(&value, |v, key| v.get(key)) {
return Some(v.clone());
}
let name = file.file_name()?.to_string_lossy();
if depth >= MAX_DEPTH || !(name.starts_with("tsconfig") || name.starts_with("jsconfig")) {
return None;
}
let extends = match value.get("extends")? {
serde_json::Value::String(s) => vec![s.as_str()],
serde_json::Value::Array(a) => a.iter().filter_map(serde_json::Value::as_str).collect(),
_ => return None,
};
extends.into_iter().filter(|e| e.starts_with("./") || e.starts_with("../")).find_map(|e| {
let base = file.parent()?.join(e);
let base = if base.is_file() {
base
} else {
base.with_file_name(format!("{}.json", base.file_name()?.to_string_lossy()))
};
json_key(&base, key, depth + 1)
})
let Ok(text) = std::fs::read_to_string(file) else { return false };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(|v| !v.is_null())
}
/// `path` is (or, after its creation or removal, was) a root marker of the
@@ -221,28 +191,6 @@ mod tests {
std::fs::write(dir.join("package.json"), r#"{"eslintConfig": null}"#).unwrap();
assert!(!has_marker(dir, "package.json#eslintConfig"));
assert!(is_marker_path(&dir.join("package.json"), marker));
// tsconfig.json is JSON with comments; a switch that is off is no marker.
let cmk = "tsconfig.json#cmkOptions.enabled";
let tsconfig =
|enabled: &str| format!("{{\n // CSS Modules Kit\n \"cmkOptions\": {{ \"enabled\": {enabled} }},\n}}");
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
assert!(has_marker(dir, cmk));
std::fs::write(dir.join("tsconfig.json"), tsconfig("false")).unwrap();
assert!(!has_marker(dir, cmk));
// Inherited through a local `extends`, which the file itself can turn off.
std::fs::create_dir_all(dir.join("app")).unwrap();
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": ["@tsconfig/strictest", "../tsconfig"] }"#)
.unwrap();
assert!(has_marker(&dir.join("app"), cmk));
std::fs::write(
dir.join("app/tsconfig.json"),
r#"{ "extends": "../tsconfig.json", "cmkOptions": { "enabled": false } }"#,
)
.unwrap();
assert!(!has_marker(&dir.join("app"), cmk));
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": "./tsconfig.json" }"#).unwrap();
assert!(!has_marker(&dir.join("app"), cmk), "a cycle ends");
}
#[test]
-20
Переглянути файл
@@ -63,7 +63,6 @@ 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")),
@@ -1074,8 +1073,6 @@ mod tests {
assert_eq!(detect("shop/templates/shop/product_list.html"), "django-html");
assert_eq!(detect("shop/templates/shop/email/order.txt"), "django-html");
assert_eq!(detect("pages/promo.html"), "html");
// No `[debugger]` of its own: `find_config` would take it for debugpy instead of Python's.
assert!(reg.get(&LanguageId::new("django-html")).unwrap().debugger.is_none());
}
/// #4061: the project root is canonical; a template reached under another
@@ -1284,7 +1281,6 @@ mod tests {
("Views/MainWindow.axaml", "axaml"),
("MainWindow.xaml", "xml"),
("README.md", "markdown"),
("Intro.mdx", "mdx"),
("Dockerfile", "dockerfile"),
("Dockerfile.dev", "dockerfile"),
("Makefile", "makefile"),
@@ -1366,22 +1362,6 @@ 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 = &reg.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();
-5
Переглянути файл
@@ -13,7 +13,6 @@ mod literals;
mod outline;
mod php_align;
mod python_facts;
mod python_fixtures;
mod python_imports;
mod rearrange;
mod rst;
@@ -36,10 +35,6 @@ pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::{merge_kinds, merge_visibility};
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression};
pub use python_fixtures::{
PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestModule, resolve_fixture,
visible_fixtures,
};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::OnceLock;
-517
Переглянути файл
@@ -1,517 +0,0 @@
//! pytest fixtures in one Python module: the fixtures it defines (`@pytest.fixture`), the
//! places it names one (a test's or fixture's parameters, `usefixtures("x")`,
//! `getfixturevalue("x")`) and the plugin modules it loads (`pytest_plugins`). From the
//! syntax tree only; [`resolve_fixture`] then picks the definition pytest uses, given the
//! modules a test sees, nearest first.
use super::lines::LineIndex;
use crate::{LanguageId, Syntax};
use ide_core::{Pos, Range};
use tree_sitter::{Node, Tree};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PytestModule {
pub fixtures: Vec<PytestFixture>,
pub uses: Vec<PytestFixtureUse>,
/// Where a fixture name may be typed: completion offers the visible fixtures there.
pub slots: Vec<PytestFixtureSlot>,
/// Modules named by a module-level `pytest_plugins`, as written (`pkg.fixtures`).
pub plugins: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PytestFixture {
/// The name tests ask for: the `name=` argument, else the function's name.
pub name: String,
/// That name in the source: the function name, or the `name=` string's content.
pub selection: Range,
/// The class whose method it is; only that class's tests see it.
pub class: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PytestFixtureUseKind {
Parameter,
UseFixtures,
GetFixtureValue,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PytestFixtureUse {
pub name: String,
pub range: Range,
pub kind: PytestFixtureUseKind,
pub class: Option<String>,
/// The fixture whose parameter this is: `def tasks(tasks)` asks for the next `tasks` outward.
pub in_fixture: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PytestFixtureSlot {
/// A test's or fixture's parameter list, or the content of a `usefixtures` /
/// `getfixturevalue` string (empty strings included).
pub range: Range,
pub class: Option<String>,
}
impl PytestModule {
/// The use whose name covers `pos` (its end included, where a caret after the name sits).
pub fn use_at(&self, pos: Pos) -> Option<&PytestFixtureUse> {
self.uses.iter().find(|u| u.range.start <= pos && pos <= u.range.end)
}
/// The slot holding `pos`.
pub fn slot_at(&self, pos: Pos) -> Option<&PytestFixtureSlot> {
self.slots.iter().filter(|s| s.range.start <= pos && pos <= s.range.end).min_by_key(|s| s.range.end)
}
}
impl Syntax {
/// The pytest fixtures a Python `text` defines and names; empty for other languages.
pub fn pytest_module(&self, lang: &LanguageId, text: &str) -> PytestModule {
self.analyze(lang, text, |g, tree, text| (g.spec.name == "python").then(|| extract(tree, text)))
.unwrap_or_default()
}
}
/// The fixture pytest uses for a name asked in `layers[0]` (the module), `class` being the
/// asking test's class, the later layers being the `conftest.py` files from the module's
/// folder upward, then plugins and pytest's own modules. `overriding`: the asker is a fixture
/// of that same name, which gets the next definition outward. Returns (layer, fixture) indexes.
pub fn resolve_fixture(
layers: &[&PytestModule],
name: &str,
class: Option<&str>,
overriding: bool,
) -> Option<(usize, usize)> {
visible(layers, class).filter(|&(l, f)| layers[l].fixtures[f].name == name).nth(usize::from(overriding))
}
/// The fixtures a test of `class` in `layers[0]` sees, nearest first, one per name.
pub fn visible_fixtures(layers: &[&PytestModule], class: Option<&str>) -> Vec<(usize, usize)> {
let mut seen = std::collections::HashSet::new();
visible(layers, class).filter(|&(l, f)| seen.insert(layers[l].fixtures[f].name.as_str())).collect()
}
/// Every fixture visible from `class` in `layers[0]`, nearest first: the class's own, then
/// the module's, then each later layer's module-level ones. Within one scope the last
/// definition of a name wins, as Python rebinds it.
fn visible<'a>(layers: &'a [&'a PytestModule], class: Option<&'a str>) -> impl Iterator<Item = (usize, usize)> + 'a {
let scopes = layers.iter().enumerate().flat_map(move |(l, m)| {
let own = (l == 0).then_some(class).flatten().map(|c| (l, m, Some(c)));
own.into_iter().chain(std::iter::once((l, m, None)))
});
scopes.flat_map(|(l, m, scope)| {
let mut picked: Vec<(usize, usize)> = Vec::new();
for (f, fixture) in m.fixtures.iter().enumerate().rev() {
if fixture.class.as_deref() == scope && !picked.iter().any(|&(_, p)| m.fixtures[p].name == fixture.name) {
picked.push((l, f));
}
}
picked.reverse();
picked
})
}
fn extract(tree: &Tree, text: &str) -> PytestModule {
let idx = LineIndex::new(text);
let mut out = PytestModule::default();
let root = tree.root_node();
let mut cursor = root.walk();
for node in root.named_children(&mut cursor) {
statement(node, None, text, &idx, &mut out);
}
// `usefixtures` / `getfixturevalue` calls wherever they are.
let mut walker = root.walk();
visit(&mut walker, &mut |node| {
if node.kind() == "call" {
fixture_call(node, text, &idx, &mut out);
}
});
out
}
/// A top-level statement, or one in a class body (`class` set).
fn statement(node: Node, class: Option<&str>, text: &str, idx: &LineIndex, out: &mut PytestModule) {
let (definition, decorators) = match node.kind() {
"decorated_definition" => {
let mut c = node.walk();
let decorators: Vec<Node> = node.children(&mut c).filter(|n| n.kind() == "decorator").collect();
let Some(definition) = node.child_by_field_name("definition") else { return };
(definition, decorators)
}
_ => (node, Vec::new()),
};
match definition.kind() {
"function_definition" => function(definition, &decorators, class, &[], text, idx, out),
"class_definition" if class.is_none() => {
let Some(name) = definition.child_by_field_name("name") else { return };
let name = text_of(name, text);
let Some(body) = definition.child_by_field_name("body") else { return };
// `@pytest.mark.parametrize` on the class names arguments of every test in it.
let class_args = parametrized(&decorators, text, idx);
let mut c = body.walk();
for child in body.named_children(&mut c) {
let (def, decs) = match child.kind() {
"decorated_definition" => {
let mut c2 = child.walk();
let decs: Vec<Node> = child.children(&mut c2).filter(|n| n.kind() == "decorator").collect();
match child.child_by_field_name("definition") {
Some(d) => (d, decs),
None => continue,
}
}
_ => (child, Vec::new()),
};
if def.kind() == "function_definition" {
function(def, &decs, Some(&name), &class_args, text, idx, out);
}
}
}
"expression_statement" if class.is_none() => plugins(definition, text, idx, &mut out.plugins),
_ => {}
}
}
fn function(
def: Node,
decorators: &[Node],
class: Option<&str>,
class_args: &[String],
text: &str,
idx: &LineIndex,
out: &mut PytestModule,
) {
let Some(name_node) = def.child_by_field_name("name") else { return };
let name = text_of(name_node, text);
let fixture = decorators.iter().find_map(|d| fixture_decorator(*d, text, idx));
let is_test = name.starts_with("test") && class.is_none_or(|c| c.starts_with("Test"));
if fixture.is_none() && !is_test {
return;
}
let fixture_name = fixture.as_ref().and_then(|f| f.as_ref().map(|(n, _)| n.clone())).unwrap_or(name.clone());
if let Some(f) = &fixture {
let selection = match f {
Some((_, string)) => *string,
None => idx.range(name_node.start_byte(), name_node.end_byte()),
};
out.fixtures.push(PytestFixture { name: fixture_name.clone(), selection, class: class.map(str::to_owned) });
}
let Some(params) = def.child_by_field_name("parameters") else { return };
out.slots.push(PytestFixtureSlot {
range: idx.range(params.start_byte(), params.end_byte()),
class: class.map(str::to_owned),
});
// Arguments `parametrize` supplies are no fixtures (unless indirect).
let mut skip: Vec<String> = parametrized(decorators, text, idx);
skip.extend_from_slice(class_args);
let mut c = params.walk();
for (i, param) in params.named_children(&mut c).enumerate() {
let ident = match param.kind() {
"identifier" => param,
"typed_parameter" => match param.named_child(0) {
Some(n) if n.kind() == "identifier" => n,
_ => continue,
},
// Defaulted parameters, `*args`, `**kwargs`: no fixtures.
_ => continue,
};
let param_name = text_of(ident, text);
if (i == 0 && class.is_some() && (param_name == "self" || param_name == "cls")) || skip.contains(&param_name) {
continue;
}
out.uses.push(PytestFixtureUse {
name: param_name,
range: idx.range(ident.start_byte(), ident.end_byte()),
kind: PytestFixtureUseKind::Parameter,
class: class.map(str::to_owned),
in_fixture: fixture.is_some().then(|| fixture_name.clone()),
});
}
}
/// `Some(None)` for `@pytest.fixture` / `@fixture(...)`, `Some(Some((name, range)))` with a
/// `name="…"` argument, `None` for any other decorator.
fn fixture_decorator(decorator: Node, text: &str, idx: &LineIndex) -> Option<Option<(String, Range)>> {
let expr = decorator.named_child(0)?;
let (callee, args) = match expr.kind() {
"call" => (expr.child_by_field_name("function")?, expr.child_by_field_name("arguments")),
_ => (expr, None),
};
let callee = text_of(callee, text);
if callee != "fixture" && !callee.ends_with(".fixture") {
return None;
}
let named = args.and_then(|args| {
let mut c = args.walk();
args.named_children(&mut c).find_map(|a| {
if a.kind() != "keyword_argument" || a.child_by_field_name("name").map(|n| text_of(n, text))? != "name" {
return None;
}
string_content(a.child_by_field_name("value")?, text, idx)
})
});
Some(named)
}
/// The argument names of `@pytest.mark.parametrize("a, b", …)` decorators that are passed
/// directly (no `indirect=`).
fn parametrized(decorators: &[Node], text: &str, idx: &LineIndex) -> Vec<String> {
let mut out = Vec::new();
for d in decorators {
let Some(call) = d.named_child(0).filter(|n| n.kind() == "call") else { continue };
let Some(callee) = call.child_by_field_name("function") else { continue };
if !text_of(callee, text).ends_with("parametrize") {
continue;
}
let Some(args) = call.child_by_field_name("arguments") else { continue };
let mut c = args.walk();
let all: Vec<Node> = args.named_children(&mut c).collect();
let indirect = all.iter().any(|a| {
a.kind() == "keyword_argument"
&& a.child_by_field_name("name").is_some_and(|n| text_of(n, text) == "indirect")
&& a.child_by_field_name("value").is_some_and(|v| text_of(v, text) != "False")
});
if indirect {
continue;
}
let first = all.iter().find(|a| a.kind() != "keyword_argument");
let names: Vec<String> = match first {
Some(n) if n.kind() == "string" => string_content(*n, text, idx)
.map(|(s, _)| s.split(',').map(|p| p.trim().to_owned()).collect())
.unwrap_or_default(),
Some(n) if matches!(n.kind(), "list" | "tuple") => {
let mut c = n.walk();
n.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s)).collect()
}
_ => Vec::new(),
};
out.extend(names.into_iter().filter(|n| !n.is_empty()));
}
out
}
/// `usefixtures("a", "b")` and `request.getfixturevalue("a")`.
fn fixture_call(call: Node, text: &str, idx: &LineIndex, out: &mut PytestModule) {
let Some(callee) = call.child_by_field_name("function") else { return };
let callee_text = text_of(callee, text);
let kind = if callee_text == "usefixtures" || callee_text.ends_with(".usefixtures") {
PytestFixtureUseKind::UseFixtures
} else if callee.kind() == "attribute"
&& callee.child_by_field_name("attribute").is_some_and(|a| text_of(a, text) == "getfixturevalue")
{
PytestFixtureUseKind::GetFixtureValue
} else {
return;
};
let Some(args) = call.child_by_field_name("arguments") else { return };
let class = enclosing_class(call, text);
let mut c = args.walk();
for (i, arg) in args.named_children(&mut c).enumerate() {
if kind == PytestFixtureUseKind::GetFixtureValue && i > 0 {
break;
}
let Some((name, range)) = string_content(arg, text, idx) else { continue };
out.slots.push(PytestFixtureSlot { range, class: class.clone() });
if !name.is_empty() {
out.uses.push(PytestFixtureUse { name, range, kind, class: class.clone(), in_fixture: None });
}
}
}
/// The top-level class a node is in, if any.
fn enclosing_class(node: Node, text: &str) -> Option<String> {
let mut at = node.parent();
let mut class = None;
while let Some(n) = at {
if n.kind() == "class_definition" {
class = n.child_by_field_name("name").map(|c| text_of(c, text));
}
at = n.parent();
}
class
}
/// `pytest_plugins = "a"`, `= ["a", "b"]` or `= ("a",)`.
fn plugins(statement: Node, text: &str, idx: &LineIndex, out: &mut Vec<String>) {
let Some(assign) = statement.named_child(0).filter(|n| n.kind() == "assignment") else { return };
if assign.child_by_field_name("left").map(|l| text_of(l, text)).as_deref() != Some("pytest_plugins") {
return;
}
let Some(right) = assign.child_by_field_name("right") else { return };
match right.kind() {
"string" => out.extend(string_content(right, text, idx).map(|(s, _)| s)),
"list" | "tuple" => {
let mut c = right.walk();
out.extend(right.named_children(&mut c).filter_map(|e| string_content(e, text, idx).map(|(s, _)| s)));
}
_ => {}
}
}
/// The content of a plain string literal and its range (between the quotes); none for
/// f-strings, byte strings and concatenations.
fn string_content(node: Node, text: &str, idx: &LineIndex) -> Option<(String, Range)> {
if node.kind() != "string" {
return None;
}
let mut c = node.walk();
let parts: Vec<Node> = node.children(&mut c).collect();
let start = parts.iter().find(|p| p.kind() == "string_start")?;
let end = parts.iter().find(|p| p.kind() == "string_end")?;
if text_of(*start, text).chars().any(|ch| matches!(ch, 'f' | 'F' | 'b' | 'B')) {
return None;
}
if parts.iter().any(|p| p.kind() == "interpolation" || p.kind() == "escape_sequence") {
return None;
}
let (from, to) = (start.end_byte(), end.start_byte());
Some((text.get(from..to)?.to_owned(), idx.range(from, to)))
}
fn text_of(node: Node, text: &str) -> String {
text.get(node.byte_range()).unwrap_or_default().to_owned()
}
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
loop {
f(cursor.node());
if cursor.goto_first_child() {
continue;
}
loop {
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn module(src: &str) -> PytestModule {
static S: std::sync::OnceLock<Syntax> = std::sync::OnceLock::new();
S.get_or_init(Syntax::new).pytest_module(&LanguageId::new("python"), src)
}
fn names(m: &PytestModule) -> Vec<String> {
m.fixtures
.iter()
.map(|f| format!("{}{}", f.class.as_deref().map(|c| format!("{c}.")).unwrap_or_default(), f.name))
.collect()
}
fn uses(m: &PytestModule) -> Vec<String> {
m.uses.iter().map(|u| format!("{:?} {}", u.kind, u.name)).collect()
}
const TEST_MODULE: &str = r#"import pytest
from pytest import fixture
pytest_plugins = ["pkg.fixtures", "other"]
pytestmark = pytest.mark.usefixtures("db")
@pytest.fixture
def tasks(tmp_path):
return []
@fixture(scope="module", name="client")
def make_client(tasks, request):
return request.getfixturevalue("server")
@pytest.mark.parametrize("title, expected", [("a", "a")])
def test_add(tasks, title, expected, monkeypatch, flag=False, *args):
pass
def helper(tasks):
pass
@pytest.mark.usefixtures("client", "")
class TestTasks:
@pytest.fixture
def tasks(self, tasks):
return tasks
def test_one(self, tasks: list, capsys):
pass
"#;
#[test]
fn reads_definitions_uses_and_plugins() {
let m = module(TEST_MODULE);
assert_eq!(names(&m), ["tasks", "client", "TestTasks.tasks"]);
assert_eq!(m.plugins, ["pkg.fixtures", "other"]);
assert_eq!(
uses(&m),
[
"Parameter tmp_path",
"Parameter tasks",
"Parameter request",
"Parameter tasks",
"Parameter monkeypatch",
"Parameter tasks",
"Parameter tasks",
"Parameter capsys",
"UseFixtures db",
"GetFixtureValue server",
"UseFixtures client",
]
);
// `name=` is found by its string; the overriding class fixture knows it overrides.
let client = &m.fixtures[1];
assert_eq!((client.selection.start.line, client.selection.start.col), (12, 31));
let own = m.uses.iter().find(|u| u.class.as_deref() == Some("TestTasks") && u.in_fixture.is_some()).unwrap();
assert_eq!(own.in_fixture.as_deref(), Some("tasks"));
// The empty `usefixtures` string is still a place to complete.
assert!(m.slots.iter().any(|s| s.range.start == s.range.end));
}
#[test]
fn resolves_nearest_first_and_overrides_outward() {
let m = module(TEST_MODULE);
let conftest = module(
"import pytest\n\n@pytest.fixture\ndef tasks():\n return [1]\n\n@pytest.fixture\ndef db():\n pass\n",
);
let builtins = module("from _pytest.fixtures import fixture\n\n@fixture\ndef tmp_path():\n pass\n");
let layers = [&m, &conftest, &builtins];
// In the class: its own `tasks`; at module level: the module's.
assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), false), Some((0, 2)));
assert_eq!(resolve_fixture(&layers, "tasks", None, false), Some((0, 0)));
// The class fixture's `tasks` parameter: the module's; the module's own: conftest's.
assert_eq!(resolve_fixture(&layers, "tasks", Some("TestTasks"), true), Some((0, 0)));
assert_eq!(resolve_fixture(&layers, "tasks", None, true), Some((1, 0)));
assert_eq!(resolve_fixture(&layers, "db", None, false), Some((1, 1)));
assert_eq!(resolve_fixture(&layers, "tmp_path", None, false), Some((2, 0)));
assert_eq!(resolve_fixture(&layers, "missing", None, false), None);
// Completion: one entry per name, nearest first; another class's fixtures are hidden.
let visible: Vec<&str> =
visible_fixtures(&layers, None).iter().map(|&(l, f)| layers[l].fixtures[f].name.as_str()).collect();
assert_eq!(visible, ["tasks", "client", "db", "tmp_path"]);
}
#[test]
fn a_later_definition_replaces_an_earlier_one() {
let m = module("import pytest\n\n@pytest.fixture\ndef a():\n pass\n\n@pytest.fixture\ndef a():\n pass\n");
assert_eq!(resolve_fixture(&[&m], "a", None, false), Some((0, 1)));
}
#[test]
fn finds_the_use_and_slot_at_a_position() {
let m = module(TEST_MODULE);
// `def test_add(tasks, …` is on line 18; the caret right after `tasks`.
let at = m.use_at(Pos::new(18, 18)).unwrap();
assert_eq!(at.name, "tasks");
assert!(m.slot_at(Pos::new(18, 13)).is_some());
assert!(m.use_at(Pos::new(22, 11)).is_none(), "a plain function's parameters are no fixtures");
}
}
+33 -178
Переглянути файл
@@ -38,85 +38,27 @@ struct Rewrite<'a> {
impl Rewrite<'_> {
fn run(mut self, tree: &Tree) -> Vec<TextEdit> {
let mut imports = Vec::new();
let mut idents = Vec::new();
let mut chains = Vec::new();
collect(tree.root_node(), &mut |n| match n.kind() {
"import_statement" | "import_from_statement" => imports.push(n),
"identifier" if !inside_import(n) => idents.push(n),
"attribute" if !inside_import(n) => chains.push(n),
_ => {}
});
// Unaliased `import a.b` that change: (name node, old, new). They bind `a`, used as `a.b.x`.
let mut dotted: Vec<(Node, String, String)> = Vec::new();
let mut kept: Vec<String> = Vec::new();
let mut renamed: Vec<(String, String)> = Vec::new();
for node in imports {
if node.kind() == "import_statement" {
self.import(node, &mut dotted, &mut kept);
self.import(node, &mut renamed);
} else {
self.import_from(node);
}
}
if dotted.is_empty() {
return self.finish();
}
let root_of = |s: &str| s.split('.').next().unwrap_or_default().to_owned();
let mut needed: Vec<(usize, String)> = Vec::new();
for id in idents {
let name = self.src(id);
if !dotted.iter().any(|(_, old, _)| root_of(old) == name) || is_attribute_field(id) {
continue;
}
// `a`, `a.b`, `a.b.x`: one edit per expression, on the longest prefix that moved.
let mut spine = vec![id];
while let Some(p) = spine
.last()
.and_then(|n| n.parent())
.filter(|p| p.kind() == "attribute" && p.child_by_field_name("object") == spine.last().copied())
{
spine.push(p);
}
let key = |n: Node| self.src(n).chars().filter(|c| !c.is_whitespace()).collect::<String>();
// ponytail: a bare `pkg` (no attribute) is never rewritten, it may be a parameter or a
// local of the same name.
if let Some((node, new)) =
spine.iter().skip(1).rev().find_map(|&n| Some((n, map_module(&key(n), self.moves)?)))
{
self.edit(node, new);
continue;
}
// A use the rewritten imports no longer bind (`pkg.helper()` after `import pkg.models` moved).
if spine.len() < 2 {
continue;
}
let used = key(*spine.last().unwrap_or(&id));
for (i, (_, old, new)) in dotted.iter().enumerate() {
let common: Vec<&str> = old
.split('.')
.zip(used.split('.'))
.take(old.split('.').count() - 1)
.take_while(|(a, b)| a == b)
.map(|(a, _)| a)
.collect();
if common.is_empty() {
continue;
}
let prefix = common.join(".");
let covered = |m: &String| *m == prefix || m.starts_with(&format!("{prefix}."));
let gone = map_module(&prefix, self.moves).is_some();
if !gone && !covered(new) && !kept.iter().any(covered) && !needed.contains(&(i, prefix.clone())) {
needed.push((i, prefix));
}
// `import a.b` is used as `a.b.x`: those chains follow the import.
for node in chains {
let t = self.src(node);
if let Some((_, new)) = renamed.iter().find(|(old, _)| *old == t) {
self.edit(node, new.clone());
}
}
for (i, (node, _, new)) in dotted.iter().enumerate() {
let extra: String = needed.iter().filter(|(j, _)| *j == i).map(|(_, p)| format!(", {p}")).collect();
self.edits.push(TextEdit {
range: self.idx.range(node.start_byte(), node.end_byte()),
new_text: format!("{new}{extra}"),
});
}
self.finish()
}
fn finish(mut self) -> Vec<TextEdit> {
self.edits.sort_by_key(|e| (e.range.start.line, e.range.start.col));
self.edits
}
@@ -130,7 +72,7 @@ impl Rewrite<'_> {
}
/// `import a.b`, `import a.b as c`.
fn import<'t>(&mut self, node: Node<'t>, dotted: &mut Vec<(Node<'t>, String, String)>, kept: &mut Vec<String>) {
fn import(&mut self, node: Node, renamed: &mut Vec<(String, String)>) {
let mut cursor = node.walk();
for item in node.children_by_field_name("name", &mut cursor) {
let (name, aliased) = match item.kind() {
@@ -141,16 +83,12 @@ impl Rewrite<'_> {
_ => (item, false),
};
let old = self.src(name).to_owned();
let Some(new) = map_module(&old, self.moves) else {
if !aliased {
kept.push(old);
}
continue;
};
let Some(new) = map_module(&old, self.moves) else { continue };
if aliased {
self.edit(name, new);
} else if old.contains('.') {
dotted.push((name, old, new));
renamed.push((old, new.clone()));
self.edit(name, new);
} else {
// The bound name stays, so the rest of the file needs no change.
self.edit(name, format!("{new} as {old}"));
@@ -228,20 +166,18 @@ impl Rewrite<'_> {
}
return;
}
for (item, text) in &in_place {
self.edit(*item, text.clone());
}
if moved.is_empty() {
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
for (item, text) in in_place {
self.edit(item, text);
}
return;
}
// Names imported from elsewhere now go to statements of their own, after this one (or
// after `;` when the statement shares its line: `try: from a import b, c`).
let line_start = self.text[..node.start_byte()].rfind('\n').map_or(0, |i| i + 1);
let before = &self.text[line_start..node.start_byte()];
let sep = if before.trim().is_empty() { format!("\n{before}") } else { "; ".to_owned() };
// ponytail: a split statement loses a multi-line names list's layout; fine for the rare
// "some names of one `from` moved elsewhere" case.
let indent = line_indent(self.text, node.start_byte());
let mut parents: Vec<&str> = Vec::new();
for m in &moved {
if !parents.contains(&m.1.as_str()) {
@@ -258,46 +194,28 @@ impl Rewrite<'_> {
format!("from {from} import {}", items.join(", "))
});
}
let is_moved = |n: &Node| moved.iter().any(|m| m.0 == *n);
let Some(last_kept) = names.iter().rposition(|n| !is_moved(n)) else {
let kept: Vec<String> = names
.iter()
.filter(|n| !moved.iter().any(|m| m.0 == **n))
.map(|n| in_place.iter().find(|(i, _)| i == n).map_or_else(|| self.src(*n).to_owned(), |(_, t)| t.clone()))
.collect();
let sep = format!("\n{indent}");
if kept.is_empty() {
self.edit(node, added.join(&sep));
return;
};
}
if let Some(m) = render(&target, self).filter(|m| m != self.src(module)) {
self.edit(module, m);
}
let mut trailing_done = false;
for (i, item) in names.iter().enumerate().filter(|(_, n)| is_moved(n)) {
let (start, end) = if let Some(line) = self.own_lines(*item) {
line
} else if i < last_kept {
(item.start_byte(), names[i + 1].start_byte())
} else if !trailing_done {
trailing_done = true;
(names[last_kept].end_byte(), names[names.len() - 1].end_byte())
} else {
continue;
};
self.edits.push(TextEdit { range: self.idx.range(start, end), new_text: String::new() });
}
let (first, last) = (names[0], names[names.len() - 1]);
let range = self.idx.range(first.start_byte(), last.end_byte());
self.edits.push(TextEdit { range, new_text: kept.join(", ") });
let end = self.idx.pos(node.end_byte());
self.edits.push(TextEdit {
range: ide_core::Range { start: end, end },
new_text: format!("{sep}{}", added.join(&sep)),
});
}
/// The whole lines of an import list item that has them to itself (` models, # noqa`).
fn own_lines(&self, item: Node) -> Option<(usize, usize)> {
let start = self.text[..item.start_byte()].rfind('\n').map_or(0, |i| i + 1);
if !self.text[start..item.start_byte()].trim().is_empty() {
return None;
}
let end = self.text[item.end_byte()..].find('\n').map_or(self.text.len(), |i| item.end_byte() + i + 1);
let rest = self.text[item.end_byte()..end].trim_start();
let rest = rest.strip_prefix(',').unwrap_or(rest).trim();
(rest.is_empty() || rest.starts_with('#')).then_some((start, end))
}
}
fn collect<'t>(node: Node<'t>, f: &mut impl FnMut(Node<'t>)) {
@@ -318,9 +236,9 @@ fn inside_import(mut n: Node) -> bool {
false
}
/// `x` in `obj.x`.
fn is_attribute_field(n: Node) -> bool {
n.parent().is_some_and(|p| p.kind() == "attribute" && p.child_by_field_name("attribute") == Some(n))
fn line_indent(text: &str, byte: usize) -> &str {
let start = text[..byte].rfind('\n').map_or(0, |i| i + 1);
&text[start..byte]
}
fn join(a: &str, b: &str) -> String {
@@ -370,11 +288,6 @@ mod tests {
let moves: Vec<(String, String)> = moves.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
let mut edits = Syntax::new().python_import_edits(text, package, new_package, &moves);
edits.sort_by_key(|e| std::cmp::Reverse((e.range.start.line, e.range.start.col)));
// Like `ide-text`, which rejects a set of overlapping edits.
for w in edits.windows(2) {
let (later, earlier) = (&w[0].range, &w[1].range);
assert!((earlier.end.line, earlier.end.col) <= (later.start.line, later.start.col), "overlap: {edits:?}");
}
let mut out = text.to_owned();
for e in edits {
let (s, t) = (byte_at(&out, e.range.start).unwrap(), byte_at(&out, e.range.end).unwrap());
@@ -475,64 +388,6 @@ mod tests {
assert_eq!(apply(src, "pkg", "pkg", RENAME), src);
}
#[test]
fn nested_chains_get_one_edit() {
let src = "import pkg.models\nimport pkg.models.sub\npkg.models.sub.f()\npkg.models.g()\n";
assert_eq!(
apply(src, "", "", &[("pkg", "lib.pkg")]),
"import lib.pkg.models\nimport lib.pkg.models.sub\nlib.pkg.models.sub.f()\nlib.pkg.models.g()\n"
);
}
#[test]
fn other_uses_of_the_old_prefix_keep_their_binding() {
let moves = &[("pkg.models", "core.models")];
assert_eq!(
apply("import pkg.models\n\npkg.models.Task()\npkg.helper()\n", "", "", moves),
"import core.models, pkg\n\ncore.models.Task()\npkg.helper()\n"
);
let moves = &[("a.b.c", "a.x.c")];
assert_eq!(
apply("import a.b.c\na.b.c.f()\na.b.g()\n", "", "", moves),
"import a.x.c, a.b\na.x.c.f()\na.b.g()\n"
);
// Inside a moved package the other uses follow it.
assert_eq!(
apply("import pkg.models\npkg.helper()\n", "", "", &[("pkg", "lib.pkg")]),
"import lib.pkg.models\nlib.pkg.helper()\n"
);
}
#[test]
fn bare_names_are_left_alone() {
let src = "import pkg.models\ndef f(pkg):\n return pkg.models.x\n";
assert_eq!(
apply(src, "", "", &[("pkg", "lib.pkg")]),
"import lib.pkg.models\ndef f(pkg):\n return lib.pkg.models.x\n"
);
}
#[test]
fn split_statements_stay_valid() {
let moves = &[("pkg.models", "core.models")];
assert_eq!(
apply("try: from pkg import cli, models\nexcept ImportError: pass\n", "", "", moves),
"try: from pkg import cli; from core import models\nexcept ImportError: pass\n"
);
assert_eq!(
apply("import os; from pkg import cli, models\n", "", "", moves),
"import os; from pkg import cli; from core import models\n"
);
assert_eq!(
apply("from pkg import (\n models, # noqa: F401\n cli, # used below\n)\n", "", "", moves),
"from pkg import (\n cli, # used below\n)\nfrom core import models\n"
);
assert_eq!(
apply("from pkg import (\n cli, # used below\n models,\n)\n", "", "", moves),
"from pkg import (\n cli, # used below\n)\nfrom core import models\n"
);
}
#[test]
fn helpers() {
assert_eq!(resolve(1, "m", "a.b").as_deref(), Some("a.b.m"));
-1
Переглянути файл
@@ -28,7 +28,6 @@ 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"] }
-53
Переглянути файл
@@ -34,20 +34,6 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin
Some(settings)
}
/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with
/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3:
/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes.
/// A threshold the server configuration sets explicitly is kept.
fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value {
let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned();
let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5);
let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3);
json!({
"starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)),
"staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)),
})
}
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
for (id, value) in settings {
let marker = format!(r#"<setting id="{id}" value=""#);
@@ -98,7 +84,6 @@ pub fn configure_formatter(
});
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited);
cfg.settings = Some(settings);
let Some(style) = style else { return Ok(()) };
let indent = indent_settings(style);
@@ -315,44 +300,6 @@ mod tests {
}
}
#[test]
fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir_all(&root).unwrap();
let imports = |cfg: &LanguageServerConfig| {
crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone()
};
let mut cfg = config("jdtls");
let style = LanguageCodeStyle {
class_count_to_use_import_with_star: Some(7),
names_count_to_use_static_import_with_star: Some(4),
..Default::default()
};
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4}));
// Unset: IDEA's 5 and 3, not jdtls' 99 (#6026).
let mut cfg = config("jdtls");
let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() };
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2}));
let mut cfg = config("jdtls");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3}));
// A threshold set in the server configuration wins.
let mut cfg = config("jdtls");
cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}}));
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2}));
let mut cfg = config("rust-analyzer");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert!(crate::handler::all_settings(&cfg)["java"].is_null());
}
#[test]
fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() {
let dir = tempfile::tempdir().unwrap();
+6 -51
Переглянути файл
@@ -352,9 +352,6 @@ fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, pa
/// No target for `feature`: names the running servers that lack it, so the UI can
/// tell "the server can't do this" from "no server is running" (the UI's
/// `unavailableText` matches the "… doesn't support …" wording).
/// vscode-css-language-server, which lists a selector's own rule among its references.
const CSS_SERVER: &str = "vscode-css-language-server";
fn unsupported(servers: &[Arc<Server>], feature: &str) -> IdeError {
let running: Vec<&str> = servers.iter().filter(|s| s.running().is_some()).map(|s| s.name.as_str()).collect();
if running.is_empty() {
@@ -2232,19 +2229,7 @@ impl LspManager {
// A library method has thousands of usages in the dependencies and the JDK,
// which take seconds to search: those in the sources (where scope widening
// searches again) are shown first, then the rest are searched once.
let shown = |first: &Vec<ClassifiedReference>| {
if let Some(partial) = partial
&& !first.is_empty()
{
partial(References {
locations: first.iter().map(|r| r.location.clone()).collect(),
classified: first.clone(),
incomplete: None,
libraries_skipped: false,
});
}
};
let sources = self.widened(snap, t, pos, cancel, || query(true), files, shown).await?;
let sources = self.widened(snap, t, pos, cancel, || query(true), files).await?;
if let Some(e) = extension_error.lock().take() {
return Err(e);
}
@@ -2319,7 +2304,6 @@ impl LspManager {
}
}
}
let single = targets.len() == 1;
let requests = targets.iter().map(|t| {
let (snap, cancel) = (&snap, &cancel);
async move {
@@ -2336,20 +2320,8 @@ impl LspManager {
};
let files =
|v: &Vec<Location>| v.iter().filter(|l| l.uri.is_none()).map(|l| l.path.to_path_buf()).collect();
// With one server, what it finds in its own scope is shown while the files beyond
// it are searched. The CSS server's answer still loses the rule's own selector.
let shown = |first: &Vec<Location>| {
if let Some(partial) = partial
&& single
&& t.server.name != CSS_SERVER
&& !first.is_empty()
{
self.note_virtual(&t.server, first.iter().map(|l| l.uri.as_deref()));
partial(References { locations: first.clone(), ..Default::default() });
}
};
let result = if project_wide && !angular {
self.widened(snap, t, pos, cancel, query, files, shown).await
self.widened(snap, t, pos, cancel, query, files).await
} else {
query().await.map(|first| {
let empty = first.is_empty();
@@ -2360,13 +2332,9 @@ impl LspManager {
}
});
// The Angular server lists the declaration even when not asked to: the one
// the definition at `pos` points to is taken out of its answer. So does the CSS server
// with a selector's own rule (`.button`), always: where CSS Modules Kit defines the class
// name (`button`), vtsls lists the declaration itself when asked.
// the definition at `pos` points to is taken out of its answer.
let declarations = async {
let listed =
|t: &Target| (t.server.name == angular::SERVER && !include_declaration) || t.server.name == CSS_SERVER;
if !targets.iter().any(listed) {
if include_declaration || !targets.iter().any(|t| t.server.name == angular::SERVER) {
return Vec::new();
}
let defining = self.ready_targets(&snap.servers, |c| c.has("definitionProvider")).await;
@@ -2383,14 +2351,6 @@ impl LspManager {
let mut locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
if t.server.name == angular::SERVER {
locs.retain(|l| !declarations.contains(l));
} else if t.server.name == CSS_SERVER {
let overlaps = |a: &Location, b: &Location| {
a.path == b.path
&& a.uri == b.uri
&& a.range.start <= b.range.end
&& b.range.start <= a.range.end
};
locs.retain(|l| !declarations.iter().any(|d| overlaps(d, l)));
}
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
self.note_arduino_sources(&t.server, &locs);
@@ -2962,11 +2922,6 @@ impl LspManager {
let prepared = join_all(targets.iter().map(|t| self.prepare_rename_on(snap, t, pos))).await;
let able: Vec<&Target> =
targets.iter().zip(prepared).filter(|(_, r)| matches!(r, Ok(Some(_)))).map(|(t, _)| t).collect();
// CSS Modules Kit (vtsls) renames a class in the stylesheet and its scripts; the CSS
// server's own edit replaces the whole selector (`.button`) and would drop the dot.
if able.iter().any(|t| t.server.name == "vtsls") {
return able.into_iter().filter(|t| t.server.name != CSS_SERVER).collect();
}
if !able.is_empty() {
return able;
}
@@ -3022,7 +2977,7 @@ impl LspManager {
})
.collect()
};
let w = self.widened(snap, t, pos, cancel, query, files, |_| {}).await?;
let w = self.widened(snap, t, pos, cancel, query, files).await?;
// The second edit covers the first: its files stay analysed.
let mut edit = w.second.unwrap_or(w.first);
let mut more: BTreeMap<PathBuf, Vec<TextEdit>> = BTreeMap::new();
@@ -3661,7 +3616,7 @@ impl LspManager {
let files = |v: &Vec<HierarchyItem>| {
v.iter().filter(|i| i.uri.is_none()).map(|i| i.path.to_path_buf()).collect()
};
let w = self.widened(&snap, t, pos, cancel, query, files, |_| {}).await?;
let w = self.widened(&snap, t, pos, cancel, query, files).await?;
(w.second.unwrap_or(w.first), w.incomplete)
}
HierarchyDirection::Outgoing => (query().await?, None),
+1 -6
Переглянути файл
@@ -116,8 +116,7 @@ impl LspManager {
/// Runs `query` on `t`; then again with the project files that mention the
/// symbol at `pos` outside `covered(first)` and the server's analysis scope opened.
/// A first answer that is empty while the server indexes is retried once
/// indexing ends. `first_found` gets the first answer before the other files are searched.
#[allow(clippy::too_many_arguments)]
/// indexing ends.
pub(crate) async fn widened<R, F, Fut>(
&self,
snap: &DocSnap,
@@ -126,7 +125,6 @@ impl LspManager {
cancel: &CancellationToken,
query: F,
covered: impl Fn(&R) -> Vec<PathBuf>,
first_found: impl Fn(&R),
) -> IdeResult<Widened<R>>
where
F: Fn() -> Fut,
@@ -158,9 +156,6 @@ impl LspManager {
if candidates.limit_hit {
incomplete = incomplete.or(Some(ReferencesIncomplete::TooManyFiles));
}
// Opening the other candidate files and asking again takes the server a while: what it
// found in its own scope can be shown meanwhile.
first_found(&first);
let known: HashSet<PathBuf> = covered(&first).into_iter().chain([snap.path.clone()]).collect();
let files: Vec<PathBuf> = candidates.files.into_iter().filter(|f| !known.contains(f)).collect();
let mut files = self.files_beyond_scope(t, files, cancel).await;
Loaded 100 of 738 files, more files were not shown because too many files have changed in this diff. Show more