дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Порівняти коміти
149
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
55464314bb | ||
|
|
177babf298 | ||
|
|
406cf4e474 | ||
|
|
bc019ace9d | ||
|
|
55c9787996 | ||
|
|
5b1e4a31f2 | ||
|
|
f3582403f3 | ||
|
|
a5f958d544 | ||
|
|
4aeeb4d883 | ||
|
|
15f3eadcf1 | ||
|
|
ae9804bc8b | ||
|
|
644a380616 | ||
|
|
4a41b14992 | ||
|
|
551328c901 | ||
|
|
54ce7ac6f8 | ||
|
|
a33c46465b | ||
|
|
b747e81cb6 | ||
|
|
24fdbb54db | ||
|
|
535f7584ee | ||
|
|
49e26d1de1 | ||
|
|
40fb4923e6 | ||
|
|
8fefbc1c82 | ||
|
|
059dca5b34 | ||
|
|
277464e93b | ||
|
|
a6e9c79c96 | ||
|
|
1a6c0dff36 | ||
|
|
73708c8e7d | ||
|
|
d2cc2093b1 | ||
|
|
ff9a48eb0e | ||
|
|
24e42bb302 | ||
|
|
67c00a986a | ||
|
|
896ec3b924 | ||
|
|
2f18cacbaf | ||
|
|
2cad48b401 | ||
|
|
1f8cf7e3a8 | ||
|
|
978bcd6dd4 | ||
|
|
a1d406beb3 | ||
|
|
b46c467fc3 | ||
|
|
091dd85ef0 | ||
|
|
4eab243ef2 | ||
|
|
56c6e8090a | ||
|
|
bd3f0cb651 | ||
|
|
fe1838aca6 | ||
|
|
9737adb66c | ||
|
|
1c4aa9f1b2 | ||
|
|
4335cf46af | ||
|
|
f2b602a48e | ||
|
|
b4c8a6708c | ||
|
|
8e36365bc4 | ||
|
|
b5a8a77cfa | ||
|
|
70a4fbec3a | ||
|
|
b640078b11 | ||
|
|
e186f74782 | ||
|
|
25d0294947 | ||
|
|
5d26e44c0e | ||
|
|
6e327e6ffc | ||
|
|
81d1285e38 | ||
|
|
8a92a7b10c | ||
|
|
3eb4b54525 | ||
|
|
5dd0565456 | ||
|
|
b16d485f35 | ||
|
|
34739e181d | ||
|
|
2cf5f5369f | ||
|
|
b27ef431a6 | ||
|
|
166ef2dffa | ||
|
|
ed57059cad | ||
|
|
31e7b420ae | ||
|
|
70a7932939 | ||
|
|
8b1ca86526 | ||
|
|
16e160f5b9 | ||
|
|
0d3e9a27cc | ||
|
|
3a31ec25aa | ||
|
|
693b24bf65 | ||
|
|
6304811ac9 | ||
|
|
d55f116add | ||
|
|
d62c978032 | ||
|
|
5f452a8e36 | ||
|
|
7992063ef2 | ||
|
|
34cb6a45cd | ||
|
|
e670463b8e | ||
|
|
2b0cc6b733 | ||
|
|
152f7123a0 | ||
|
|
a223f3e6b2 | ||
|
|
9c73f7d784 | ||
|
|
9ad7f91c04 | ||
|
|
5ec05b3aca | ||
|
|
26688a79f7 | ||
|
|
c6428a8e4c | ||
|
|
9e3077753d | ||
|
|
7d33b470f2 | ||
|
|
5bfdaf679d | ||
|
|
ab08c3d245 | ||
|
|
1ee5f0d71d | ||
|
|
d2686f922d | ||
|
|
35682aadc2 | ||
|
|
35529ddd64 | ||
|
|
f5abe8b509 | ||
|
|
c1cde544fb | ||
|
|
40ea4267bd | ||
|
|
377e900e84 | ||
|
|
74b2b5113b | ||
|
|
68a322edad | ||
|
|
ba04c34710 | ||
|
|
cddf57d4c7 | ||
|
|
8c82d9924c | ||
|
|
a050a8054f | ||
|
|
a12999c3d5 | ||
|
|
309a805794 | ||
|
|
ac9198dd52 | ||
|
|
7eed207163 | ||
|
|
952c67f752 | ||
|
|
e4d0a36b5a | ||
|
|
d1f311d2a3 | ||
|
|
52e81f8158 | ||
|
|
7cca129a8e | ||
|
|
006ab617e8 | ||
|
|
fbc4c51c8f | ||
|
|
6f68b8659d | ||
|
|
f49782daaf | ||
|
|
69374c8868 | ||
|
|
7c9fa1dc3b | ||
|
|
c412491972 | ||
|
|
6fbbab6c6f | ||
|
|
eb2be13a1e | ||
|
|
7fd5ad50b8 | ||
|
|
b21be36bf8 | ||
|
|
35e4b4cc92 | ||
|
|
f1876f1260 | ||
|
|
703c33a089 | ||
|
|
16def0187c | ||
|
|
d61ffa5430 | ||
|
|
9fcd7c1468 | ||
|
|
a6aa26ea2a | ||
|
|
ea4ac8cc6e | ||
|
|
f62b89fccc | ||
|
|
3edc7ee1a0 | ||
|
|
42b6363646 | ||
|
|
7ff13704ff | ||
|
|
a53e25f398 | ||
|
|
ade8bdd36a | ||
|
|
0e221ba78a | ||
|
|
5f31f1292a | ||
|
|
5de7b0964e | ||
|
|
61418e9cb5 | ||
|
|
fd22254194 | ||
|
|
e666bb2e33 | ||
|
|
4f2d85007b | ||
|
|
6e5f91f7fd | ||
|
|
e38599b82b |
No files matched your search
@@ -7,7 +7,7 @@ BASEDPYRIGHT=1.40.2
|
||||
RUFF=0.17.3
|
||||
GOPLS=v0.24.0
|
||||
JDTLS=1.63.0-202610191322
|
||||
KOTLIN_LSP=271.2085.0
|
||||
KOTLIN_LSP=271.3588.0
|
||||
GRADLE=8.14.3
|
||||
INTELEPHENSE=1.18.5
|
||||
# The JDK projects compile against (JAVA_HOME): library navigation opens its sources.
|
||||
|
||||
@@ -47,7 +47,7 @@ on:
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
- "src-tauri/icons/128x128.png"
|
||||
- "src/assets/openidea-logo.png"
|
||||
- "smoke/**"
|
||||
- "vite.config.ts"
|
||||
- "tsconfig.json"
|
||||
@@ -111,7 +111,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-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|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|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|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.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
|
||||
|
||||
Створено
@@ -6827,6 +6827,7 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"security-framework",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<p align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
|
||||
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
Знакомая вам IDE, переписанная на Rust.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · Русский
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Скачать</b></a>
|
||||
·
|
||||
<a href="https://openidea.sh">Документация</a>
|
||||
·
|
||||
<a href="#сравнение-производительности">Производительность</a>
|
||||
·
|
||||
<a href="#плагины">Плагины</a>
|
||||
·
|
||||
<a href="#сообщество">Сообщество</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
|
||||
OpenIDEA переносит привычные для пользователей IntelliJ IDEA сочетания клавиш, окна инструментов
|
||||
и глобальный поиск в нативное приложение с ядром на Rust.
|
||||
|
||||
Редактор, средства анализа кода, отладчик, Git, терминал, клиенты для работы с базами данных и HTTP.
|
||||
Поддержка более 60 языков. Сборки для macOS, Windows и Linux.
|
||||
|
||||
На macOS IDE также можно установить через Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Сравнение производительности
|
||||
|
||||
Открытие проекта [freqtrade](https://github.com/freqtrade/freqtrade) (Python, около 770 файлов)
|
||||
с прогретыми кешами, медиана пяти запусков:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| ---------------------------------------------- | ------------------- | ---------------------- |
|
||||
| Появление окна с проектом | **0,9 с** | 3,1 с |
|
||||
| Готовность (нагрузка на CPU стабилизировалась) | **1,1 с** | 13,2 с |
|
||||
| Память (USS, все процессы) | **169 МБ** | 2011 МБ |
|
||||
| Процессорное время до готовности | **2,4 с** | 47,9 с |
|
||||
| Загрузка CPU в простое | **4 %** одного ядра | 7 % одного ядра |
|
||||
| Завершение работы | **0,3 с** | 5,9 с |
|
||||
|
||||
В тесте использовались релизная сборка OpenIDEA из ветки `main` и IDEA с настройками и плагинами по умолчанию.
|
||||
Окружение: Windows 11, 32-ядерный процессор AMD, 62 ГБ оперативной памяти.
|
||||
IDEA глубже анализирует Python-код, поэтому к моменту готовности обе IDE выполняют разный объём работы.
|
||||
Измерения обеих IDE проводились извне по одной методике: с помощью
|
||||
[`perf/compare`](perf/compare) можно повторить тест на своём компьютере со своими проектами.
|
||||
|
||||
## Плагины
|
||||
|
||||
Плагины добавляют действия, автодополнение кода, быстрые исправления, окна инструментов, пользовательские редакторы,
|
||||
темы оформления, значки файлов и поддержку языков. Они работают как компоненты WebAssembly в изолированной среде;
|
||||
для тем оформления, тем значков и языков писать код не нужно.
|
||||
|
||||
Плагины можно установить в разделе «Настройки › Плагины» (Settings › Plugins) или создать собственный командой
|
||||
`openidea-plugin new`. См. [руководство по созданию плагинов OpenIDEA](https://openidea.sh/en/plugins)
|
||||
и [официальные плагины](plugins/official). API плагинов пока доступен в предварительной версии.
|
||||
|
||||
## Сообщество
|
||||
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): вопросы, обратная связь и новости о релизах.
|
||||
- Группа WeChat: отсканируйте QR-код, чтобы присоединиться.
|
||||
|
||||
<img src=".github/assets/wechat-group-5.png" alt="QR-код группы WeChat" width="200">
|
||||
|
||||
- Как внести вклад: см. [CONTRIBUTING.md](CONTRIBUTING.md) и [документацию для участников проекта](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
## Лицензия
|
||||
|
||||
[Apache 2.0](LICENSE). Включённые в поставку сторонние ресурсы перечислены в [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
<sub>OpenIDEA не связан с JetBrains. IntelliJ IDEA — товарный знак JetBrains s.r.o.</sub>
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · 简体中文
|
||||
<a href="README.md">English</a> · 简体中文 · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
match run_once(shared, spec, prefer_stored, model).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::is_copilot_provider(spec.base_id())
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
@@ -53,7 +53,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
let cwd = dunce::canonicalize(&root).unwrap_or(root);
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.base_id().to_owned(), ..Default::default() });
|
||||
let client = Dialect::wrap(updates.clone());
|
||||
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(|_| {});
|
||||
let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr)
|
||||
@@ -69,7 +69,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(discovery_error)?;
|
||||
let mut options = config::options_of(&new);
|
||||
config::add_client_options(&launch.id, &mut options);
|
||||
config::add_client_options(launch.base_id(), &mut options);
|
||||
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
|
||||
let mut levels = BTreeMap::new();
|
||||
let has_config = new.get("configOptions").is_some_and(Value::is_array);
|
||||
@@ -119,7 +119,7 @@ async fn run_once(
|
||||
.commands
|
||||
.lock()
|
||||
.clone()
|
||||
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id)));
|
||||
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, launch.base_id())));
|
||||
Ok::<_, String>(Discovered { config: options, commands, levels })
|
||||
};
|
||||
let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await;
|
||||
|
||||
@@ -680,7 +680,7 @@ async fn discover(
|
||||
Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
&spec.id,
|
||||
spec.base_id(),
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
@@ -704,7 +704,7 @@ async fn discover(
|
||||
Ok(found) => Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
&spec.id,
|
||||
spec.base_id(),
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
|
||||
@@ -146,6 +146,10 @@ pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
|
||||
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
|
||||
}
|
||||
|
||||
pub(crate) fn is_approval_option_id(id: &str) -> bool {
|
||||
id == CURSOR_APPROVAL || matches!(id, "mode" | "allow_all" | "permissions" | "approval" | "approval_policy")
|
||||
}
|
||||
|
||||
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
|
||||
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
|
||||
}
|
||||
@@ -425,15 +429,19 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
id == "fast"
|
||||
}
|
||||
|
||||
/// Whether a raw config option id belongs to the selected model rather than the provider.
|
||||
pub(crate) fn is_per_model_option_id(id: &str) -> bool {
|
||||
matches!(id, "effort" | "reasoning_effort" | "thinking" | "reasoning" | "service_tier")
|
||||
|| is_fast_option(id)
|
||||
|| is_context_option(id)
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
|
||||
/// rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
|| o.id == "service_tier"
|
||||
|| is_per_model_option_id(&o.id)
|
||||
}
|
||||
|
||||
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
|
||||
|
||||
@@ -79,6 +79,12 @@ pub fn login_launch_without_project(
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
|
||||
}
|
||||
|
||||
/// The built-in agent `id` is an instance of, or `id` itself, outside a project.
|
||||
pub fn base_provider_id_without_project(custom_agents_dir: Option<&Path>, id: &str) -> String {
|
||||
let specs = provider::load(custom_agents_dir, None);
|
||||
specs.iter().find(|p| p.id == id).map_or(id, |p| p.base_id()).to_owned()
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status_with(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
@@ -231,11 +237,13 @@ impl AgentPaths {
|
||||
fn provider_specs(&self) -> Vec<provider::ProviderSpec> {
|
||||
let mut specs = provider::load(self.custom_agents_dir.as_deref(), self.env_secrets.as_deref());
|
||||
for spec in &mut specs {
|
||||
if spec.source == AgentSource::Builtin
|
||||
&& let Some(pkg) = cli_update::package(&spec.id)
|
||||
&& let Some(builtin) = provider::builtin_spec(&spec.id)
|
||||
// An instance launching its base's command shares the base's managed install.
|
||||
let base = spec.base_id().to_owned();
|
||||
if (spec.source == AgentSource::Builtin || spec.base.is_some())
|
||||
&& let Some(pkg) = cli_update::package(&base)
|
||||
&& let Some(builtin) = provider::builtin_spec(&base)
|
||||
&& spec.command == builtin.command
|
||||
&& let Some(link) = cli_update::managed_cli(&self.cli_dir.join(&spec.id), pkg, &spec.command)
|
||||
&& let Some(link) = cli_update::managed_cli(&self.cli_dir.join(&base), pkg, &spec.command)
|
||||
&& !provider::installed_with_env(&spec.command, &spec.env)
|
||||
{
|
||||
spec.managed_cli = link.to_str().map(str::to_owned);
|
||||
@@ -397,6 +405,11 @@ impl Shared {
|
||||
self.providers.read().iter().find(|p| p.id == id).cloned()
|
||||
}
|
||||
|
||||
/// The built-in id agent `id` is an instance of, or else `id` itself.
|
||||
fn base_id(&self, id: &str) -> String {
|
||||
self.providers.read().iter().find(|p| p.id == id).map_or(id, |p| p.base_id()).to_owned()
|
||||
}
|
||||
|
||||
fn env_secrets(&self) -> Option<&dyn EnvSecrets> {
|
||||
self.paths.env_secrets.as_deref()
|
||||
}
|
||||
@@ -420,7 +433,7 @@ impl Shared {
|
||||
|
||||
async fn probe_network(&self, provider: &str) -> bool {
|
||||
let hook = self.network_probe_hook.read().clone();
|
||||
let provider = provider.to_owned();
|
||||
let provider = self.base_id(provider);
|
||||
tokio::task::spawn_blocking(move || match hook {
|
||||
Some(hook) => hook(&provider),
|
||||
None => default_network_probe(&provider),
|
||||
@@ -511,7 +524,7 @@ impl Shared {
|
||||
fn config_for_new_task(&self, mut config: Vec<AgentConfigOption>, provider: &str) -> Vec<AgentConfigOption> {
|
||||
// Model-specific options are offered separately, never as provider-wide defaults.
|
||||
config.retain(|o| !config::is_per_model_option(o));
|
||||
config::add_client_options(provider, &mut config);
|
||||
config::add_client_options(&self.base_id(provider), &mut config);
|
||||
let hook = self.new_task_approvals.read().clone();
|
||||
if hook.is_some_and(|ask| ask() == ide_core::settings::NewTaskApprovals::Ask) {
|
||||
config::ask_for_approvals(&mut config);
|
||||
@@ -526,8 +539,9 @@ impl Shared {
|
||||
mut levels: BTreeMap<String, Vec<AgentConfigOption>>,
|
||||
provider: &str,
|
||||
) -> BTreeMap<String, Vec<AgentConfigOption>> {
|
||||
let base = self.base_id(provider);
|
||||
for options in levels.values_mut() {
|
||||
config::apply_model_defaults(provider, options);
|
||||
config::apply_model_defaults(&base, options);
|
||||
}
|
||||
levels
|
||||
}
|
||||
@@ -1306,10 +1320,20 @@ impl AgentManager {
|
||||
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
|
||||
pub fn providers(&self) -> Vec<AgentProvider> {
|
||||
let specs = self.shared.paths.provider_specs();
|
||||
{
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
let old = prev.iter().find(|p| &p.id == id);
|
||||
let new = specs.iter().find(|p| &p.id == id);
|
||||
matches!((old, new), (Some(a), Some(b)) if a.executable() == b.executable() && a.args == b.args && a.env == b.env)
|
||||
});
|
||||
*prev = specs.clone();
|
||||
}
|
||||
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
|
||||
specs
|
||||
.iter()
|
||||
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
|
||||
.map(|p| {
|
||||
@@ -1329,19 +1353,12 @@ impl AgentManager {
|
||||
info.commands = self.shared.known_commands(&p.id);
|
||||
info
|
||||
})
|
||||
.collect();
|
||||
drop(terminal_auth);
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
let old = prev.iter().find(|p| &p.id == id);
|
||||
let new = specs.iter().find(|p| &p.id == id);
|
||||
matches!((old, new), (Some(a), Some(b)) if a.executable() == b.executable() && a.args == b.args && a.env == b.env)
|
||||
});
|
||||
*prev = specs.clone();
|
||||
drop(probes);
|
||||
drop(prev);
|
||||
list
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The built-in id agent `id` is an instance of, or else `id` itself.
|
||||
pub fn base_provider_id(&self, id: &str) -> String {
|
||||
self.shared.base_id(id)
|
||||
}
|
||||
|
||||
/// Resolves the interactive sign-in command for agent `id`.
|
||||
@@ -1386,7 +1403,7 @@ impl AgentManager {
|
||||
provider::set_builtin_additional_args(dir, self.shared.env_secrets(), id, args)
|
||||
}
|
||||
|
||||
/// Sets the environment variables built-in `id` starts with; empty clears them.
|
||||
/// Sets the environment variables built-in `id` (or an instance of one) starts with; empty clears them.
|
||||
pub fn set_builtin_env(&self, id: &str, env: std::collections::BTreeMap<String, String>) -> IdeResult<()> {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
@@ -1396,12 +1413,14 @@ impl AgentManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
/// Saves a new custom ACP agent, or an instance of a built-in agent, through its agent file.
|
||||
pub fn save_custom_agent(&self, input: CustomAgentInput) -> IdeResult<()> {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::save_custom(&dir, self.shared.env_secrets(), &input)
|
||||
provider::save_custom(&dir, self.shared.env_secrets(), &input)?;
|
||||
*self.shared.providers.write() = self.shared.paths.provider_specs();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes a custom agent's file (registry installs go through `registry_remove`).
|
||||
@@ -1409,7 +1428,10 @@ impl AgentManager {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::remove_custom(&dir, self.shared.env_secrets(), id)
|
||||
provider::remove_custom(&dir, self.shared.env_secrets(), id)?;
|
||||
*self.shared.providers.write() = self.shared.paths.provider_specs();
|
||||
self.shared.paths.catalogs.evict_if_idle(&self.shared, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Imports a JetBrains `acp.json` file's `agent_servers` entries as custom agents.
|
||||
@@ -1490,23 +1512,26 @@ impl AgentManager {
|
||||
}
|
||||
offered = self.shared.known_commands(&provider);
|
||||
}
|
||||
for command in builtin_commands(&provider) {
|
||||
let base_id = self.shared.base_id(&provider);
|
||||
for command in builtin_commands(&base_id) {
|
||||
if !offered.iter().any(|c| c.name == command.name) {
|
||||
offered.push(command);
|
||||
}
|
||||
}
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
if provider == "hermes" || provider.starts_with("hermes-") {
|
||||
if base_id == "hermes" || provider.starts_with("hermes-") {
|
||||
let hermes_home = home.clone();
|
||||
let hermes_provider = provider.clone();
|
||||
let hermes_base = base_id.clone();
|
||||
let found = blocking(move || {
|
||||
let profile =
|
||||
hermes::root(hermes_home.as_deref()).and_then(|root| hermes::profile_home(&root, &hermes_provider));
|
||||
let profile = hermes::root(hermes_home.as_deref()).and_then(|root| {
|
||||
hermes::profile_home(&root, &hermes_provider).or_else(|| hermes::profile_home(&root, &hermes_base))
|
||||
});
|
||||
Ok(profile.map(|p| skills::hermes(&p)).unwrap_or_default())
|
||||
})
|
||||
.await?;
|
||||
offered = skills::merge(offered, found);
|
||||
} else if provider == "claude" || provider == "claude-acp" {
|
||||
} else if base_id == "claude" || base_id == "claude-acp" {
|
||||
let claude_cwd = cwd.clone();
|
||||
let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?;
|
||||
offered = skills::merge(offered, found);
|
||||
@@ -1527,7 +1552,7 @@ impl AgentManager {
|
||||
let plugin_dirs = policy.plugin_dirs;
|
||||
let indexed_skill_files = policy.indexed_skill_files;
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
let cmd_provider = provider.clone();
|
||||
let cmd_provider = base_id.clone();
|
||||
blocking(move || {
|
||||
let mut p_pol = plug_policy;
|
||||
if p_pol.workspace_roots.is_empty() {
|
||||
@@ -1896,7 +1921,7 @@ impl AgentManager {
|
||||
.map(|h| h())
|
||||
.unwrap_or(ide_core::settings::NewTaskApprovals::Bypass);
|
||||
let mode = Some(meta.permissions.unwrap_or_default());
|
||||
config::clamp_automation_permissions(&spec.id, mode, interactive, &mut config, &mut wanted);
|
||||
config::clamp_automation_permissions(spec.base_id(), mode, interactive, &mut config, &mut wanted);
|
||||
}
|
||||
let now = now_ms();
|
||||
// Copies of the files the user had changed already, for rolling back the task's changes to them.
|
||||
@@ -2050,6 +2075,11 @@ impl AgentManager {
|
||||
s.busy = true;
|
||||
s.pending_prompt = Some(prompt.clone());
|
||||
s.active_scheduled_turn = scheduled.clone();
|
||||
// A run watcher reads the status before the spawned turn shows its prompt, and
|
||||
// would take the previous turn's `Ready` for the end of this one.
|
||||
if scheduled.is_some() {
|
||||
s.change_status(AgentStatus::Starting, None);
|
||||
}
|
||||
Some((prompt, scheduled, epoch))
|
||||
}
|
||||
};
|
||||
@@ -2324,10 +2354,16 @@ impl AgentManager {
|
||||
let epoch = self.shared.shutdown_epoch();
|
||||
// A Codex fork must be opened by its own task: the creating app-server owns its writer.
|
||||
// It can also fork a recorded thread whose writer is held by another process.
|
||||
let codex_source = {
|
||||
let (source_provider, source_session) = {
|
||||
let s = source.state.lock();
|
||||
(s.task.provider == "codex").then(|| s.session_id.clone()).flatten()
|
||||
(s.task.provider.clone(), s.session_id.clone())
|
||||
};
|
||||
let codex_source = source
|
||||
.shared
|
||||
.spec(&source_provider)
|
||||
.is_some_and(|spec| spec.driver == provider::Driver::Codex)
|
||||
.then_some(source_session)
|
||||
.flatten();
|
||||
let live = if codex_source.is_none() {
|
||||
Some(source.ensure_session(epoch).await.map_err(IdeError::internal)?)
|
||||
} else {
|
||||
@@ -2349,10 +2385,11 @@ impl AgentManager {
|
||||
let t = &s.task;
|
||||
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
|
||||
};
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides, None);
|
||||
let base_id = source.shared.base_id(&provider_id);
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&base_id, &live.init, &mcp_overrides, None);
|
||||
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
|
||||
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
|
||||
let memory_delivery = source.stage_memory(&provider_id, &cwd).await;
|
||||
let memory_delivery = source.stage_memory(&base_id, &cwd).await;
|
||||
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
|
||||
let reply: Value = live
|
||||
.peer
|
||||
@@ -3738,6 +3775,13 @@ impl AgentManager {
|
||||
self.shared.sinks.write().clear();
|
||||
}
|
||||
|
||||
/// Stops sending events to UI sinks while keeping internal host subscribers (`__`-prefixed,
|
||||
/// such as automation run watchers and peer bridges) attached when retaining an `AgentManager`
|
||||
/// headlessly across window close.
|
||||
pub fn detach_ui_sinks(&self) {
|
||||
self.shared.sinks.write().retain(|key, _| key.starts_with("__"));
|
||||
}
|
||||
|
||||
/// Stops every agent (project closed or trust revoked).
|
||||
pub fn shutdown(&self) {
|
||||
self.shutdown_with(AgentShutdownReason::default());
|
||||
@@ -3885,7 +3929,7 @@ impl Task {
|
||||
/// The task from the parts of `file` other than its history, which `history` holds.
|
||||
fn assemble(file: TaskFile, history: StoredHistory, adopt: bool, shared: Arc<Shared>) -> Arc<Self> {
|
||||
let mut task = file.task;
|
||||
config::add_client_options(&task.provider, &mut task.config);
|
||||
config::add_client_options(&shared.base_id(&task.provider), &mut task.config);
|
||||
let mut wanted = file.wanted;
|
||||
let mut pending_model = file.pending_switch.or_else(|| {
|
||||
let id = file.pending_model?;
|
||||
@@ -4488,8 +4532,24 @@ impl Task {
|
||||
.as_ref()
|
||||
.map(|h| h())
|
||||
.unwrap_or(ide_core::settings::NewTaskApprovals::Bypass);
|
||||
let (provider, to_apply) = {
|
||||
let base = {
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
self.shared.base_id(&provider)
|
||||
};
|
||||
let mut non_approval_choices = {
|
||||
let mut s = self.state.lock();
|
||||
let model_opt_id =
|
||||
s.task.config.iter().find(|o| o.category.as_deref() == Some("model")).map(|o| o.id.clone());
|
||||
let current_model = model_of(&s.task.config);
|
||||
let switching_model = extra_choices.iter().any(|c| {
|
||||
(model_opt_id.as_deref() == Some(c.id.as_str()) || c.id == "model")
|
||||
&& current_model.as_deref() != Some(c.value.as_str())
|
||||
});
|
||||
if switching_model {
|
||||
let per_model_ids: HashSet<String> =
|
||||
s.task.config.iter().filter(|o| config::is_per_model_option(o)).map(|o| o.id.clone()).collect();
|
||||
s.wanted.retain(|c| !per_model_ids.contains(&c.id) && !config::is_per_model_option_id(&c.id));
|
||||
}
|
||||
for choice in extra_choices {
|
||||
if let Some(existing) = s.wanted.iter_mut().find(|c| c.id == choice.id) {
|
||||
existing.value = choice.value.clone();
|
||||
@@ -4497,27 +4557,108 @@ impl Task {
|
||||
s.wanted.push(choice.clone());
|
||||
}
|
||||
}
|
||||
let provider = s.task.provider.clone();
|
||||
let mut target_config = s.task.config.clone();
|
||||
let mut target_wanted = s.wanted.clone();
|
||||
config::clamp_automation_permissions(&provider, mode, interactive, &mut target_config, &mut target_wanted);
|
||||
let mut diffs = Vec::new();
|
||||
for next_opt in &target_config {
|
||||
let prev_cur = s.task.config.iter().find(|o| o.id == next_opt.id).and_then(|o| o.current.as_deref());
|
||||
if let Some(next_val) = next_opt.current.as_deref()
|
||||
&& prev_cur != Some(next_val)
|
||||
&& next_opt.values.iter().any(|v| v.value == next_val)
|
||||
{
|
||||
diffs.push((next_opt.id.clone(), next_val.to_owned()));
|
||||
}
|
||||
}
|
||||
config::clamp_automation_permissions(&base, mode, interactive, &mut target_config, &mut target_wanted);
|
||||
s.wanted = target_wanted;
|
||||
(provider, diffs)
|
||||
let non_approval: Vec<AgentConfigChoice> = extra_choices
|
||||
.iter()
|
||||
.filter(|c| {
|
||||
let known_approval =
|
||||
s.task.config.iter().find(|o| o.id == c.id).is_some_and(config::is_approval_option);
|
||||
!known_approval && !config::is_approval_option_id(&c.id)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
non_approval
|
||||
};
|
||||
self.persist();
|
||||
|
||||
let live = self.live.lock().clone().filter(|l| !l.peer.is_closed());
|
||||
if let Some(live) = live {
|
||||
// Apply model first so updated per-model configOptions (effort, context_tier, fast…)
|
||||
// are merged before applying per-model choices.
|
||||
{
|
||||
let s = self.state.lock();
|
||||
non_approval_choices.sort_by_key(|c| match s.task.config.iter().find(|o| o.id == c.id) {
|
||||
Some(o) if o.category.as_deref() == Some("model") => 0,
|
||||
Some(o) if config::is_per_model_option(o) => 2,
|
||||
None if c.id == "model" => 0,
|
||||
None if config::is_per_model_option_id(&c.id) => 2,
|
||||
_ => 1,
|
||||
});
|
||||
}
|
||||
|
||||
for choice in non_approval_choices {
|
||||
let Some(target_opt) = self.state.lock().task.config.iter().find(|o| o.id == choice.id).cloned() else {
|
||||
continue;
|
||||
};
|
||||
if config::is_approval_option(&target_opt) {
|
||||
continue;
|
||||
}
|
||||
let already =
|
||||
target_opt.id != "service_tier" && target_opt.current.as_deref() == Some(choice.value.as_str());
|
||||
if already || !target_opt.values.iter().any(|v| v.value == choice.value) {
|
||||
continue;
|
||||
}
|
||||
{
|
||||
let mut sent = self.config_sent.lock();
|
||||
sent.retain(|(id, _)| id != &choice.id);
|
||||
sent.insert((choice.id.clone(), choice.value.clone()));
|
||||
}
|
||||
let (method, mut params) = config::set_request(&target_opt, &choice.value);
|
||||
params["sessionId"] = json!(live.session);
|
||||
match live.peer.request::<_, Value>(method, params, None).await {
|
||||
Ok(reply) => {
|
||||
let mut s = self.state.lock();
|
||||
if let Some(options) = reply.get("configOptions") {
|
||||
config::merge_update(&mut s.task.config, options);
|
||||
} else {
|
||||
if target_opt.category.as_deref() == Some("model")
|
||||
&& target_opt.current.as_deref() != Some(choice.value.as_str())
|
||||
{
|
||||
s.task.config.retain(|o| !config::is_per_model_option(o));
|
||||
}
|
||||
if let Some(o) = s.task.config.iter_mut().find(|o| o.id == choice.id) {
|
||||
o.current = Some(choice.value.clone());
|
||||
}
|
||||
}
|
||||
s.task.model = model_of(&s.task.config).or(s.task.model.take());
|
||||
sync_usage_context_size(&mut s.task);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"agent task {}: setting automation config {} to {} failed: {}",
|
||||
self.id,
|
||||
choice.id,
|
||||
choice.value,
|
||||
self.describe(e)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recompute approval diffs against the post-model-switch config and enforce strictly.
|
||||
let to_apply = {
|
||||
let mut s = self.state.lock();
|
||||
let mut target_config = s.task.config.clone();
|
||||
let mut target_wanted = s.wanted.clone();
|
||||
config::clamp_automation_permissions(&base, mode, interactive, &mut target_config, &mut target_wanted);
|
||||
let mut diffs = Vec::new();
|
||||
for next_opt in &target_config {
|
||||
let prev_cur =
|
||||
s.task.config.iter().find(|o| o.id == next_opt.id).and_then(|o| o.current.as_deref());
|
||||
if let Some(next_val) = next_opt.current.as_deref()
|
||||
&& prev_cur != Some(next_val)
|
||||
&& next_opt.values.iter().any(|v| v.value == next_val)
|
||||
{
|
||||
diffs.push((next_opt.id.clone(), next_val.to_owned()));
|
||||
}
|
||||
}
|
||||
s.wanted = target_wanted;
|
||||
diffs
|
||||
};
|
||||
|
||||
for (opt_id, val) in to_apply {
|
||||
let Some(target_opt) = self.state.lock().task.config.iter().find(|o| o.id == opt_id).cloned() else {
|
||||
continue;
|
||||
@@ -4543,7 +4684,7 @@ impl Task {
|
||||
}
|
||||
}
|
||||
let current_cfg = self.state.lock().task.config.clone();
|
||||
config::verify_automation_ceiling(&provider, mode, interactive, ¤t_cfg).map_err(IdeError::invalid)?;
|
||||
config::verify_automation_ceiling(&base, mode, interactive, ¤t_cfg).map_err(IdeError::invalid)?;
|
||||
self.approve_pending();
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
@@ -4870,10 +5011,11 @@ impl Task {
|
||||
}
|
||||
|
||||
fn cursor_at_capacity(&self, result: &Result<String, Failure>) -> bool {
|
||||
let s = self.state.lock();
|
||||
if s.task.provider != "cursor" {
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
if self.shared.base_id(&provider) != "cursor" {
|
||||
return false;
|
||||
}
|
||||
let s = self.state.lock();
|
||||
matches!(result, Ok(stop) if stop == "end_turn")
|
||||
&& matches!(
|
||||
s.history.conversation.main.entries.last(),
|
||||
@@ -5195,11 +5337,13 @@ impl Task {
|
||||
/// Adds `prompt` to the running turn when the agent takes that; gives it back otherwise.
|
||||
async fn steer(self: &Arc<Self>, prompt: AgentPrompt) -> Result<(), AgentPrompt> {
|
||||
let live = self.live.lock().clone().filter(|l| l.capabilities.steer && !l.peer.is_closed());
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let cursor = self.shared.base_id(&provider) == "cursor";
|
||||
let running = {
|
||||
let s = self.state.lock();
|
||||
// During Cursor backoff the ACP turn has already ended. Send Now must
|
||||
// cancel the wait and dispatch the new prompt as a turn of its own.
|
||||
s.busy && s.task.status == AgentStatus::Running && !(s.task.provider == "cursor" && s.task.retry.is_some())
|
||||
s.busy && s.task.status == AgentStatus::Running && !(cursor && s.task.retry.is_some())
|
||||
};
|
||||
let Some((live, method)) = live
|
||||
.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images))
|
||||
@@ -5451,11 +5595,13 @@ impl Task {
|
||||
if self.recorded_load_started.load(Ordering::Acquire) || !self.adopts_replay() || self.live.lock().is_some() {
|
||||
return false;
|
||||
}
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let base = self.shared.base_id(&provider);
|
||||
let s = self.state.lock();
|
||||
!s.busy
|
||||
&& s.session_id.is_some()
|
||||
&& s.pending_native_fork.is_none()
|
||||
&& RECORDED_SESSION_AGENTS.contains(&s.task.provider.as_str())
|
||||
&& RECORDED_SESSION_AGENTS.contains(&base.as_str())
|
||||
}
|
||||
|
||||
/// Opens the recorded session in the background, once per run: its replay shows the history
|
||||
@@ -5557,6 +5703,7 @@ impl Task {
|
||||
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
|
||||
let cwd = verified_cwd.as_path();
|
||||
let launch_cwd = cwd.to_path_buf();
|
||||
let base_id = spec.base_id().to_owned();
|
||||
let mut spec = tokio::task::spawn_blocking(move || {
|
||||
spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth())
|
||||
})
|
||||
@@ -5566,10 +5713,10 @@ impl Task {
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
return Err(SessionOpenError { message: "The agent manager shut down.".into(), allow_acp_fallback: false });
|
||||
}
|
||||
let memory_delivery = self.stage_memory(provider_id, cwd).await;
|
||||
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
|
||||
let memory_delivery = self.stage_memory(&base_id, cwd).await;
|
||||
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(&base_id) {
|
||||
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
|
||||
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
|
||||
for name in self.shared.mcp_servers_off_for_session(&base_id, &mcp_overrides) {
|
||||
spec.args.push("--disable-mcp-server".into());
|
||||
spec.args.push(name);
|
||||
}
|
||||
@@ -5645,7 +5792,7 @@ impl Task {
|
||||
})
|
||||
};
|
||||
let mcp_servers = self.shared.mcp_servers_for_session(
|
||||
provider_id,
|
||||
&base_id,
|
||||
&init,
|
||||
&mcp_overrides,
|
||||
mcp_nonce.as_ref().map(|g| g.nonce.as_str()),
|
||||
@@ -5847,7 +5994,7 @@ impl Task {
|
||||
let effective_perm_mode = sched_perm.unwrap_or(auto_perm);
|
||||
(options, wanted, ceiling_active, effective_perm_mode)
|
||||
};
|
||||
config::add_client_options(provider_id, &mut options);
|
||||
config::add_client_options(&base_id, &mut options);
|
||||
let interactive = self
|
||||
.shared
|
||||
.new_task_approvals
|
||||
@@ -5859,13 +6006,7 @@ impl Task {
|
||||
// Compute clamped choices on a scratch copy of `options` so `options[i].current` still
|
||||
// reflects what the CLI reported and the `wanted` loop below sends any needed downgrade!
|
||||
let mut scratch = options.clone();
|
||||
config::clamp_automation_permissions(
|
||||
provider_id,
|
||||
effective_perm_mode,
|
||||
interactive,
|
||||
&mut scratch,
|
||||
&mut wanted,
|
||||
);
|
||||
config::clamp_automation_permissions(&base_id, effective_perm_mode, interactive, &mut scratch, &mut wanted);
|
||||
}
|
||||
// Changing model can replace the effort / context-tier choices; validate those only afterwards.
|
||||
wanted.sort_by_key(|c| {
|
||||
@@ -5880,6 +6021,8 @@ impl Task {
|
||||
match options.iter().find(|o| o.id == c.id) {
|
||||
Some(o) if o.category.as_deref() == Some("model") => 0,
|
||||
Some(o) if config::is_per_model_option(o) => 2,
|
||||
None if c.id == "model" => 0,
|
||||
None if config::is_per_model_option_id(&c.id) => 2,
|
||||
_ => 1,
|
||||
}
|
||||
});
|
||||
@@ -5980,7 +6123,7 @@ impl Task {
|
||||
}
|
||||
}
|
||||
if ceiling_active {
|
||||
config::verify_automation_ceiling(provider_id, effective_perm_mode, interactive, &options)
|
||||
config::verify_automation_ceiling(&base_id, effective_perm_mode, interactive, &options)
|
||||
.map_err(|message| SessionOpenError { message, allow_acp_fallback: false })?;
|
||||
}
|
||||
if self.shared.shut_down_since(epoch) {
|
||||
@@ -6213,6 +6356,7 @@ impl Task {
|
||||
}
|
||||
// Session state (also while `session/load` replays history).
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let base = self.shared.base_id(&provider);
|
||||
let task_changed = {
|
||||
let mut s = self.state.lock();
|
||||
match kind {
|
||||
@@ -6230,7 +6374,7 @@ impl Task {
|
||||
true
|
||||
}
|
||||
"available_commands_update" => {
|
||||
s.task.commands = config::commands_of(update, &provider);
|
||||
s.task.commands = config::commands_of(update, &base);
|
||||
true
|
||||
}
|
||||
"usage_update" => {
|
||||
|
||||
@@ -769,6 +769,12 @@ pub struct AgentProvider {
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
/// The built-in agent this one is an instance of.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
/// A built-in agent, of which another instance can be added.
|
||||
#[serde(default)]
|
||||
pub can_duplicate: bool,
|
||||
/// Environment variables it starts with (from its agent file).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
|
||||
@@ -1876,13 +1882,16 @@ pub struct McpProbeResult {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating a custom ACP agent (always the ACP driver); the id
|
||||
/// becomes the `<config>/agents/<id>.toml` file name.
|
||||
/// Payload for creating a custom ACP agent, or an instance of built-in `base` (which
|
||||
/// launches as its base does when `command` is empty); the id becomes the
|
||||
/// `<config>/agents/<id>.toml` file name.
|
||||
#[derive(Clone, Debug, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CustomAgentInput {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub base: Option<String>,
|
||||
pub command: String,
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
|
||||
@@ -131,6 +131,7 @@ for line in sys.stdin:
|
||||
env: Vec::new(),
|
||||
login_hint: String::new(),
|
||||
source: crate::AgentSource::Builtin,
|
||||
base: None,
|
||||
};
|
||||
let found = discover(spec, tmp.path().to_path_buf()).await.unwrap();
|
||||
let models: Vec<_> = found
|
||||
|
||||
@@ -43,6 +43,8 @@ pub(crate) struct ProviderSpec {
|
||||
/// How to sign in when the agent reports it needs authentication.
|
||||
pub login_hint: String,
|
||||
pub source: AgentSource,
|
||||
/// The built-in agent an instance copies (its identity); `None` for every other agent.
|
||||
pub base: Option<String>,
|
||||
}
|
||||
|
||||
/// `(id, name, driver, command line, sign-in hint)`. npm adapters are pinned so a
|
||||
@@ -108,11 +110,17 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
env: Vec::new(),
|
||||
login_hint: (*hint).into(),
|
||||
source: AgentSource::Builtin,
|
||||
base: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl ProviderSpec {
|
||||
/// The built-in id this agent is an instance of, or else its own id.
|
||||
pub(crate) fn base_id(&self) -> &str {
|
||||
self.base.as_deref().unwrap_or(&self.id)
|
||||
}
|
||||
|
||||
pub(crate) fn executable(&self) -> &str {
|
||||
self.managed_cli.as_deref().unwrap_or(&self.command)
|
||||
}
|
||||
@@ -122,7 +130,7 @@ impl ProviderSpec {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let builtin = builtin_spec(&self.id);
|
||||
let builtin = builtin_spec(self.base_id());
|
||||
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
|
||||
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
|
||||
}
|
||||
@@ -161,7 +169,7 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let is_copilot = is_copilot_provider(self.base_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());
|
||||
@@ -191,7 +199,7 @@ impl ProviderSpec {
|
||||
} else if self.driver != Driver::Acp {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
@@ -217,7 +225,7 @@ impl ProviderSpec {
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
if let Some((separate_cmd, separate_args)) = match self.base_id() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
@@ -231,7 +239,7 @@ impl ProviderSpec {
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id)
|
||||
if let Some(builtin) = builtin_spec(self.base_id())
|
||||
&& !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id))
|
||||
{
|
||||
let args = terminal_auth_args
|
||||
@@ -241,7 +249,7 @@ impl ProviderSpec {
|
||||
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) {
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
@@ -532,7 +540,7 @@ pub(crate) fn sanitize_copilot_env_with(
|
||||
}
|
||||
|
||||
fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String {
|
||||
let Some(builtin) = builtin_spec(&spec.id) else { return spec.login_hint.clone() };
|
||||
let Some(builtin) = builtin_spec(spec.base_id()) else { return spec.login_hint.clone() };
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let Some(rest) = spec.login_hint.strip_prefix(&prefix).filter(|rest| rest.starts_with([' ', '`'])) else {
|
||||
return spec.login_hint.clone();
|
||||
@@ -620,6 +628,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
let builtin = builtin_spec(&spec.id);
|
||||
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
|
||||
Some(AgentCommandReadOnlyReason::Registry)
|
||||
} else if spec.base.is_some() {
|
||||
Some(AgentCommandReadOnlyReason::CustomAgent)
|
||||
} else if let Some(default) = &builtin {
|
||||
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
} else {
|
||||
@@ -649,6 +659,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
cli_install_command: None,
|
||||
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(),
|
||||
base: spec.base.clone(),
|
||||
can_duplicate: builtin.is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
thought_levels: BTreeMap::new(),
|
||||
@@ -687,13 +699,17 @@ pub(crate) fn set_builtin_additional_args(
|
||||
})
|
||||
}
|
||||
|
||||
/// The environment built-in `id` starts with, through its agent file (empty clears it).
|
||||
/// The environment built-in `id` (or an instance of one) starts with, through its agent file
|
||||
/// (empty clears it).
|
||||
pub(crate) fn set_builtin_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
if builtin_spec(id).is_none() {
|
||||
return set_instance_env(custom_dir, secrets, id, env);
|
||||
}
|
||||
if id == "copilot" {
|
||||
let file = custom_dir.join("copilot.toml");
|
||||
if file.try_exists()?
|
||||
@@ -725,6 +741,26 @@ pub(crate) fn set_builtin_env(
|
||||
})
|
||||
}
|
||||
|
||||
/// An instance's environment is all its own: never merged with its base's.
|
||||
fn set_instance_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
let id = validated_custom_id(id)?;
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
let mut agent = match CustomAgent::read_with(&file, &id, secrets) {
|
||||
Ok(agent) if agent.registry.is_none() && agent.base.as_deref().is_some_and(|b| builtin_spec(b).is_some()) => {
|
||||
agent
|
||||
}
|
||||
_ => return Err(IdeError::invalid(format!("{id} is not a built-in agent or an instance of one"))),
|
||||
};
|
||||
agent.env = env;
|
||||
agent.write_with(&file, &id, secrets)
|
||||
}
|
||||
|
||||
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
|
||||
fn update_builtin(
|
||||
custom_dir: &Path,
|
||||
@@ -741,6 +777,7 @@ fn update_builtin(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(builtin.name.clone()),
|
||||
base: None,
|
||||
driver: builtin.driver,
|
||||
command: builtin.command.clone(),
|
||||
args: builtin.args.clone(),
|
||||
@@ -786,7 +823,8 @@ fn lock_custom_agents(custom_dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
|
||||
/// Saves a new custom agent; refuses built-in and ACP Registry ids, taken ids
|
||||
/// and an empty command. The id is also the agent file's name, so it must be
|
||||
/// a safe file stem.
|
||||
/// a safe file stem. An instance of a built-in (`base`) may leave the command
|
||||
/// empty to launch as its base does.
|
||||
pub(crate) fn save_custom(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
@@ -796,9 +834,19 @@ pub(crate) fn save_custom(
|
||||
if builtin_spec(&id).is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is a built-in agent; change its command instead")));
|
||||
}
|
||||
if input.command.trim().is_empty() {
|
||||
let base = match input.base.as_deref() {
|
||||
Some(base) => {
|
||||
Some(builtin_spec(base).ok_or_else(|| IdeError::invalid(format!("{base} is not a built-in agent")))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let inherits = input.command.trim().is_empty();
|
||||
if inherits && base.is_none() {
|
||||
return Err(IdeError::invalid("the agent command must not be empty"));
|
||||
}
|
||||
if inherits && !input.args.is_empty() {
|
||||
return Err(IdeError::invalid("an agent without its own command takes no arguments"));
|
||||
}
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
if file.try_exists()? {
|
||||
@@ -811,8 +859,9 @@ pub(crate) fn save_custom(
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some(input.name.clone()),
|
||||
driver: Driver::Acp,
|
||||
command: input.command.clone(),
|
||||
driver: base.as_ref().filter(|_| !inherits).map_or(Driver::Acp, |b| b.driver),
|
||||
command: if inherits { String::new() } else { input.command.clone() },
|
||||
base: base.map(|b| b.id),
|
||||
args: input.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: input.env.clone(),
|
||||
@@ -884,6 +933,7 @@ pub(crate) fn import_acp(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(outcome.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
@@ -926,8 +976,12 @@ pub(crate) fn slugify_id(name: &str) -> String {
|
||||
pub(crate) struct CustomAgent {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// The built-in agent this one is an instance of; without a `command` it launches as the base does.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Driver::is_acp")]
|
||||
pub driver: Driver,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub command: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
@@ -956,9 +1010,13 @@ impl Driver {
|
||||
|
||||
impl CustomAgent {
|
||||
pub(crate) fn read(path: &Path) -> Result<Self, String> {
|
||||
std::fs::read_to_string(path)
|
||||
let agent = std::fs::read_to_string(path)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))?;
|
||||
if agent.command.is_empty() && agent.base.is_none() {
|
||||
return Err("missing field `command`".into());
|
||||
}
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
/// Writes the file atomically (a reader never sees half of it).
|
||||
@@ -1030,7 +1088,8 @@ fn forget_env(secrets: Option<&dyn EnvSecrets>, id: &str, keep: &[String]) {
|
||||
}
|
||||
|
||||
/// Built-in agents, then the `*.toml` agents of `custom_dir`; a custom agent with a
|
||||
/// built-in id replaces it.
|
||||
/// built-in id replaces it. Instances of a built-in (`base`) are resolved last, against
|
||||
/// the built-in as its own file left it, so file order does not matter.
|
||||
pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) -> Vec<ProviderSpec> {
|
||||
let mut specs = builtins();
|
||||
let mut files: Vec<PathBuf> = custom_dir
|
||||
@@ -1042,6 +1101,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
|
||||
.collect();
|
||||
files.sort();
|
||||
let mut instances = Vec::new();
|
||||
for path in files {
|
||||
let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue };
|
||||
let explicit_driver = std::fs::read_to_string(&path)
|
||||
@@ -1055,6 +1115,18 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(base) = agent.base.clone() {
|
||||
if builtin_spec(&id).is_some() {
|
||||
tracing::warn!("skipping agent {}: a built-in agent cannot have a base", path.display());
|
||||
} else if agent.registry.is_some() {
|
||||
tracing::warn!("skipping agent {}: an ACP Registry install cannot have a base", path.display());
|
||||
} else if builtin_spec(&base).is_none() {
|
||||
tracing::warn!("skipping agent {}: {base} is not a built-in agent", path.display());
|
||||
} else {
|
||||
instances.push((id, agent));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let env: Vec<(String, String)> = agent.env.into_iter().collect();
|
||||
let source = match agent.registry {
|
||||
Some(r) => AgentSource::Registry { version: r.version, update: None },
|
||||
@@ -1070,6 +1142,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
env,
|
||||
login_hint: "Sign in with the agent's own command line first.".into(),
|
||||
source,
|
||||
base: None,
|
||||
id,
|
||||
};
|
||||
match specs.iter_mut().find(|s| s.id == spec.id) {
|
||||
@@ -1097,6 +1170,34 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
None => specs.push(spec),
|
||||
}
|
||||
}
|
||||
for (id, agent) in instances {
|
||||
let base = agent.base.expect("instances have a base");
|
||||
let Some(base_spec) = specs.iter().find(|s| s.id == base && s.base.is_none()) else { continue };
|
||||
let (driver, command, args) = if agent.command.is_empty() {
|
||||
(base_spec.driver, base_spec.command.clone(), base_spec.args.clone())
|
||||
} else {
|
||||
(agent.driver, agent.command, agent.args)
|
||||
};
|
||||
let login_hint = base_spec.login_hint.clone();
|
||||
// Copies of one agent follow it, in the order of their file names.
|
||||
let at = specs.iter().rposition(|s| s.base_id() == base).map_or(specs.len(), |i| i + 1);
|
||||
specs.insert(
|
||||
at,
|
||||
ProviderSpec {
|
||||
name: agent.name.unwrap_or_else(|| id.clone()),
|
||||
driver,
|
||||
command,
|
||||
managed_cli: None,
|
||||
args,
|
||||
additional_args_len: 0,
|
||||
env: agent.env.into_iter().collect(),
|
||||
login_hint,
|
||||
source: AgentSource::Custom,
|
||||
base: Some(base),
|
||||
id,
|
||||
},
|
||||
);
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
@@ -1169,6 +1270,7 @@ mod tests {
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some("Google Antigravity".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: bin.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
@@ -1509,6 +1611,7 @@ mod tests {
|
||||
let file = dir.path().join("copilot.toml");
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
@@ -1566,6 +1669,7 @@ mod tests {
|
||||
let path = dir.path().join("codex.toml");
|
||||
CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "amp".into(),
|
||||
args: vec![],
|
||||
@@ -1592,6 +1696,7 @@ mod tests {
|
||||
for field in ["name", "driver", "args", "env", "unnamed"] {
|
||||
let mut agent = CustomAgent {
|
||||
name: Some("Claude Code".into()),
|
||||
base: None,
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
@@ -1646,6 +1751,7 @@ mod tests {
|
||||
let path = dir.path().join("agents").join("amp-acp.toml");
|
||||
let agent = CustomAgent {
|
||||
name: Some("Amp".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
|
||||
args: vec!["acp".into()],
|
||||
@@ -1666,6 +1772,7 @@ mod tests {
|
||||
CustomAgentInput {
|
||||
id: id.into(),
|
||||
name: "Mine".into(),
|
||||
base: None,
|
||||
command: "/opt/mine".into(),
|
||||
args: vec!["acp".into()],
|
||||
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
|
||||
@@ -1887,4 +1994,188 @@ github.com
|
||||
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(""));
|
||||
}
|
||||
|
||||
fn write_agent(dir: &Path, id: &str, text: &str) {
|
||||
std::fs::write(dir.join(format!("{id}.toml")), text).unwrap();
|
||||
}
|
||||
|
||||
fn spec_of(dir: &Path, id: &str) -> Option<ProviderSpec> {
|
||||
load(Some(dir), None).into_iter().find(|s| s.id == id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_inherit_the_base_launch_whatever_the_file_order() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance =
|
||||
"base = \"claude\"\nname = \"Claude Work\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n";
|
||||
// `a-claude` sorts before the base's own file, `z-claude` after it.
|
||||
write_agent(dir.path(), "a-claude", instance);
|
||||
write_agent(dir.path(), "z-claude", instance);
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"claude",
|
||||
"name = \"Claude Code\"\ndriver = \"claude\"\ncommand = \"/opt/claude\"\n[env]\nB = \"1\"\n",
|
||||
);
|
||||
let builtin = builtin_spec("claude").unwrap();
|
||||
for id in ["a-claude", "z-claude"] {
|
||||
let spec = spec_of(dir.path(), id).unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Claude, "/opt/claude"), "{id}");
|
||||
assert_eq!(spec.args, builtin.args);
|
||||
assert_eq!(spec.env, [("CLAUDE_CONFIG_DIR".to_owned(), "/home/me/.claude-work".to_owned())]);
|
||||
assert_eq!(spec.login_hint, builtin.login_hint);
|
||||
assert_eq!(
|
||||
(&spec.source, spec.base.as_deref(), spec.base_id()),
|
||||
(&AgentSource::Custom, Some("claude"), "claude")
|
||||
);
|
||||
assert_eq!(spec.name, "Claude Work");
|
||||
}
|
||||
std::fs::remove_file(dir.path().join("claude.toml")).unwrap();
|
||||
assert_eq!(spec_of(dir.path(), "a-claude").unwrap().command, "claude");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_follow_their_base_in_the_list() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "z-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "a-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "codex-2", "base = \"codex\"\n");
|
||||
write_agent(dir.path(), "mine", "command = \"/opt/mine\"\n");
|
||||
let ids: Vec<String> = load(Some(dir.path()), None).into_iter().map(|s| s.id).collect();
|
||||
let at = |id: &str| ids.iter().position(|i| i == id).unwrap();
|
||||
assert_eq!((at("a-claude"), at("z-claude")), (at("claude") + 1, at("claude") + 2));
|
||||
assert_eq!(at("codex-2"), at("codex") + 1);
|
||||
assert_eq!(at("mine"), ids.len() - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_with_its_own_command_keeps_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"codex-2",
|
||||
"base = \"codex\"\ndriver = \"codex\"\ncommand = \"/opt/codex2\"\nargs = [\"app-server\", \"-v\"]\n",
|
||||
);
|
||||
write_agent(dir.path(), "codex", "driver = \"codex\"\ncommand = \"/opt/codex\"\nargs = [\"app-server\"]\n");
|
||||
let spec = spec_of(dir.path(), "codex-2").unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Codex, "/opt/codex2"));
|
||||
assert_eq!(spec.args, ["app-server", "-v"]);
|
||||
assert_eq!(spec.base.as_deref(), Some("codex"));
|
||||
assert_eq!(spec.login_hint, builtin_spec("codex").unwrap().login_hint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_instances_are_skipped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "unknown-base", "base = \"nope\"\n");
|
||||
write_agent(dir.path(), "first", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "chained", "base = \"first\"\n");
|
||||
write_agent(dir.path(), "codex", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "no-command", "name = \"Nothing\"\n");
|
||||
let specs = load(Some(dir.path()), None);
|
||||
let ids: Vec<&str> = specs.iter().filter(|s| s.source != AgentSource::Builtin).map(|s| s.id.as_str()).collect();
|
||||
assert_eq!(ids, ["first"]);
|
||||
assert_eq!(specs.iter().find(|s| s.id == "codex").unwrap(), &builtin_spec("codex").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_custom_writes_instances() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance = |id: &str, base: &str| CustomAgentInput {
|
||||
base: Some(base.into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
..custom_input(id)
|
||||
};
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"claude\"") && !text.contains("command") && !text.contains("driver"), "{text}");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert_eq!(
|
||||
(spec.driver, spec.command.as_str(), spec.base.as_deref()),
|
||||
(Driver::Claude, "claude", Some("claude"))
|
||||
);
|
||||
|
||||
save_custom(dir.path(), None, &CustomAgentInput { command: "/opt/codex".into(), ..instance("own", "codex") })
|
||||
.unwrap();
|
||||
let own = spec_of(dir.path(), "own").unwrap();
|
||||
assert_eq!((own.driver, own.command.as_str()), (Driver::Codex, "/opt/codex"));
|
||||
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "nope")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "work")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("codex", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &CustomAgentInput { args: vec!["x".into()], ..instance("other", "claude") })
|
||||
.unwrap_err();
|
||||
assert!(!dir.path().join("other.toml").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_describe_their_base() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n");
|
||||
save_custom(dir.path(), None, &custom_input("mine")).unwrap();
|
||||
let info = |id: &str| describe(&spec_of(dir.path(), id).unwrap());
|
||||
let work = info("work");
|
||||
assert_eq!(work.base.as_deref(), Some("claude"));
|
||||
assert!(!work.can_duplicate && !work.can_check_cli_update && !work.command_editable);
|
||||
assert_eq!(work.command_read_only_reason, Some(AgentCommandReadOnlyReason::CustomAgent));
|
||||
assert_eq!(work.login_hint.as_deref(), Some("Run `claude` in a terminal and sign in."));
|
||||
let claude = info("claude");
|
||||
assert!(claude.can_duplicate && claude.base.is_none());
|
||||
let mine = info("mine");
|
||||
assert!(!mine.can_duplicate && mine.base.is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn instances_sign_in_with_their_own_environment() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("claude");
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
write_agent(dir.path(), "claude", &format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()));
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert!(spec.can_sign_in(dir.path(), None));
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert!(launch.args.is_empty());
|
||||
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_environment_is_set_and_forgotten_through_the_secrets() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let secrets = MemorySecrets::default();
|
||||
let s = Some(&secrets as &dyn EnvSecrets);
|
||||
let instance = CustomAgentInput {
|
||||
base: Some("copilot".into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
..custom_input("copilot-work")
|
||||
};
|
||||
save_custom(dir.path(), s, &instance).unwrap();
|
||||
let env = BTreeMap::from([
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.to_owned(), "octo-work".to_owned()),
|
||||
("COPILOT_HOME".to_owned(), "/home/me/.copilot-work".to_owned()),
|
||||
]);
|
||||
set_builtin_env(dir.path(), s, "copilot-work", env.clone()).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("copilot-work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"copilot\"") && !text.contains("octo-work"), "{text}");
|
||||
let spec = load(Some(dir.path()), s).into_iter().find(|p| p.id == "copilot-work").unwrap();
|
||||
assert_eq!(describe(&spec).env, env);
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("octo-work"));
|
||||
assert!(load(Some(dir.path()), s).iter().find(|p| p.id == "copilot").unwrap().env.is_empty());
|
||||
|
||||
save_custom(dir.path(), s, &custom_input("mine")).unwrap();
|
||||
set_builtin_env(dir.path(), s, "mine", env.clone()).unwrap_err();
|
||||
write_agent(dir.path(), "bad-base", "base = \"nope\"\n");
|
||||
set_builtin_env(dir.path(), s, "bad-base", env).unwrap_err();
|
||||
assert!(secrets.keys("agent/bad-base/").is_empty());
|
||||
remove_custom(dir.path(), s, "copilot-work").unwrap();
|
||||
assert!(!dir.path().join("copilot-work.toml").exists());
|
||||
assert!(secrets.keys("agent/copilot-work/").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -587,6 +587,7 @@ fn install_entry_with(
|
||||
}
|
||||
let agent = CustomAgent {
|
||||
name: Some(entry.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
@@ -985,6 +986,7 @@ mod tests {
|
||||
let entries = parse(INDEX).unwrap();
|
||||
let installed = |id: &str, version: &str| CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/x".into(),
|
||||
args: vec![],
|
||||
@@ -1222,6 +1224,7 @@ esac
|
||||
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
|
||||
@@ -663,6 +663,30 @@ async fn subscribers_do_not_replace_or_close_each_other() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detach_ui_sinks_preserves_internal_host_subscribers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let ui = Arc::new(Mutex::new(Vec::new()));
|
||||
let watcher = Arc::new(Mutex::new(Vec::new()));
|
||||
let subscribe = |key: &str, events: &Arc<Mutex<Vec<AgentEvent>>>| {
|
||||
let events = events.clone();
|
||||
mgr.subscribe_as(key, Arc::new(move |event| events.lock().push(event)));
|
||||
};
|
||||
subscribe("main", &ui);
|
||||
subscribe("__automation_watch_run1", &watcher);
|
||||
|
||||
mgr.detach_ui_sinks();
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(ui.lock().len(), 0, "UI window sink must be detached");
|
||||
assert_eq!(watcher.lock().len(), 1, "internal __-prefixed automation watcher must stay attached");
|
||||
|
||||
mgr.detach_sinks();
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(watcher.lock().len(), 1, "detach_sinks clears all remaining sinks");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentManager {
|
||||
// These tests speak to FakeAgent, never an installed CLI, including after a provider reload.
|
||||
let agents = dir.join("agents");
|
||||
@@ -1371,6 +1395,31 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
assert_eq!(names(mgr_a.providers().into_iter().find(|p| p.id == "claude").unwrap().commands), ["review"]);
|
||||
}
|
||||
|
||||
fn instance_of(id: &str, base: &str) -> crate::CustomAgentInput {
|
||||
crate::CustomAgentInput {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
base: Some(base.into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
env: std::collections::BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn instances_offer_the_commands_of_their_base() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent);
|
||||
mgr.save_custom_agent(instance_of("codex-work", "codex")).unwrap();
|
||||
mgr.reload_providers();
|
||||
assert_eq!((mgr.base_provider_id("codex-work"), mgr.base_provider_id("custom")), ("codex".into(), "custom".into()));
|
||||
let names = |commands: Vec<AgentCommand>| commands.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
let instance = names(mgr.commands("codex-work", None).await.unwrap());
|
||||
assert!(instance.iter().any(|name| name == "review"), "{instance:?}");
|
||||
assert_eq!(instance, names(mgr.commands("codex", None).await.unwrap()));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metadata() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -2248,14 +2297,25 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
|
||||
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
|
||||
}
|
||||
|
||||
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
|
||||
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks,
|
||||
/// also when the task runs an instance of Codex.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
|
||||
for provider in ["codex", "codex-work"] {
|
||||
codex_writer_conflict_forks_on_a_new_connection(provider).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn codex_writer_conflict_forks_on_a_new_connection(provider: &str) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let task = {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
if provider != "codex" {
|
||||
mgr.save_custom_agent(instance_of(provider, "codex")).unwrap();
|
||||
mgr.reload_providers();
|
||||
}
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
|
||||
.create(NewAgentTask { prompt: text("again"), provider: provider.into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
@@ -4205,6 +4265,59 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Saving or dropping a Cursor instance on disk is reflected on the very first `providers()` call.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn new_cursor_instance_has_approval_option_on_first_providers_call() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
// Saved through the API: base_provider_id and providers() see it immediately without reload_providers().
|
||||
mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap();
|
||||
assert_eq!(mgr.base_provider_id("cursor-work"), "cursor");
|
||||
// Hand-written on disk: providers() updates its cache before mapping per-provider options.
|
||||
std::fs::write(tmp.path().join("agents/cursor-disk.toml"), "base = \"cursor\"\nname = \"Cursor Disk\"\n").unwrap();
|
||||
let list = mgr.providers();
|
||||
for id in ["cursor-work", "cursor-disk"] {
|
||||
let info = list.iter().find(|p| p.id == id).unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(info.config.iter().any(|o| o.id == config::CURSOR_APPROVAL), "{id}: {:?}", info.config);
|
||||
}
|
||||
}
|
||||
|
||||
/// An instance of Cursor offers Cursor's client-side approval option, and a scheduled turn
|
||||
/// clamps it as it clamps Cursor's own.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn instances_take_the_approval_options_and_automation_clamp_of_their_base() {
|
||||
for provider in ["cursor", "cursor-work"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap();
|
||||
mgr.reload_providers();
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: provider.into(),
|
||||
config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }],
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let approval = || {
|
||||
let snapshot = mgr.task_snapshot(&task.id).unwrap();
|
||||
snapshot.config.iter().find(|o| o.id == config::CURSOR_APPROVAL).and_then(|o| o.current.clone())
|
||||
};
|
||||
assert_eq!(approval().as_deref(), Some("bypass"), "{provider}");
|
||||
let meta = ScheduledTurnMeta {
|
||||
permissions: Some(automation::AutomationPermissionMode::Default),
|
||||
..Default::default()
|
||||
};
|
||||
mgr.prompt_scheduled(&task.id, text("again"), meta).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(approval().as_deref(), Some("ask"), "{provider}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permissions() {
|
||||
for prompt in ["ask", "qwen ask"] {
|
||||
@@ -7604,3 +7717,22 @@ async fn metadata_edits_do_not_bump_updated_ms() {
|
||||
.unwrap();
|
||||
assert_eq!(after_memory.updated_ms, fixed_ms);
|
||||
}
|
||||
|
||||
/// An automation reads the status as soon as its prompt is accepted: the previous turn's
|
||||
/// `Ready` would complete the run before its turn started.
|
||||
#[tokio::test]
|
||||
async fn an_accepted_scheduled_prompt_no_longer_reads_as_ready() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
mgr.prompt_scheduled(&task.id, text("again"), ScheduledTurnMeta::default()).await.unwrap();
|
||||
// The single-threaded runtime has not started the spawned turn yet.
|
||||
assert_eq!(mgr.task_snapshot(&task.id).unwrap().status, AgentStatus::Starting);
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
@@ -569,6 +569,56 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
Ok(vec![step])
|
||||
}
|
||||
|
||||
/// A `dotnet` command the .NET tool window runs on a solution or project file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DotnetCommand {
|
||||
Build,
|
||||
Clean,
|
||||
Restore,
|
||||
}
|
||||
|
||||
/// `dotnet build` / `clean` / `restore` of one solution or project file, followed by `options`
|
||||
/// (`--configuration`, `--framework`, `-p:…`).
|
||||
pub fn dotnet_command_plan(file: &Path, command: DotnetCommand, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
let verb = match command {
|
||||
DotnetCommand::Build => "build",
|
||||
DotnetCommand::Clean => "clean",
|
||||
DotnetCommand::Restore => "restore",
|
||||
};
|
||||
dotnet_file_plan(file, verb, true, options)
|
||||
}
|
||||
|
||||
/// `dotnet publish` of one project file with the publish dialog's `options` (`-p:PublishProfile=…`,
|
||||
/// or `--configuration` / `--runtime` / `--output`).
|
||||
pub fn dotnet_publish_plan(file: &Path, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
dotnet_file_plan(file, "publish", false, options)
|
||||
}
|
||||
|
||||
fn dotnet_file_plan(file: &Path, verb: &str, solutions: bool, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let accepted = match ext.as_str() {
|
||||
"csproj" | "fsproj" | "vbproj" => true,
|
||||
"sln" | "slnx" => solutions,
|
||||
_ => false,
|
||||
};
|
||||
let (Some(dir), Some(name), true) = (file.parent(), file.file_name(), accepted) else {
|
||||
return Err(IdeError::invalid(if solutions {
|
||||
format!("dotnet {verb} needs a solution or a C#, F# or VB project")
|
||||
} else {
|
||||
format!("dotnet {verb} needs a C#, F# or VB project")
|
||||
}));
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
|
||||
}
|
||||
let name = name.to_string_lossy();
|
||||
let mut step = BuildStep::new("dotnet", &[verb, &name, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
|
||||
step.args.extend_from_slice(options);
|
||||
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
|
||||
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet {verb} {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
/// `dotnet format` of a solution or C# / VB project file; `verify` only reports what it would
|
||||
/// change and fails when there is anything.
|
||||
pub fn dotnet_format_plan(file: &Path, verify: bool) -> IdeResult<BuildPlan> {
|
||||
@@ -2324,4 +2374,86 @@ mod tests {
|
||||
assert!(run(true).success, "{target}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_publish_runs_on_one_project_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.csproj", "App.fsproj", "App.vbproj", "Sln.slnx"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
let options = ["-p:PublishProfile=My Folder".to_owned()];
|
||||
for name in ["App.csproj", "App.fsproj", "App.vbproj"] {
|
||||
let plan = super::dotnet_publish_plan(&dir.path().join(name), &options).unwrap();
|
||||
assert_eq!(
|
||||
plan.steps[0].args,
|
||||
["publish", name, "-nologo", "-clp:NoSummary", "-p:PublishProfile=My Folder"]
|
||||
);
|
||||
}
|
||||
for name in ["Sln.slnx", "Missing.csproj"] {
|
||||
assert!(super::dotnet_publish_plan(&dir.path().join(name), &[]).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_commands_run_on_one_solution_or_project_file() {
|
||||
use super::DotnetCommand;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.csproj", "Sln.sln", "Sln.slnx", "notes.txt"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
let options = ["--configuration".to_owned(), "Release".to_owned()];
|
||||
for (name, command, verb) in [
|
||||
("Sln.sln", DotnetCommand::Build, "build"),
|
||||
("Sln.slnx", DotnetCommand::Clean, "clean"),
|
||||
("App.csproj", DotnetCommand::Restore, "restore"),
|
||||
] {
|
||||
let plan = super::dotnet_command_plan(&dir.path().join(name), command, &options).unwrap();
|
||||
assert_eq!(plan.title, format!("dotnet {verb} {name}"));
|
||||
assert_eq!(plan.steps[0].args, [verb, name, "-nologo", "-clp:NoSummary", "--configuration", "Release"]);
|
||||
assert_eq!(plan.steps[0].cwd, dir.path());
|
||||
}
|
||||
for name in ["notes.txt", "Missing.sln"] {
|
||||
assert!(super::dotnet_command_plan(&dir.path().join(name), DotnetCommand::Build, &[]).is_err(), "{name}");
|
||||
}
|
||||
assert!(super::dotnet_publish_plan(&dir.path().join("Sln.sln"), &[]).is_err(), "publish takes a project");
|
||||
}
|
||||
|
||||
/// The real `dotnet publish` (`-- --ignored`): publishes, reports compile errors, and stops
|
||||
/// when cancelled.
|
||||
#[test]
|
||||
#[ignore = "needs the .NET SDK"]
|
||||
fn dotnet_publish_publishes_fails_and_cancels_with_the_real_sdk() {
|
||||
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let new = ["new", "console", "-n", "App", "-o", "App"];
|
||||
assert!(std::process::Command::new("dotnet").args(new).current_dir(&root).status().unwrap().success());
|
||||
let project = root.join("App").join("App.csproj");
|
||||
let options = ["--output".to_owned(), "out dir".to_owned()];
|
||||
let plan = super::dotnet_publish_plan(&project, &options).unwrap();
|
||||
|
||||
let published = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert!(published.success);
|
||||
let output = root.join("App").join("out dir").join("App.dll");
|
||||
assert!(output.is_file());
|
||||
|
||||
std::fs::remove_dir_all(root.join("App").join("out dir")).unwrap();
|
||||
let token = CancellationToken::new();
|
||||
let cancel = token.clone();
|
||||
let result = super::run(&root, &plan, &token, &|e| {
|
||||
if matches!(e, BuildEvent::Output { .. }) {
|
||||
cancel.cancel();
|
||||
}
|
||||
});
|
||||
assert!(result.is_err(), "a cancelled publish is not a result");
|
||||
assert!(!output.exists());
|
||||
|
||||
std::fs::write(root.join("App").join("Program.cs"), "nope\n").unwrap();
|
||||
let failed = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert!(!failed.success);
|
||||
assert!(failed.messages.iter().any(|m| m.path.as_ref().is_some_and(|p| p.ends_with("Program.cs"))));
|
||||
}
|
||||
}
|
||||
@@ -103,9 +103,19 @@ pub fn load_linked_with_jdk(
|
||||
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
// The user settings' profiles can be chosen too (`-P` applies to them as well).
|
||||
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
|
||||
if !m.profiles.iter().any(|x| x.id == p.id) {
|
||||
m.profiles.push(p);
|
||||
if let Some(settings_file) = maven::user_settings_file(root, settings) {
|
||||
for p in maven::settings_profiles(&settings_file) {
|
||||
if let Some(existing) = m.profiles.iter_mut().find(|x| x.id == p.id) {
|
||||
existing.active_by_default |= p.active_by_default;
|
||||
} else {
|
||||
m.profiles.push(p);
|
||||
}
|
||||
}
|
||||
let active_in_settings = maven::settings_active_profiles(&settings_file);
|
||||
for existing in &mut m.profiles {
|
||||
if active_in_settings.iter().any(|id| id == &existing.id) {
|
||||
existing.active_by_default = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
@@ -358,6 +368,49 @@ mod tests {
|
||||
assert!(modules(&settings).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_xml_active_profiles_mark_pom_profiles_active_by_default() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir(root.join("child")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version><packaging>pom</packaging>
|
||||
<modules><module>child</module></modules>
|
||||
<profiles>
|
||||
<profile><id>test3</id></profile>
|
||||
<profile><id>dev</id><activation><activeByDefault>TRUE</activeByDefault></activation></profile>
|
||||
</profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("child/pom.xml"),
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version></parent>
|
||||
<artifactId>child</artifactId>
|
||||
<profiles><profile><id>child-default</id><activation><activeByDefault>true</activeByDefault></activation></profile></profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let settings_xml = root.join("settings.xml");
|
||||
std::fs::write(
|
||||
&settings_xml,
|
||||
r#"<settings><activeProfiles><activeProfile>test3</activeProfile></activeProfiles></settings>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let cache = root.join("cache");
|
||||
let settings = ide_core::settings::MavenSettings {
|
||||
user_settings: settings_xml.to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let model = load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap();
|
||||
let flags: Vec<(&str, bool)> = model.profiles.iter().map(|p| (p.id.as_str(), p.active_by_default)).collect();
|
||||
assert!(
|
||||
flags.contains(&("test3", true)),
|
||||
"activeProfile from settings.xml marks POM profile active: {flags:?}"
|
||||
);
|
||||
assert!(flags.contains(&("dev", true)), "case-insensitive activeByDefault: {flags:?}");
|
||||
assert!(flags.contains(&("child-default", true)), "child module activeByDefault: {flags:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_build_systems_and_build_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -43,6 +43,10 @@ pub struct MavenModel {
|
||||
/// Build files changed since that sync.
|
||||
pub stale: bool,
|
||||
pub sync_error: Option<String>,
|
||||
/// The `<activation><jdk>` values of the projects' own POMs that the JDK matches.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub(crate) jdk_activations: std::collections::BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -433,7 +437,9 @@ fn read_raw(project: &Element) -> RawPom {
|
||||
for p in project.list("profiles", "profile") {
|
||||
let mut profile = RawProfile {
|
||||
id: p.text_of("id").unwrap_or_else(|| "default".into()),
|
||||
active_by_default: p.at("activation/activeByDefault").is_some_and(|a| a.text.trim() == "true"),
|
||||
active_by_default: p
|
||||
.at("activation/activeByDefault")
|
||||
.is_some_and(|a| a.text.trim().eq_ignore_ascii_case("true")),
|
||||
activation_jdk: p.at("activation/jdk").map(|jdk| jdk.text.trim().to_owned()).filter(|jdk| !jdk.is_empty()),
|
||||
modules: module_names(p),
|
||||
properties: read_properties(p.child("properties")),
|
||||
@@ -597,12 +603,25 @@ pub fn settings_profiles(settings: &Path) -> Vec<MavenProfile> {
|
||||
if profiles.iter().any(|p| p.id == id) {
|
||||
continue;
|
||||
}
|
||||
let by_default = profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim() == "true");
|
||||
let by_default =
|
||||
profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim().eq_ignore_ascii_case("true"));
|
||||
profiles.push(MavenProfile { active_by_default: by_default || active.contains(&id), id, ..Default::default() });
|
||||
}
|
||||
profiles
|
||||
}
|
||||
|
||||
/// Profile IDs listed under `<activeProfiles>` in `settings.xml` (may refer to profiles defined in POMs).
|
||||
pub fn settings_active_profiles(settings: &Path) -> Vec<String> {
|
||||
let Some(root) = xml::read_text(settings).as_deref().and_then(xml::parse) else {
|
||||
return Vec::new();
|
||||
};
|
||||
root.list("activeProfiles", "activeProfile")
|
||||
.iter()
|
||||
.map(|e| e.text.trim().to_owned())
|
||||
.filter(|id| !id.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `<localRepository>` of a settings file, when it names one: the repository a build
|
||||
/// with `-s <file>` resolves into, which is not necessarily the user's default.
|
||||
pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
|
||||
@@ -1620,6 +1639,8 @@ pub fn load_with_linked_jdk(
|
||||
for p in resolver.active(&pom.profiles) {
|
||||
module_names.extend(p.modules.iter().cloned());
|
||||
}
|
||||
let jdks = pom.profiles.iter().filter_map(|p| p.activation_jdk.as_ref());
|
||||
model.jdk_activations.extend(jdks.filter(|spec| jdk_matches(spec, jdk_version)).cloned());
|
||||
let mut modules: Vec<PathBuf> = Vec::new();
|
||||
for m in module_names {
|
||||
let mut mp = crate::gradle::normalize(&dir.join(i(&m)));
|
||||
@@ -1702,7 +1723,9 @@ pub fn load_with_linked_jdk(
|
||||
|
||||
// The project can activate the profiles of its own POM and its ancestors'.
|
||||
for (id, active) in &ctx.profiles {
|
||||
if !model.profiles.iter().any(|x| x.id == *id) {
|
||||
if let Some(existing) = model.profiles.iter_mut().find(|x| x.id == *id) {
|
||||
existing.active_by_default |= *active;
|
||||
} else {
|
||||
model.profiles.push(MavenProfile { id: id.clone(), active_by_default: *active, ..Default::default() });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::process::{self, Output};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
@@ -32,6 +32,8 @@ pub struct SyncOptions {
|
||||
pub profiles: Vec<String>,
|
||||
/// Extra environment (`JAVA_HOME`).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Major version of the JDK Maven runs on, the same as the model is loaded with.
|
||||
pub jdk_version: Option<u32>,
|
||||
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
|
||||
pub maven_command: Option<String>,
|
||||
/// Resolved Gradle launcher from Settings.
|
||||
@@ -62,6 +64,9 @@ struct MavenCache {
|
||||
/// The trees list omitted occurrences (`-Dverbose`); older caches are reloaded.
|
||||
#[serde(default)]
|
||||
verbose: bool,
|
||||
/// [`MavenModel::jdk_activations`] of the sync; `None` in caches from before they were recorded.
|
||||
#[serde(default)]
|
||||
jdk_activations: Option<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
@@ -233,7 +238,9 @@ pub fn apply_maven_cache(root: &Path, cache_dir: &Path, model: &mut MavenModel)
|
||||
}
|
||||
model.synced_at = Some(cache.at_ms);
|
||||
model.sync_error = cache.error;
|
||||
let changed = cache.hash != hash_files(&maven::build_files(root, model));
|
||||
// Another JDK can switch profiles of the same build files.
|
||||
let changed = cache.hash != hash_files(&maven::build_files(root, model))
|
||||
|| cache.jdk_activations.is_some_and(|jdks| jdks != model.jdk_activations);
|
||||
model.stale = !cache.verbose || changed;
|
||||
// A cache older than the current build files: its effective-POM plugins and
|
||||
// resolved dependencies would hide what the POMs declare now (a just added
|
||||
@@ -368,10 +375,11 @@ pub fn sync_maven(
|
||||
cancel: &CancellationToken,
|
||||
progress: &dyn Fn(SyncProgress),
|
||||
) -> IdeResult<()> {
|
||||
let mut model = maven::load_with_linked(
|
||||
let mut model = maven::load_with_linked_jdk(
|
||||
root,
|
||||
maven::default_local_repo(),
|
||||
&options.maven_settings.profiles(&options.profiles),
|
||||
options.jdk_version,
|
||||
&options.maven_settings.linked_projects,
|
||||
);
|
||||
maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model);
|
||||
@@ -380,6 +388,7 @@ pub fn sync_maven(
|
||||
version: MAVEN_CACHE_VERSION,
|
||||
hash: hash_files(&maven::build_files(root, &model)),
|
||||
verbose: true,
|
||||
jdk_activations: Some(model.jdk_activations.clone()),
|
||||
..MavenCache::default()
|
||||
};
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read from.
|
||||
@@ -683,6 +692,7 @@ mod tests {
|
||||
at_ms: 5.0,
|
||||
error: None,
|
||||
verbose: true,
|
||||
jdk_activations: None,
|
||||
projects: vec![CachedMavenProject {
|
||||
key: "g:a".into(),
|
||||
plugins: vec![maven::plugin(
|
||||
@@ -733,6 +743,7 @@ mod tests {
|
||||
at_ms: 5.0,
|
||||
error: None,
|
||||
verbose: true,
|
||||
jdk_activations: None,
|
||||
projects: vec![CachedMavenProject {
|
||||
key: "g:a".into(),
|
||||
plugins: vec![maven::plugin(
|
||||
@@ -1055,6 +1066,95 @@ mod tests {
|
||||
assert_eq!(std::fs::metadata(&mvnw).unwrap().permissions().mode() & 0o777, 0o644);
|
||||
}
|
||||
|
||||
/// `root` with module `core`, and what `profile` adds when the JDK activates it: the module
|
||||
/// `modern` or only a property. Synced with `jdk` by a launcher printing `core`'s tree.
|
||||
#[cfg(unix)]
|
||||
fn synced_with_a_jdk_profile(base: &Path, profile: &str, jdk: Option<u32>) -> (PathBuf, PathBuf) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (root, cache) = (base.join("p"), base.join("cache"));
|
||||
let project = "<project><groupId>g</groupId><version>1</version>";
|
||||
for module in ["core", "modern"] {
|
||||
std::fs::create_dir_all(root.join(module)).unwrap();
|
||||
let pom = format!("{project}<artifactId>{module}</artifactId></project>");
|
||||
std::fs::write(root.join(module).join("pom.xml"), pom).unwrap();
|
||||
}
|
||||
let pom = format!(
|
||||
"{project}<artifactId>root</artifactId><packaging>pom</packaging><modules><module>core</module></modules>\
|
||||
<profiles><profile><id>modern</id><activation><jdk>[11,)</jdk></activation>{profile}</profile></profiles>\
|
||||
</project>"
|
||||
);
|
||||
std::fs::write(root.join("pom.xml"), pom).unwrap();
|
||||
let launcher = base.join("mvn");
|
||||
let tree = "[INFO] --- dependency:3.8.1:tree (default-cli) @ core ---\\n[INFO] g:core:jar:1\\n\
|
||||
[INFO] \\\\- g:lib:jar:1:compile\\n[INFO] \\\\- g:transitive:jar:1:compile\\n";
|
||||
std::fs::write(&launcher, format!("#!/bin/sh\nprintf '{tree}'\n")).unwrap();
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let options = SyncOptions {
|
||||
maven_command: Some(launcher.to_string_lossy().into_owned()),
|
||||
jdk_version: jdk,
|
||||
..Default::default()
|
||||
};
|
||||
sync_maven(&root, &cache, &options, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
(root, cache)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn loaded_with_jdk((root, cache): &(PathBuf, PathBuf), jdk: Option<u32>) -> MavenModel {
|
||||
crate::load_linked_with_jdk(root, cache, None, &Default::default(), &Default::default(), jdk).maven.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const MODULE: &str = "<modules><module>modern</module></modules>";
|
||||
#[cfg(unix)]
|
||||
const PROPERTY: &str = "<properties><x>1</x></properties>";
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_synced_model_with_a_jdk_profile_is_current() {
|
||||
for (profile, jdk, modules) in
|
||||
[(MODULE, Some(17), 3), (MODULE, Some(8), 2), (MODULE, None, 2), (PROPERTY, Some(17), 2)]
|
||||
{
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, jdk), jdk);
|
||||
assert_eq!(model.projects.len(), modules, "{profile} {jdk:?}");
|
||||
assert!(!model.stale, "{profile} {jdk:?}");
|
||||
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
|
||||
assert_eq!(core.dependencies[0].children[0].artifact_id, "transitive", "{profile} {jdk:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_jdk_change_is_stale_when_it_switches_a_profile() {
|
||||
for profile in [MODULE, PROPERTY] {
|
||||
for (synced, loaded, stale) in [
|
||||
(Some(17), Some(21), false),
|
||||
(Some(17), Some(8), true),
|
||||
(Some(8), Some(17), true),
|
||||
(Some(17), None, true),
|
||||
(None, Some(17), true),
|
||||
(None, Some(8), false),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, synced), loaded);
|
||||
assert_eq!(model.stale, stale, "{profile} {synced:?} {loaded:?}");
|
||||
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
|
||||
assert_eq!(core.dependencies.is_empty(), stale, "{profile} {synced:?} {loaded:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_sync_from_before_jdk_profiles_were_recorded_stays_current() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = synced_with_a_jdk_profile(tmp.path(), PROPERTY, Some(17));
|
||||
let mut json: serde_json::Value = read_cache(&project.1, MAVEN_CACHE).unwrap();
|
||||
assert!(json.as_object_mut().unwrap().remove("jdk_activations").is_some());
|
||||
write_cache(&project.1, MAVEN_CACHE, &json).unwrap();
|
||||
assert!(!loaded_with_jdk(&project, Some(17)).stale);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn maven_sync_runs_the_daemon_command_serially() {
|
||||
|
||||
@@ -27,4 +27,4 @@ libc = "0.2"
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Environment", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -86,6 +86,8 @@ pub struct EditorAppearanceSettings {
|
||||
pub indent_guides: bool,
|
||||
/// Colour indent guides by depth (`--syn-rainbow-*`), while `indent_guides` is on.
|
||||
pub rainbow_indent_guides: bool,
|
||||
/// Also tint each indent level's whitespace in its rainbow colour, while `rainbow_indent_guides` is on.
|
||||
pub rainbow_indent_guides_fill: bool,
|
||||
/// Right margin and visual guides from Code Style.
|
||||
pub hard_wrap_guides: bool,
|
||||
pub intention_bulb: bool,
|
||||
@@ -114,6 +116,7 @@ impl Default for EditorAppearanceSettings {
|
||||
whitespace_trailing: true,
|
||||
indent_guides: true,
|
||||
rainbow_indent_guides: false,
|
||||
rainbow_indent_guides_fill: false,
|
||||
hard_wrap_guides: true,
|
||||
intention_bulb: true,
|
||||
render_doc_comments: false,
|
||||
|
||||
@@ -328,6 +328,18 @@ pub enum IdeEvent {
|
||||
AskpassDone {
|
||||
id: u64,
|
||||
},
|
||||
/// An external `/api/file` request asks the target project window to confirm opening a file;
|
||||
/// answered with `web_file_api_confirm`.
|
||||
FileApiConfirm {
|
||||
id: u64,
|
||||
source: String,
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
},
|
||||
/// File-open confirmation prompt `id` was answered or cancelled.
|
||||
FileApiConfirmDone {
|
||||
id: u64,
|
||||
},
|
||||
/// The kernel of an open notebook changed state (`starting`, `idle`, `busy`,
|
||||
/// `dead`); `message` says why it failed to start or died.
|
||||
NotebookKernel {
|
||||
|
||||
@@ -285,6 +285,190 @@ fn taskkill_tree_of(pid: u32) {
|
||||
windows_tree::wait_all(&started, TREE_EXIT_WAIT);
|
||||
}
|
||||
|
||||
/// The registry environment behind [`registry_env_changes`], read with
|
||||
/// `CreateEnvironmentBlock` as Explorer does for the programs it starts after a
|
||||
/// `WM_SETTINGCHANGE`. It is read again only after `HKCU\Environment` or the machine's
|
||||
/// `Environment` key reports a change, so spawning a child costs two event polls.
|
||||
#[cfg(windows)]
|
||||
mod registry_env {
|
||||
use std::ffi::OsString;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||
use std::sync::Mutex;
|
||||
use windows_sys::Win32::Foundation::{ERROR_SUCCESS, HANDLE, WAIT_OBJECT_0};
|
||||
use windows_sys::Win32::Security::{TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY};
|
||||
use windows_sys::Win32::System::Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock};
|
||||
use windows_sys::Win32::System::Registry::{
|
||||
HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_NOTIFY, REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_CHANGE_NAME,
|
||||
REG_NOTIFY_THREAD_AGNOSTIC, RegCloseKey, RegNotifyChangeKeyValue, RegOpenKeyExW,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
CreateEventW, GetCurrentProcess, OpenProcessToken, ResetEvent, WaitForSingleObject,
|
||||
};
|
||||
|
||||
type Vars = Vec<(OsString, OsString)>;
|
||||
|
||||
/// An open registry key and the event its next change signals.
|
||||
struct Watch {
|
||||
key: HKEY,
|
||||
event: OwnedHandle,
|
||||
}
|
||||
|
||||
// SAFETY: a registry key handle is a kernel handle, usable from any thread.
|
||||
unsafe impl Send for Watch {}
|
||||
|
||||
impl Watch {
|
||||
fn new(root: HKEY, path: &str) -> Option<Self> {
|
||||
let path: Vec<u16> = path.encode_utf16().chain(Some(0)).collect();
|
||||
let mut key: HKEY = std::ptr::null_mut();
|
||||
// SAFETY: `path` is NUL-terminated; `key` receives a handle the watch owns.
|
||||
if unsafe { RegOpenKeyExW(root, path.as_ptr(), 0, KEY_NOTIFY, &mut key) } != ERROR_SUCCESS {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: plain call; a non-null result is a manual-reset event handle owned here.
|
||||
let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) };
|
||||
if event.is_null() {
|
||||
// SAFETY: `key` was opened above and is closed once.
|
||||
unsafe { RegCloseKey(key) };
|
||||
return None;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
let watch = Watch { key, event: unsafe { OwnedHandle::from_raw_handle(event) } };
|
||||
watch.arm().then_some(watch)
|
||||
}
|
||||
|
||||
/// Asks to be told of the key's next change; `false` when it cannot be watched.
|
||||
fn arm(&self) -> bool {
|
||||
let filter = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC;
|
||||
// SAFETY: both handles are owned by the watch and open.
|
||||
let status = unsafe { RegNotifyChangeKeyValue(self.key, 0, filter, self.event.as_raw_handle(), 1) };
|
||||
status == ERROR_SUCCESS
|
||||
}
|
||||
|
||||
/// Whether the key changed since the last call; re-arms the watch when it did.
|
||||
fn changed(&self) -> bool {
|
||||
let event: HANDLE = self.event.as_raw_handle();
|
||||
// SAFETY: an event handle owned by the watch.
|
||||
if unsafe { WaitForSingleObject(event, 0) } != WAIT_OBJECT_0 {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
unsafe { ResetEvent(event) };
|
||||
self.arm();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Watch {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the key was opened by `Watch::new` and is closed once.
|
||||
unsafe { RegCloseKey(self.key) };
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
startup: Vars,
|
||||
current: Vars,
|
||||
watches: Vec<Watch>,
|
||||
}
|
||||
|
||||
static STATE: Mutex<Option<State>> = Mutex::new(None);
|
||||
|
||||
pub(super) fn record() {
|
||||
let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if state.is_none() {
|
||||
*state = Some(start());
|
||||
}
|
||||
}
|
||||
|
||||
fn start() -> State {
|
||||
// Watch before reading: a change in between is then read again, not missed.
|
||||
let watches = [
|
||||
(HKEY_CURRENT_USER, "Environment"),
|
||||
(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(root, path)| Watch::new(root, path))
|
||||
.collect();
|
||||
let startup = read().unwrap_or_default();
|
||||
State { current: startup.clone(), startup, watches }
|
||||
}
|
||||
|
||||
pub(super) fn changes() -> Vec<(OsString, Option<OsString>)> {
|
||||
let mut guard = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let state = guard.get_or_insert_with(start);
|
||||
// Poll every watch: each one that fired must be re-armed.
|
||||
let changed = state.watches.iter().fold(false, |any, watch| watch.changed() | any);
|
||||
if changed && let Some(fresh) = read() {
|
||||
state.current = fresh;
|
||||
}
|
||||
if state.current == state.startup {
|
||||
return Vec::new();
|
||||
}
|
||||
super::registry_diff(&|k| std::env::var_os(k), &state.startup, &state.current)
|
||||
}
|
||||
|
||||
/// The environment a program Explorer starts now would get; `None` when it cannot be read.
|
||||
pub(super) fn read() -> Option<Vars> {
|
||||
let mut token: HANDLE = std::ptr::null_mut();
|
||||
let access = TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE;
|
||||
// SAFETY: this process's pseudo-handle; `token` receives a handle owned here.
|
||||
if unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut token) } == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||
let mut block: *mut core::ffi::c_void = std::ptr::null_mut();
|
||||
// SAFETY: an open token; `block` receives a block destroyed below.
|
||||
if unsafe { CreateEnvironmentBlock(&mut block, token.as_raw_handle(), 0) } == 0 || block.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the block holds `NAME=VALUE` entries, each NUL-terminated, then a final NUL.
|
||||
let vars = unsafe { parse_block(block as *const u16) };
|
||||
// SAFETY: the block was created above and is destroyed once.
|
||||
unsafe { DestroyEnvironmentBlock(block) };
|
||||
Some(vars)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `block` points to UTF-16 entries, each NUL-terminated, ended by an empty one.
|
||||
unsafe fn parse_block(block: *const u16) -> Vars {
|
||||
let mut vars = Vars::new();
|
||||
let mut at = block;
|
||||
loop {
|
||||
let mut len = 0;
|
||||
// SAFETY: the caller guarantees the terminating NULs.
|
||||
while unsafe { *at.add(len) } != 0 {
|
||||
len += 1;
|
||||
}
|
||||
if len == 0 {
|
||||
return vars;
|
||||
}
|
||||
// SAFETY: the `len` units before the NUL were just read.
|
||||
let entry = unsafe { std::slice::from_raw_parts(at, len) };
|
||||
// Per-drive directories (`=C:=C:\dir`) have an empty name: skip them.
|
||||
if let Some(eq) = entry.iter().skip(1).position(|&c| c == u16::from(b'=')) {
|
||||
let eq = eq + 1;
|
||||
vars.push((OsString::from_wide(&entry[..eq]), OsString::from_wide(&entry[eq + 1..])));
|
||||
}
|
||||
// SAFETY: the entry's NUL is followed by the next entry or the final NUL.
|
||||
at = unsafe { at.add(len + 1) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn reads_this_users_environment() {
|
||||
let vars = super::read().expect("environment block");
|
||||
let get = |k: &str| vars.iter().find(|(n, _)| n.eq_ignore_ascii_case(k)).map(|(_, v)| v.clone());
|
||||
assert!(get("SystemRoot").is_some_and(|v| !v.is_empty()), "{vars:?}");
|
||||
assert!(get("Path").is_some_and(|v| !v.is_empty()), "{vars:?}");
|
||||
assert!(vars.iter().all(|(k, _)| !k.is_empty() && !k.to_string_lossy().contains('=')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows_tree {
|
||||
use std::collections::HashSet;
|
||||
@@ -676,7 +860,7 @@ pub fn host_var_os_in(dir: &Path, key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
}
|
||||
|
||||
fn host_var_os_for(dir: Option<&Path>, key: &OsStr) -> Option<OsString> {
|
||||
match child_env_changes(dir).into_iter().find(|(k, _)| k == key) {
|
||||
match child_env_changes(dir).into_iter().find(|(k, _)| same_key(k, key)) {
|
||||
Some((_, fixed)) => fixed,
|
||||
None => std::env::var_os(key).or_else(|| shell_env_for(dir).find(|(k, _)| k == key).map(|(_, v)| v)),
|
||||
}
|
||||
@@ -688,7 +872,7 @@ fn apply_changes(
|
||||
changes: &[(OsString, Option<OsString>)],
|
||||
) -> Vec<(OsString, OsString)> {
|
||||
for (key, value) in changes {
|
||||
let at = vars.iter().position(|(k, _)| k == key);
|
||||
let at = vars.iter().position(|(k, _)| same_key(k, key));
|
||||
match (at, value) {
|
||||
(Some(i), Some(v)) => vars[i].1 = v.clone(),
|
||||
(Some(i), None) => {
|
||||
@@ -701,25 +885,126 @@ fn apply_changes(
|
||||
vars
|
||||
}
|
||||
|
||||
/// The AppImage fixes, the overlay, the manual proxy's, then those of the project holding
|
||||
/// `dir` (a later one wins); one entry per name.
|
||||
/// The registry's changes (Windows), the AppImage fixes, the overlay, the manual proxy's,
|
||||
/// then those of the project holding `dir` (a later one wins); one entry per name.
|
||||
fn child_env_changes(dir: Option<&Path>) -> Vec<(OsString, Option<OsString>)> {
|
||||
let mut changes = appimage_fixes();
|
||||
let mut changes = registry_env_changes();
|
||||
changes.extend(appimage_fixes());
|
||||
let overlay = env_overlay();
|
||||
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| o == k));
|
||||
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| same_key(o, k)));
|
||||
changes.extend(overlay.iter().cloned());
|
||||
// A manual HTTP proxy reaches tools that read `HTTP_PROXY` (language servers, git, curl).
|
||||
let proxy = crate::proxy_settings::proxy().child_env();
|
||||
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| p == k));
|
||||
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| same_key(p, k)));
|
||||
changes.extend(proxy);
|
||||
if let Some(dir) = dir {
|
||||
let project = crate::project_env::for_dir(dir);
|
||||
changes.retain(|(k, _)| !project.iter().any(|(p, _)| p == k));
|
||||
changes.retain(|(k, _)| !project.iter().any(|(p, _)| same_key(p, k)));
|
||||
changes.extend(project.iter().cloned());
|
||||
}
|
||||
changes
|
||||
}
|
||||
|
||||
/// Whether two variable names are the same variable: Windows ignores case (`Path` is `PATH`).
|
||||
fn same_key(a: &OsStr, b: &OsStr) -> bool {
|
||||
if cfg!(windows) { a.eq_ignore_ascii_case(b) } else { a == b }
|
||||
}
|
||||
|
||||
/// What changed in the environment Windows gives new programs (the registry's machine and
|
||||
/// user variables) since this process started. A program installed meanwhile (Node.js, a
|
||||
/// JDK) adds its folder to `Path`; a child of the IDE must find it, as a program started
|
||||
/// from Explorer would, without restarting the IDE. Empty elsewhere.
|
||||
fn registry_env_changes() -> Vec<(OsString, Option<OsString>)> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
registry_env::changes()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Remembers the registry environment this process starts with, so that later changes reach
|
||||
/// new children. Call at startup (otherwise the first child spawn records it). Does nothing
|
||||
/// outside Windows.
|
||||
pub fn record_startup_registry_env() {
|
||||
#[cfg(windows)]
|
||||
registry_env::record();
|
||||
}
|
||||
|
||||
/// The entry of a `PATH`-like list as compared: without a trailing separator, and on
|
||||
/// Windows without case.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn path_entry_key(dir: &Path) -> String {
|
||||
let text = dir.to_string_lossy();
|
||||
let text = text.trim_end_matches(['\\', '/']);
|
||||
if cfg!(windows) { text.to_ascii_lowercase() } else { text.to_owned() }
|
||||
}
|
||||
|
||||
/// `old` → `fresh` applied to this process's `PATH`-like list `process`: entries that
|
||||
/// `fresh` dropped are removed and those it added are appended, so what the IDE put on
|
||||
/// `PATH` itself (managed tools, the user's `Path`) stays where it is.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn rebase_path_list(process: &OsStr, old: &OsStr, fresh: &OsStr) -> OsString {
|
||||
let entries = |list: &OsStr| -> Vec<std::path::PathBuf> {
|
||||
std::env::split_paths(list).filter(|d| !d.as_os_str().is_empty()).collect()
|
||||
};
|
||||
let old: Vec<String> = entries(old).iter().map(|d| path_entry_key(d)).collect();
|
||||
let fresh = entries(fresh);
|
||||
let fresh_keys: Vec<String> = fresh.iter().map(|d| path_entry_key(d)).collect();
|
||||
let mut out: Vec<std::path::PathBuf> = entries(process)
|
||||
.into_iter()
|
||||
.filter(|d| {
|
||||
let key = path_entry_key(d);
|
||||
!old.contains(&key) || fresh_keys.contains(&key)
|
||||
})
|
||||
.collect();
|
||||
for (dir, key) in fresh.into_iter().zip(fresh_keys) {
|
||||
if !old.contains(&key) && !out.iter().any(|d| path_entry_key(d) == key) {
|
||||
out.push(dir);
|
||||
}
|
||||
}
|
||||
std::env::join_paths(out).unwrap_or_else(|_| process.to_owned())
|
||||
}
|
||||
|
||||
/// The changes that bring this process's environment (`process`) from the registry
|
||||
/// environment it started with (`old`) to the current one (`fresh`): new and changed
|
||||
/// variables; removed ones while this process still has the value it started with; and
|
||||
/// `PATH` rebased ([`rebase_path_list`]).
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn registry_diff(
|
||||
process: &dyn Fn(&OsStr) -> Option<OsString>,
|
||||
old: &[(OsString, OsString)],
|
||||
fresh: &[(OsString, OsString)],
|
||||
) -> Vec<(OsString, Option<OsString>)> {
|
||||
let get =
|
||||
|vars: &[(OsString, OsString)], k: &OsStr| vars.iter().find(|(n, _)| same_key(n, k)).map(|(_, v)| v.clone());
|
||||
let mut out = Vec::new();
|
||||
for (key, value) in fresh {
|
||||
let before = get(old, key);
|
||||
if before.as_ref() == Some(value) {
|
||||
continue;
|
||||
}
|
||||
let current = process(key);
|
||||
if key.eq_ignore_ascii_case("PATH") {
|
||||
let current = current.unwrap_or_default();
|
||||
let rebased = rebase_path_list(¤t, before.as_deref().unwrap_or_default(), value);
|
||||
if rebased != current {
|
||||
out.push((key.clone(), Some(rebased)));
|
||||
}
|
||||
} else if current.as_ref() != Some(value) {
|
||||
out.push((key.clone(), Some(value.clone())));
|
||||
}
|
||||
}
|
||||
for (key, value) in old {
|
||||
if get(fresh, key).is_none() && process(key).as_ref() == Some(value) {
|
||||
out.push((key.clone(), None));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Read on every call, not cached: startup rewrites `PATH` (login shell, managed tools).
|
||||
fn appimage_fixes() -> Vec<(OsString, Option<OsString>)> {
|
||||
if !cfg!(target_os = "linux") || std::env::var_os("APPDIR").is_none() {
|
||||
@@ -1459,6 +1744,118 @@ mod tests {
|
||||
assert!(fixes(&[("APPDIR", "/"), ("PATH", "/usr/bin")]).is_empty());
|
||||
}
|
||||
|
||||
fn os(vars: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
|
||||
vars.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect()
|
||||
}
|
||||
|
||||
fn list(dirs: &[&str]) -> OsString {
|
||||
std::env::join_paths(dirs).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_path_changes_keep_what_the_ide_added_to_path() {
|
||||
// The IDE put `tools` first at startup; meanwhile an installer appended `node`
|
||||
// and an uninstaller removed `old`.
|
||||
let process = list(&["tools", "sys", "old", "user"]);
|
||||
let rebased = rebase_path_list(&process, &list(&["sys", "old", "user"]), &list(&["sys", "user", "node"]));
|
||||
assert_eq!(rebased, list(&["tools", "sys", "user", "node"]));
|
||||
// Nothing to add when the entry is already there (a trailing separator aside).
|
||||
let sep = std::path::MAIN_SEPARATOR.to_string();
|
||||
let rebased =
|
||||
rebase_path_list(&list(&["sys", "node"]), &list(&["sys"]), &list(&["sys", &format!("node{sep}")]));
|
||||
assert_eq!(rebased, list(&["sys", "node"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_changes_are_new_changed_and_removed_variables() {
|
||||
let old = os(&[("KEEP", "1"), ("CHANGED", "a"), ("GONE", "x"), ("OVERRIDDEN", "y"), ("PATH", "sys")]);
|
||||
let fresh = os(&[("KEEP", "1"), ("CHANGED", "b"), ("NEW", "n"), ("PATH", "sys")]);
|
||||
// The IDE was launched with `OVERRIDDEN` set otherwise: that value stays.
|
||||
let process = |k: &OsStr| match k.to_str()?.to_ascii_uppercase().as_str() {
|
||||
"KEEP" => Some("1".into()),
|
||||
"CHANGED" => Some("a".into()),
|
||||
"GONE" => Some("x".into()),
|
||||
"OVERRIDDEN" => Some("launcher".into()),
|
||||
"PATH" => Some(list(&["tools", "sys"])),
|
||||
_ => None,
|
||||
};
|
||||
let got = registry_diff(&process, &old, &fresh);
|
||||
let want: Vec<(OsString, Option<OsString>)> =
|
||||
vec![("CHANGED".into(), Some("b".into())), ("NEW".into(), Some("n".into())), ("GONE".into(), None)];
|
||||
assert_eq!(got, want);
|
||||
assert!(registry_diff(&process, &old, &old).is_empty());
|
||||
// A `Path` change reaches the process `PATH` (another case of the same variable).
|
||||
let got = registry_diff(&process, &os(&[("Path", "sys")]), &os(&[("Path", "sys;node")]));
|
||||
if cfg!(windows) {
|
||||
assert_eq!(got, vec![("Path".into(), Some(list(&["tools", "sys", "node"])))]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_match_variable_names_as_the_platform_does() {
|
||||
let vars = os(&[("Path", "a")]);
|
||||
let got = apply_changes(vars, &[("PATH".into(), Some("b".into()))]);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(got, os(&[("Path", "b")]));
|
||||
} else {
|
||||
assert_eq!(got, os(&[("Path", "a"), ("PATH", "b")]));
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable set in `HKCU\Environment` after startup (as an installer or the System
|
||||
/// Properties dialog does) reaches the next child without a restart.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_user_variable_set_after_startup_reaches_new_children() {
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RegDeleteKeyValueW, RegSetKeyValueW};
|
||||
|
||||
fn wide(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
struct Cleanup(Vec<u16>);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: NUL-terminated names of a value this test created.
|
||||
unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, wide("Environment").as_ptr(), self.0.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
record_startup_registry_env();
|
||||
let name = format!("OPENIDEA_REGISTRY_ENV_TEST_{}", std::process::id());
|
||||
let value = wide("installed");
|
||||
let wide_name = wide(&name);
|
||||
// SAFETY: NUL-terminated names; the data is `value`'s bytes, NUL included.
|
||||
let status = unsafe {
|
||||
RegSetKeyValueW(
|
||||
HKEY_CURRENT_USER,
|
||||
wide("Environment").as_ptr(),
|
||||
wide_name.as_ptr(),
|
||||
REG_SZ,
|
||||
value.as_ptr().cast(),
|
||||
(value.len() * 2) as u32,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, ERROR_SUCCESS);
|
||||
let cleanup = Cleanup(wide_name);
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
let seen = loop {
|
||||
let seen = host_var_os(&name);
|
||||
if seen.is_some() || std::time::Instant::now() >= deadline {
|
||||
break seen;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
assert_eq!(seen.as_deref(), Some(OsStr::new("installed")));
|
||||
assert!(spawnable_host_vars().any(|(k, v)| k == name.as_str() && v == "installed"));
|
||||
drop(cleanup);
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while host_var_os(&name).is_some() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(host_var_os(&name), None, "a removed variable is gone again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_env_keeps_what_the_call_site_set() {
|
||||
let mut cmd = Command::new("true");
|
||||
|
||||
@@ -1087,6 +1087,8 @@ pub struct GeneralSettings {
|
||||
pub close_tabs_with_window: bool,
|
||||
/// Where Open… puts a project while one is open: `ask` | `new` | `same` | `attach`.
|
||||
pub open_project_in: String,
|
||||
/// What closing a remote development window does with its backend: `ask` | `keep` | `stop`.
|
||||
pub close_remote_window: String,
|
||||
/// Initial folder of the Open / Clone dialogs; empty = the OS default.
|
||||
pub default_project_directory: String,
|
||||
/// Save all files after `idle_seconds` without input.
|
||||
@@ -1100,6 +1102,8 @@ pub struct GeneralSettings {
|
||||
pub project_name: String,
|
||||
/// Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`.
|
||||
pub update_source: String,
|
||||
/// `stable` | `nightly`; defaults to the running build's channel.
|
||||
pub update_channel: String,
|
||||
pub auto_check_updates: bool,
|
||||
/// System Settings › Updates: open the What's New page after the app starts a new version.
|
||||
pub show_whats_new_after_update: bool,
|
||||
@@ -1115,6 +1119,7 @@ impl Default for GeneralSettings {
|
||||
close_without_welcome: false,
|
||||
close_tabs_with_window: false,
|
||||
open_project_in: "ask".into(),
|
||||
close_remote_window: "ask".into(),
|
||||
default_project_directory: String::new(),
|
||||
save_on_idle: false,
|
||||
idle_seconds: 15,
|
||||
@@ -1122,6 +1127,7 @@ impl Default for GeneralSettings {
|
||||
power_save_mode: false,
|
||||
project_name: String::new(),
|
||||
update_source: "auto".into(),
|
||||
update_channel: crate::updates::UpdateChannel::of_version(env!("CARGO_PKG_VERSION")).as_str().into(),
|
||||
auto_check_updates: true,
|
||||
show_whats_new_after_update: true,
|
||||
last_run_version: String::new(),
|
||||
@@ -1466,6 +1472,9 @@ pub struct EditorSettings {
|
||||
/// Color Scheme › Language Defaults › Semantic highlighting: local variables and
|
||||
/// parameters get a colour derived from their name (IDEA's rainbow identifiers).
|
||||
pub semantic_highlighting: bool,
|
||||
/// Color Scheme › Language Defaults › Dim inactive preprocessor code: grey out the
|
||||
/// `#if`/`#ifdef` branches clangd reports as inactive (C and C++).
|
||||
pub dim_inactive_code: bool,
|
||||
/// Docstring markup format whose tags and keywords the Python editor highlights
|
||||
/// (`plain`, `rest`, `epytext`, `google`, `numpy`).
|
||||
pub docstring_format: String,
|
||||
@@ -1531,6 +1540,7 @@ impl Default for EditorSettings {
|
||||
color_overrides: BTreeMap::new(),
|
||||
custom_schemes: BTreeMap::new(),
|
||||
semantic_highlighting: false,
|
||||
dim_inactive_code: true,
|
||||
docstring_format: "rest".into(),
|
||||
rainbow_brackets: false,
|
||||
rainbow_bracket_kinds: RainbowBracketKinds::default(),
|
||||
@@ -1730,6 +1740,8 @@ pub struct MarkdownSettings {
|
||||
pub preview_layout: MarkdownPreviewLayout,
|
||||
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
|
||||
pub preview_font_size: Option<u32>,
|
||||
/// How single newlines inside a paragraph are rendered in the Markdown preview.
|
||||
pub soft_line_breaks: MarkdownSoftLineBreaks,
|
||||
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
|
||||
/// trusted projects, or stay in static safe mode.
|
||||
pub mdx_execution: MdxExecutionPolicy,
|
||||
@@ -1745,6 +1757,7 @@ impl Default for MarkdownSettings {
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
soft_line_breaks: MarkdownSoftLineBreaks::default(),
|
||||
mdx_execution: MdxExecutionPolicy::default(),
|
||||
run_commands: true,
|
||||
command_directory: None,
|
||||
@@ -1752,6 +1765,16 @@ impl Default for MarkdownSettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownSoftLineBreaks {
|
||||
/// Standard Markdown: a single newline collapses into a space.
|
||||
#[default]
|
||||
Standard,
|
||||
/// Render each single newline inside a paragraph as a line break (`<br>`).
|
||||
Break,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MdxExecutionPolicy {
|
||||
@@ -2577,12 +2600,16 @@ mod tests {
|
||||
let old: Settings = serde_json::from_str(r#"{"languages":{"markdown":{"previewFontSize":16}}}"#).unwrap();
|
||||
assert_eq!(old.languages.markdown.preview_layout, MarkdownPreviewLayout::SideBySide);
|
||||
assert_eq!(old.languages.markdown.preview_font_size, Some(16));
|
||||
assert_eq!(old.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Standard);
|
||||
|
||||
let stacked: Settings =
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked"}}}"#).unwrap();
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked","softLineBreaks":"break"}}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(stacked.languages.markdown.preview_layout, MarkdownPreviewLayout::Stacked);
|
||||
assert_eq!(stacked.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Break);
|
||||
let saved = serde_json::to_value(&stacked).unwrap();
|
||||
assert_eq!(saved["languages"]["markdown"]["previewLayout"], "stacked");
|
||||
assert_eq!(saved["languages"]["markdown"]["softLineBreaks"], "break");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().languages.markdown, stacked.languages.markdown);
|
||||
}
|
||||
|
||||
@@ -2699,6 +2726,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_inactive_code_defaults_on_and_round_trips() {
|
||||
let mut settings = Settings::default();
|
||||
assert!(settings.editor.dim_inactive_code);
|
||||
settings.editor.dim_inactive_code = false;
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["editor"]["dimInactiveCode"], false);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert!(!restored.editor.dim_inactive_code);
|
||||
// Settings written before the option existed keep clangd's inactive-code grey.
|
||||
let old: Settings = serde_json::from_str(r#"{"editor":{"semanticHighlighting":true}}"#).unwrap();
|
||||
assert!(old.editor.dim_inactive_code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_window_badges_default_on_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
|
||||
|
||||
@@ -30,6 +30,38 @@ impl UpdateSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// System Settings › Updates › Update channel: which release line updates come from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UpdateChannel {
|
||||
/// `releases/latest`, never a prerelease, mirrored on CNB.
|
||||
Stable,
|
||||
/// The rolling `nightly` release (nightly.yml), on GitHub only.
|
||||
Nightly,
|
||||
}
|
||||
|
||||
impl UpdateChannel {
|
||||
/// The channel a build of `version` updates from unless the setting says otherwise.
|
||||
pub fn of_version(version: &str) -> Self {
|
||||
if version.contains("-nightly.") { Self::Nightly } else { Self::Stable }
|
||||
}
|
||||
|
||||
/// The `general.updateChannel` setting; anything else follows this build.
|
||||
pub fn resolve(preference: &str) -> Self {
|
||||
match preference {
|
||||
"stable" => Self::Stable,
|
||||
"nightly" => Self::Nightly,
|
||||
_ => Self::of_version(env!("CARGO_PKG_VERSION")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Stable => "stable",
|
||||
Self::Nightly => "nightly",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateInfo {
|
||||
@@ -109,6 +141,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_follows_the_build_unless_chosen() {
|
||||
assert_eq!(UpdateChannel::of_version("0.1.57"), UpdateChannel::Stable);
|
||||
assert_eq!(UpdateChannel::of_version("0.1.58-nightly.20261203"), UpdateChannel::Nightly);
|
||||
assert_eq!(UpdateChannel::of_version("0.1.58-nightly.20261203.2"), UpdateChannel::Nightly);
|
||||
assert_eq!(UpdateChannel::of_version("0.2.0-beta.1"), UpdateChannel::Stable);
|
||||
assert_eq!(UpdateChannel::resolve("stable"), UpdateChannel::Stable);
|
||||
assert_eq!(UpdateChannel::resolve("nightly"), UpdateChannel::Nightly);
|
||||
let build = UpdateChannel::of_version(env!("CARGO_PKG_VERSION"));
|
||||
for other in ["", "auto", "Nightly", "eap"] {
|
||||
assert_eq!(UpdateChannel::resolve(other), build);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checks_at_startup_and_every_four_hours_even_after_failure() {
|
||||
let mut policy = UpdatePolicy::default();
|
||||
|
||||
@@ -31,6 +31,17 @@ pub struct VcsSettings {
|
||||
pub svn: SvnSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
/// Branch and tag URL layout configured for one Subversion repository.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SvnBranchConfig {
|
||||
/// Trunk URL (e.g. `https://svn.example.com/repos/project/trunk`).
|
||||
pub trunk_url: String,
|
||||
/// Folders holding branches/tags (e.g. `["https://svn.example.com/repos/project/branches"]`).
|
||||
pub branch_locations: Vec<String>,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -43,6 +54,8 @@ pub struct SvnSettings {
|
||||
/// Pass `--config-dir config_dir` to every svn command.
|
||||
pub use_custom_config_dir: bool,
|
||||
pub config_dir: String,
|
||||
/// Configured trunk/branch locations keyed by normalized repository root URL or WC root.
|
||||
pub branch_configurations: std::collections::BTreeMap<String, SvnBranchConfig>,
|
||||
}
|
||||
|
||||
impl Default for SvnSettings {
|
||||
@@ -54,6 +67,7 @@ impl Default for SvnSettings {
|
||||
interactive: !cfg!(windows),
|
||||
use_custom_config_dir: false,
|
||||
config_dir: String::new(),
|
||||
branch_configurations: std::collections::BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -562,6 +576,8 @@ pub struct DebuggerSettings {
|
||||
pub flutter_hot_reload_on_save: bool,
|
||||
/// Java: whether to reload changed classes into running debug sessions after compilation.
|
||||
pub hot_swap_after_compile: HotSwapPolicy,
|
||||
/// Built-in Server: starting loopback port for `/api/file/<path>:<line>` requests.
|
||||
pub built_in_server_port: u16,
|
||||
pub python: PythonDebuggerSettings,
|
||||
pub cpp: CppDebuggerSettings,
|
||||
}
|
||||
@@ -585,6 +601,7 @@ impl Default for DebuggerSettings {
|
||||
debug_server_page: false,
|
||||
flutter_hot_reload_on_save: true,
|
||||
hot_swap_after_compile: HotSwapPolicy::Ask,
|
||||
built_in_server_port: 63342,
|
||||
python: PythonDebuggerSettings::default(),
|
||||
cpp: CppDebuggerSettings::default(),
|
||||
}
|
||||
@@ -727,6 +744,8 @@ impl Default for TerminalSettings {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ActionsOnSaveSettings {
|
||||
pub optimize_imports: bool,
|
||||
/// Rearrange code: class members in arrangement order, for the languages that have it.
|
||||
pub rearrange: bool,
|
||||
/// Run code cleanup (`source.fixAll`).
|
||||
pub cleanup: bool,
|
||||
}
|
||||
|
||||
@@ -157,6 +157,15 @@ pub struct TableInfo {
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
/// Non-secret identity of an already-connected data source target.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ConnectedSourceInfo {
|
||||
pub source_id: String,
|
||||
pub name: String,
|
||||
pub driver: DbDriver,
|
||||
pub database: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbColumnInfo")]
|
||||
@@ -1299,15 +1308,49 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lists non-secret metadata for every currently connected source target on this project/window.
|
||||
/// Never allocates a pool, connects a source, or reads credentials.
|
||||
pub fn connected_sources(&self) -> Vec<ConnectedSourceInfo> {
|
||||
let connected = self.connected();
|
||||
if connected.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let sources: std::collections::HashMap<String, DataSource> =
|
||||
self.sources().unwrap_or_default().into_iter().map(|s| (s.id.clone(), s)).collect();
|
||||
let mut out: Vec<ConnectedSourceInfo> = connected
|
||||
.into_iter()
|
||||
.filter_map(|source_id| {
|
||||
let (base_id, db_suffix) = split_target(&source_id);
|
||||
let source = sources.get(base_id)?.resolved().ok()?;
|
||||
let database =
|
||||
db_suffix.map(str::to_owned).or_else(|| (!source.database.is_empty()).then_some(source.database));
|
||||
Some(ConnectedSourceInfo { source_id, name: source.name, driver: source.driver, database })
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.source_id.cmp(&b.source_id));
|
||||
out
|
||||
}
|
||||
|
||||
/// Every schema (the Schemas tab picks the ones the tree shows); system schemas
|
||||
/// only with [`DbIntrospection::show_system`].
|
||||
pub async fn schemas(&self, id: &str) -> IdeResult<Vec<String>> {
|
||||
let system = self.source(id)?.introspection.show_system;
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Snowflake(p) = &*pool {
|
||||
Self::schemas_on(&pool, system).await
|
||||
}
|
||||
|
||||
/// Read schemas using an existing connection only. Never opens a connection or prompts for credentials.
|
||||
pub async fn connected_schemas(&self, id: &str) -> IdeResult<Vec<String>> {
|
||||
let system = self.source(id)?.introspection.show_system;
|
||||
let pool = self.connected_pool(id)?;
|
||||
Self::schemas_on(&pool, system).await
|
||||
}
|
||||
|
||||
async fn schemas_on(pool: &Pool, system: bool) -> IdeResult<Vec<String>> {
|
||||
if let Pool::Snowflake(p) = pool {
|
||||
return snowflake::meta::schemas(p, system).await;
|
||||
}
|
||||
let rows = match &*pool {
|
||||
let rows = match pool {
|
||||
Pool::Jdbc(p) => p.metadata(&["schemas"]).await?,
|
||||
_ => pool.rows(sql::schemas(pool.driver(), system), MAX_META_ROWS).await?,
|
||||
};
|
||||
@@ -1316,10 +1359,20 @@ impl DbManager {
|
||||
|
||||
pub async fn tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
|
||||
let pool = self.pool(id).await?;
|
||||
if let Pool::Snowflake(p) = &*pool {
|
||||
Self::tables_on(&pool, schema).await
|
||||
}
|
||||
|
||||
/// Read tables using an existing connection only. Never opens a connection or prompts for credentials.
|
||||
pub async fn connected_tables(&self, id: &str, schema: &str) -> IdeResult<Vec<TableInfo>> {
|
||||
let pool = self.connected_pool(id)?;
|
||||
Self::tables_on(&pool, schema).await
|
||||
}
|
||||
|
||||
async fn tables_on(pool: &Pool, schema: &str) -> IdeResult<Vec<TableInfo>> {
|
||||
if let Pool::Snowflake(p) = pool {
|
||||
return snowflake::meta::tables(p, schema).await;
|
||||
}
|
||||
let rows = match &*pool {
|
||||
let rows = match pool {
|
||||
Pool::Jdbc(p) => p.metadata(&["tables", schema]).await?,
|
||||
_ => pool.rows(&sql::tables(pool.driver(), schema), MAX_META_ROWS).await?,
|
||||
};
|
||||
@@ -1337,6 +1390,25 @@ impl DbManager {
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Executes a SQL statement using an existing connection only (used by extension hosts).
|
||||
/// Respects read-only connections and never opens a disconnected source or prompts for credentials.
|
||||
pub async fn connected_execute(
|
||||
&self,
|
||||
id: &str,
|
||||
statement: &str,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let pool = self.connected_pool(id)?;
|
||||
if pool.transaction_read_only() {
|
||||
conn::validate_pg_read_only(statement).map_err(IdeError::invalid)?;
|
||||
}
|
||||
if !conn::cursor_statement(statement) {
|
||||
self.cursors.release_target(id);
|
||||
}
|
||||
pool.execute_from(statement, 0, max_rows, cancel).await
|
||||
}
|
||||
|
||||
async fn duckdb_catalog_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
|
||||
let source = self.source(id)?;
|
||||
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Splitting SQL scripts into statements (`;`-terminated), aware of string
|
||||
//! literals, quoted identifiers, comments and PostgreSQL dollar quoting.
|
||||
//! MySQL strings take backslash escapes (no `NO_BACKSLASH_ESCAPES`) and double
|
||||
//! quotes (no `ANSI_QUOTES`), its defaults; the console's lexer.ts reads them alike.
|
||||
//! Offsets are UTF-16 code units, like everything on the IPC boundary.
|
||||
|
||||
use crate::DbDriver;
|
||||
@@ -22,12 +24,13 @@ enum State {
|
||||
Single,
|
||||
Double,
|
||||
Backtick,
|
||||
Bracket,
|
||||
LineComment,
|
||||
BlockComment,
|
||||
}
|
||||
|
||||
// Starts just after the opening `/*`. ClickHouse supports nested block comments.
|
||||
fn after_clickhouse_block_comment(mut text: &str) -> &str {
|
||||
// Starts just after the opening `/*`.
|
||||
fn after_nested_block_comment(mut text: &str) -> &str {
|
||||
let mut depth = 1usize;
|
||||
while let Some(at) = text.find(['/', '*']) {
|
||||
text = &text[at..];
|
||||
@@ -55,7 +58,7 @@ pub(super) fn clickhouse_keyword<'a>(sql: &mut &'a str) -> Option<&'a str> {
|
||||
if let Some(comment) = text.strip_prefix('#').or_else(|| text.strip_prefix("--")) {
|
||||
text = comment.split_once('\n').map_or("", |(_, rest)| rest);
|
||||
} else if let Some(comment) = text.strip_prefix("/*") {
|
||||
text = after_clickhouse_block_comment(comment);
|
||||
text = after_nested_block_comment(comment);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
@@ -76,6 +79,10 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
// PL/SQL: `;` inside BEGIN…END / DECLARE…END blocks does not terminate a statement.
|
||||
let plsql = driver == DbDriver::Oracle;
|
||||
let snowflake = driver == DbDriver::Snowflake;
|
||||
let postgres = driver == DbDriver::Postgres;
|
||||
let sqlite = driver == DbDriver::Sqlite;
|
||||
let sql_server = driver == DbDriver::SqlServer;
|
||||
let nested_comments = clickhouse || postgres || sql_server;
|
||||
let chars: Vec<(usize, char)> = text.char_indices().collect();
|
||||
// UTF-16 offset of each char index (plus the end).
|
||||
let mut u16_at = Vec::with_capacity(chars.len() + 1);
|
||||
@@ -105,6 +112,8 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
let mut script = false;
|
||||
// The segment may carry a Scripting block as its body (`CREATE TASK … AS BEGIN … END`).
|
||||
let mut defines = false;
|
||||
// The open string is PostgreSQL's `E'…'`.
|
||||
let mut escape_string = false;
|
||||
let push = |out: &mut Vec<SqlStatement>, s: usize, e: usize, has_code: bool| {
|
||||
if !has_code {
|
||||
return;
|
||||
@@ -164,6 +173,18 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
defines = false;
|
||||
}
|
||||
';' => has_code = true,
|
||||
// Words are read whole: the `E` of `E'…'` starts one, and a `$` inside one quotes nothing.
|
||||
_ if postgres && (c.is_alphabetic() || c == '_') => {
|
||||
has_code = true;
|
||||
if matches!(c, 'E' | 'e') && next == Some('\'') {
|
||||
(state, escape_string) = (State::Single, true);
|
||||
i += 1;
|
||||
} else {
|
||||
while chars.get(i + 1).is_some_and(|&(_, c)| c.is_alphanumeric() || matches!(c, '_' | '$')) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
'\'' => {
|
||||
state = State::Single;
|
||||
has_code = true;
|
||||
@@ -172,13 +193,17 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
state = State::Double;
|
||||
has_code = true;
|
||||
}
|
||||
'`' if mysql || clickhouse => {
|
||||
'`' if mysql || clickhouse || sqlite => {
|
||||
state = State::Backtick;
|
||||
has_code = true;
|
||||
}
|
||||
'[' if sqlite || sql_server => {
|
||||
state = State::Bracket;
|
||||
has_code = true;
|
||||
}
|
||||
'/' if next == Some('*') => {
|
||||
if clickhouse {
|
||||
let rest = after_clickhouse_block_comment(&text[byte_at(i + 2)..]);
|
||||
if nested_comments {
|
||||
let rest = after_nested_block_comment(&text[byte_at(i + 2)..]);
|
||||
let end = text.len() - rest.len();
|
||||
i = chars.partition_point(|&(offset, _)| offset < end);
|
||||
continue;
|
||||
@@ -199,7 +224,10 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
block = false;
|
||||
package = false;
|
||||
}
|
||||
'-' if next == Some('-') => {
|
||||
// MySQL reads `5--1` as a subtraction.
|
||||
'-' if next == Some('-')
|
||||
&& (!mysql || chars.get(i + 2).is_none_or(|&(_, c)| c == ' ' || c.is_ascii_control())) =>
|
||||
{
|
||||
state = State::LineComment;
|
||||
i += 1;
|
||||
}
|
||||
@@ -213,7 +241,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
state = State::LineComment;
|
||||
i += 1;
|
||||
}
|
||||
'$' if driver == DbDriver::Postgres || snowflake => {
|
||||
'$' if postgres || snowflake => {
|
||||
// `$tag$ … $tag$` (tag may be empty); `$1` parameters are not quotes.
|
||||
let rest = &text[byte_at(i)..];
|
||||
let tag_len = rest[1..].find('$').filter(|&n| {
|
||||
@@ -289,18 +317,18 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
_ => {}
|
||||
},
|
||||
State::Single => {
|
||||
if (mysql || clickhouse || snowflake) && c == '\\' {
|
||||
if (mysql || clickhouse || snowflake || escape_string) && c == '\\' {
|
||||
i += 1;
|
||||
} else if c == '\'' {
|
||||
if next == Some('\'') {
|
||||
i += 1;
|
||||
} else {
|
||||
state = State::Code;
|
||||
(state, escape_string) = (State::Code, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
State::Double => {
|
||||
if clickhouse && c == '\\' {
|
||||
if (mysql || clickhouse) && c == '\\' {
|
||||
i += 1;
|
||||
} else if c == '"' {
|
||||
if next == Some('"') {
|
||||
@@ -317,6 +345,13 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
state = State::Code;
|
||||
}
|
||||
}
|
||||
State::Bracket => {
|
||||
if sql_server && c == ']' && next == Some(']') {
|
||||
i += 1;
|
||||
} else if c == ']' {
|
||||
state = State::Code;
|
||||
}
|
||||
}
|
||||
State::LineComment => {
|
||||
if c == '\n' {
|
||||
state = State::Code;
|
||||
@@ -510,6 +545,76 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_and_sql_server_nest_block_comments() {
|
||||
let sql = "/* outer /* inner */ ; DELETE FROM b; */ SELECT 1";
|
||||
for driver in [DbDriver::Postgres, DbDriver::SqlServer] {
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), driver), vec![sql, "SELECT 2"]);
|
||||
assert_eq!(statement_at(sql, 25, driver).map(|s| s.text).as_deref(), Some(sql));
|
||||
assert_eq!(texts("/* open /* ; */ ; DELETE FROM b", driver), Vec::<String>::new());
|
||||
}
|
||||
for driver in [DbDriver::Mysql, DbDriver::Sqlite, DbDriver::Oracle, DbDriver::Snowflake] {
|
||||
assert_eq!(texts("/* a /* b */ SELECT 1; SELECT 2", driver), vec!["/* a /* b */ SELECT 1", "SELECT 2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_escape_strings_and_dollars_in_names() {
|
||||
for sql in [r"SELECT E'it\'s; DELETE FROM b; --'", r"SELECT e'a\\', E'it''s; \';'"] {
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Postgres), vec![sql, "SELECT 2"]);
|
||||
assert_eq!(statement_at(sql, 22, DbDriver::Postgres).map(|s| s.text).as_deref(), Some(sql));
|
||||
}
|
||||
// A backslash is plain in other strings, also after a word that ends in `e`.
|
||||
for sql in [r"SELECT 'a\'", r"SELECT date'\'", r"SELECT U&'\'", r#"SELECT "a\""#] {
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Postgres), vec![sql, "SELECT 2"]);
|
||||
}
|
||||
// A `$` inside a name opens no dollar quote.
|
||||
assert_eq!(
|
||||
texts("SELECT a$b$ FROM t; SELECT b$b$ FROM t", DbDriver::Postgres),
|
||||
vec!["SELECT a$b$ FROM t", "SELECT b$b$ FROM t"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_double_quoted_strings_and_dashes() {
|
||||
let sql = r#"SELECT "say \"hi; DELETE FROM b; \"", 'a''b;', "c"";", `d``;`"#;
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Mysql), vec![sql, "SELECT 2"]);
|
||||
assert_eq!(statement_at(sql, 24, DbDriver::Mysql).map(|s| s.text).as_deref(), Some(sql));
|
||||
// `--` starts a comment only before whitespace, a control character or the end.
|
||||
assert_eq!(texts("SELECT 5--1; SELECT 2", DbDriver::Mysql), vec!["SELECT 5--1", "SELECT 2"]);
|
||||
for comment in ["-- a;", "--\ta;", "--"] {
|
||||
assert_eq!(texts(&format!("SELECT 5 {comment}\n+ 1; SELECT 2"), DbDriver::Mysql).len(), 2);
|
||||
assert_eq!(texts(&format!("SELECT 1; {comment}"), DbDriver::Mysql), vec!["SELECT 1"]);
|
||||
}
|
||||
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Oracle] {
|
||||
assert_eq!(texts("SELECT 5--1; SELECT 2", driver), vec!["SELECT 5--1; SELECT 2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bracketed_and_backtick_names() {
|
||||
for (sql, driver) in [
|
||||
("SELECT * FROM [a;b]", DbDriver::SqlServer),
|
||||
("SELECT * FROM [a]];'b]", DbDriver::SqlServer),
|
||||
("SELECT * FROM `a;b`, `c``;'d`", DbDriver::Sqlite),
|
||||
("SELECT * FROM [c;d], [it's]", DbDriver::Sqlite),
|
||||
("SELECT * FROM [e[;]", DbDriver::Sqlite),
|
||||
] {
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), driver), vec![sql, "SELECT 2"]);
|
||||
assert_eq!(statement_at(sql, 16, driver).map(|s| s.text).as_deref(), Some(sql));
|
||||
}
|
||||
// Array subscripts and literals elsewhere.
|
||||
assert_eq!(texts("SELECT a[1; SELECT 2", DbDriver::Postgres), vec!["SELECT a[1", "SELECT 2"]);
|
||||
assert_eq!(texts("SELECT [1; SELECT 2", DbDriver::Clickhouse), vec!["SELECT [1", "SELECT 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_keeps_literals_whole() {
|
||||
let sql = "SELECT 0; SELECT E'\\';'; SELECT 2";
|
||||
let s = statements_in(sql, 10, sql.len() as u32, DbDriver::Postgres);
|
||||
assert_eq!(s.iter().map(|s| s.text.as_str()).collect::<Vec<_>>(), vec!["SELECT E'\\';'", "SELECT 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_offsets() {
|
||||
let sql = "select '😀';\nselect 2;";
|
||||
|
||||
@@ -26,6 +26,8 @@ pub enum Capability {
|
||||
DatabaseSources,
|
||||
/// Read table metadata of connected project sources; never rows or credentials.
|
||||
DatabaseSchema,
|
||||
/// Execute SQL statements against connected project database sources.
|
||||
DatabaseQuery,
|
||||
VcsRead,
|
||||
VcsWrite,
|
||||
/// The Maven / Gradle dependency graph the IDE resolved.
|
||||
@@ -109,6 +111,7 @@ impl Capability {
|
||||
// A trusted project's own files name the programs the IDE starts (its settings, its
|
||||
// build scripts), so writing them is running code.
|
||||
Self::ProjectWrite
|
||||
| Self::DatabaseQuery
|
||||
| Self::IdeCommands
|
||||
| Self::Ipc(_)
|
||||
| Self::Process(_)
|
||||
@@ -134,6 +137,7 @@ impl Capability {
|
||||
Self::ProjectWrite => "Create and change files in the open project".into(),
|
||||
Self::DatabaseSources => "Manage its own database sources and store their passwords in trusted projects".into(),
|
||||
Self::DatabaseSchema => "Read table structures of connected database sources in trusted projects, without rows or passwords".into(),
|
||||
Self::DatabaseQuery => "Execute SQL queries and statements on connected database sources in trusted projects".into(),
|
||||
Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(),
|
||||
Self::VcsRead => "Read version control state".into(),
|
||||
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
|
||||
@@ -294,6 +298,7 @@ impl fmt::Display for Capability {
|
||||
Self::IdeCommands => f.write_str("ide.commands"),
|
||||
Self::DatabaseSources => f.write_str("database.sources"),
|
||||
Self::DatabaseSchema => f.write_str("database.schema"),
|
||||
Self::DatabaseQuery => f.write_str("database.query"),
|
||||
Self::VcsRead => f.write_str("vcs.read"),
|
||||
Self::VcsWrite => f.write_str("vcs.write"),
|
||||
Self::BuildRead => f.write_str("build.read"),
|
||||
@@ -389,6 +394,7 @@ impl FromStr for Capability {
|
||||
"ide.commands" => Self::IdeCommands,
|
||||
"database.sources" => Self::DatabaseSources,
|
||||
"database.schema" => Self::DatabaseSchema,
|
||||
"database.query" => Self::DatabaseQuery,
|
||||
"vcs.read" => Self::VcsRead,
|
||||
"vcs.write" => Self::VcsWrite,
|
||||
"build.read" => Self::BuildRead,
|
||||
@@ -700,6 +706,23 @@ mod database_tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn database_query_is_a_separate_high_risk_grant_requiring_api21() {
|
||||
let cap: Capability = "database.query".parse().unwrap();
|
||||
assert_eq!(cap, Capability::DatabaseQuery);
|
||||
assert_eq!(cap.to_string(), "database.query");
|
||||
assert_eq!(cap.risk(), Risk::High);
|
||||
assert!(!cap.auto_migrates());
|
||||
for other in [Capability::ProjectRead, Capability::DatabaseSources, Capability::DatabaseSchema] {
|
||||
assert!(!other.covers(&cap));
|
||||
}
|
||||
for (api, valid) in [("^1.20", false), ("^1.21", true)] {
|
||||
let text = format!(
|
||||
"id='query'\nname='Query'\nversion='1.0.0'\nengines.openidea='{api}'\n[capabilities]\nrequired=['database.query']"
|
||||
);
|
||||
assert_eq!(crate::Manifest::parse(&text).is_ok(), valid);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn database_sources_is_a_medium_risk_exact_grant_requiring_api4() {
|
||||
let cap: Capability = "database.sources".parse().unwrap();
|
||||
assert_eq!(cap, Capability::DatabaseSources);
|
||||
|
||||
@@ -430,6 +430,9 @@ impl Manifest {
|
||||
if matches!(cap, Capability::DatabaseSchema) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 20)?;
|
||||
}
|
||||
if matches!(cap, Capability::DatabaseQuery) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 21)?;
|
||||
}
|
||||
if matches!(cap, Capability::Agents) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
|
||||
@@ -319,6 +319,18 @@ impl AutomationService {
|
||||
self.has_enabled_schedules() || self.has_running_runs()
|
||||
}
|
||||
|
||||
/// Whether the local desktop host should stay alive in the background when editor windows close.
|
||||
///
|
||||
/// Independent of `auto_start_service` (the opt-in OS login service that runs `--scheduler`
|
||||
/// after the desktop app quits). Covers both active schedules and in-flight runs (such as a
|
||||
/// manual run or an already-fired one-shot run) so closing the last window does not abort them.
|
||||
pub fn keeps_local_host_alive(&self, host: &Host) -> bool {
|
||||
if !host.global_settings.effective().agents.automations.keep_alive_in_background {
|
||||
return false;
|
||||
}
|
||||
self.has_enabled_schedules() || self.has_running_runs()
|
||||
}
|
||||
|
||||
pub fn has_running_runs(&self) -> bool {
|
||||
self.reconcile_abandoned_claims(None);
|
||||
self.reload_from_disk();
|
||||
|
||||
@@ -516,7 +516,6 @@ impl Host {
|
||||
watch.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.agents.detach_sinks();
|
||||
project.flutter.stop();
|
||||
project.devtools.stop();
|
||||
project.widget_preview.stop();
|
||||
@@ -529,8 +528,11 @@ impl Host {
|
||||
let shutdown_agents = if !project.light
|
||||
&& self.automations.retain_on_window_close(self, &project.root, &project.agents, agent_reason)
|
||||
{
|
||||
// Keep internal automation watchers/peer bridges subscribed while dropping UI sinks.
|
||||
project.agents.detach_ui_sinks();
|
||||
Vec::new()
|
||||
} else {
|
||||
project.agents.detach_sinks();
|
||||
vec![project.agents.clone()]
|
||||
};
|
||||
let handle = self.spawn_project_shutdown(ShutdownWork {
|
||||
|
||||
@@ -687,7 +687,7 @@ Never modifies OS login-service settings (`autoStartService`) or global approval
|
||||
false,
|
||||
json!({
|
||||
"type": "array",
|
||||
"description": "Optional session configuration choices (for example model or reasoning effort)",
|
||||
"description": "Optional session configuration choices (for example model, reasoning effort, or context window)",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
|
||||
@@ -803,6 +803,10 @@ fn shell_invocation(shell: Option<&str>, line: &str) -> (String, Vec<String>) {
|
||||
"cmd" => (line.to_owned(), Vec::new()),
|
||||
"pwsh" | "powershell" => {
|
||||
args.retain(|a| a != "-l");
|
||||
// As in the terminal: script shims such as npm.ps1 run under the default policy.
|
||||
if cfg!(windows) {
|
||||
args.extend(["-ExecutionPolicy".to_owned(), "Bypass".to_owned()]);
|
||||
}
|
||||
args.extend(["-NoLogo".to_owned(), "-Command".to_owned(), line.to_owned()]);
|
||||
(program, args)
|
||||
}
|
||||
@@ -1141,7 +1145,12 @@ mod tests {
|
||||
assert_eq!(shell_invocation(Some("/bin/zsh"), "ls -a").1, ["-l", "-c", "ls -a"]);
|
||||
assert_eq!(shell_invocation(Some("/bin/bash --norc"), "ls").1, ["--norc", "-c", "ls"]);
|
||||
assert_eq!(shell_invocation(Some("/bin/tcsh"), "ls").1, ["-c", "ls"]);
|
||||
assert_eq!(shell_invocation(Some("/usr/bin/pwsh"), "ls").1, ["-NoLogo", "-Command", "ls"]);
|
||||
let pwsh: &[&str] = if cfg!(windows) {
|
||||
&["-ExecutionPolicy", "Bypass", "-NoLogo", "-Command", "ls"]
|
||||
} else {
|
||||
&["-NoLogo", "-Command", "ls"]
|
||||
};
|
||||
assert_eq!(shell_invocation(Some("/usr/bin/pwsh"), "ls").1, pwsh);
|
||||
assert_eq!(shell_invocation(Some("cmd.exe"), "dir /b"), ("dir /b".to_owned(), Vec::new()));
|
||||
}
|
||||
|
||||
|
||||
@@ -939,8 +939,10 @@ impl Walk {
|
||||
continue;
|
||||
}
|
||||
let Ok(in_base) = entry.path.strip_prefix(base) else { continue };
|
||||
let in_base = in_base.to_string_lossy().replace('\\', "/");
|
||||
let mask = self.excludes.iter().find(|(b, _)| b == base).map(|(_, m)| m);
|
||||
if mask.is_some_and(|m| !m.matches(&in_base.to_string_lossy().replace('\\', "/"))) {
|
||||
if mask.is_some_and(|m| !m.matches(&in_base) || (entry.kind == EntryKind::Dir && m.excludes_dir(&in_base)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match entry.kind {
|
||||
|
||||
@@ -763,11 +763,19 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
"Subversion",
|
||||
vec![
|
||||
act("svn.merge", "Merge From…"),
|
||||
act("svn.updateOptions", "Update Directory…"),
|
||||
act("svn.browseRepository", "Browse Repository…"),
|
||||
act("svn.export", "Export…"),
|
||||
act("svn.switchUrl", "Switch to URL…"),
|
||||
act("svn.compareWithBranch", "Compare with Branch…"),
|
||||
act("svn.configureBranches", "Configure Branches…"),
|
||||
SEP,
|
||||
act("svn.cleanup", "Cleanup"),
|
||||
act("svn.lock", "Lock…"),
|
||||
act("svn.unlock", "Unlock"),
|
||||
act("svn.relocate", "Relocate…"),
|
||||
act("svn.properties", "Properties…"),
|
||||
act("svn.copyUrl", "Copy URL"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
|
||||
@@ -142,8 +142,8 @@ pub fn agent_set_additional_args(host: &Host, window: &str, id: String, args: Ve
|
||||
host.project(window)?.agents.set_builtin_additional_args(&id, args)
|
||||
}
|
||||
|
||||
/// Environment variables built-in agent `id` starts with (saved in its agent file);
|
||||
/// an empty map clears them.
|
||||
/// Environment variables built-in agent `id`, or an instance of one, starts with (saved in
|
||||
/// its agent file); an empty map clears them.
|
||||
#[command(trust = trusted)]
|
||||
pub fn agent_set_env(
|
||||
host: &Host,
|
||||
@@ -250,6 +250,42 @@ fn spawn_login_pty(
|
||||
)
|
||||
}
|
||||
|
||||
async fn resolve_login_launch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: &str,
|
||||
) -> IdeResult<(std::path::PathBuf, LoginLaunch, String)> {
|
||||
let agent = id.to_owned();
|
||||
match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let base = agents.base_provider_id(&agent);
|
||||
let launch = host.blocking(move || agents.login_launch(&agent)).await?;
|
||||
Ok((root, launch, base))
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let secrets = host.agent_secrets.clone();
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let (launch, base) = host
|
||||
.blocking(move || {
|
||||
let base = ide_agent::base_provider_id_without_project(Some(&custom_dir), &agent);
|
||||
ide_agent::login_launch_without_project(
|
||||
Some(&custom_dir),
|
||||
Some(secrets.as_ref()),
|
||||
&cwd_for_lookup,
|
||||
&agent,
|
||||
)
|
||||
.map(|launch| (launch, base))
|
||||
})
|
||||
.await?;
|
||||
Ok((cwd, launch, base))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(
|
||||
@@ -261,28 +297,9 @@ pub async fn agent_login_spawn(
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let agent = id.clone();
|
||||
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(&agent)).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, &agent)
|
||||
})
|
||||
.await?;
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
let (cwd, mut launch, base) = resolve_login_launch(host, window, &id).await?;
|
||||
apply_remote_login_env(host, &cwd, false, &mut launch);
|
||||
use_device_auth(host.environment.is_remote(), &id, &mut launch.args);
|
||||
use_device_auth(host.environment.is_remote(), &base, &mut launch.args);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
@@ -306,8 +323,8 @@ pub async fn agent_gh_login_spawn(
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file; refuses built-in and
|
||||
/// ACP Registry ids and taken ids.
|
||||
/// Saves a new custom ACP agent, or an instance of a built-in agent, through its agent
|
||||
/// file; refuses built-in and ACP Registry ids and taken ids.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_custom_save(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
@@ -1890,11 +1907,10 @@ pub async fn agent_memory_set_auto(
|
||||
) -> IdeResult<AgentMemoryCatalog> {
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref());
|
||||
let prov_key = provider
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| ide_agent::memory::normalize_provider_id(s).to_owned());
|
||||
let prov_key = provider.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(|s| {
|
||||
let base = project.as_ref().map(|p| p.agents.base_provider_id(s));
|
||||
ide_agent::memory::normalize_provider_id(base.as_deref().unwrap_or(s)).to_owned()
|
||||
});
|
||||
let apply = |layer: &mut AgentMemorySettings| -> bool {
|
||||
match &prov_key {
|
||||
None => {
|
||||
@@ -2887,6 +2903,45 @@ mod tests {
|
||||
assert!(!ssh_env.contains_key("GH_BROWSER"));
|
||||
assert!(!ssh_env.contains_key("GLAMOUR_STYLE"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn resolve_login_launch_without_project_reads_instance_env_from_secrets() {
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = Host::new(crate::HostConfig {
|
||||
config_dir: tmp.path().join("config"),
|
||||
data_dir: tmp.path().join("data"),
|
||||
local_data_dir: tmp.path().join("data"),
|
||||
languages: std::sync::Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: std::sync::Arc::default(),
|
||||
sink_for: Box::new(|_| std::sync::Arc::new(ide_core::NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let bin = tmp.path().join(if cfg!(windows) { "claude.cmd" } else { "claude" });
|
||||
std::fs::write(&bin, if cfg!(windows) { "@echo off\r\n" } else { "#!/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 agents_dir = host.config_dir.join("agents");
|
||||
std::fs::create_dir_all(&agents_dir).unwrap();
|
||||
std::fs::write(
|
||||
agents_dir.join("claude.toml"),
|
||||
format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(agents_dir.join("claude-work.toml"), "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"\"\n")
|
||||
.unwrap();
|
||||
host.agent_secrets.set("agent/claude-work/env/CLAUDE_CONFIG_DIR", "/home/me/.claude-work").unwrap();
|
||||
|
||||
let (_, launch, base) = resolve_login_launch(&host, "no-project", "claude-work").await.unwrap();
|
||||
assert_eq!(base, "claude");
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
|
||||
@@ -12,7 +12,9 @@ use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
|
||||
use ide_build::jbuild::Target;
|
||||
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
|
||||
use ide_build::maven::sources;
|
||||
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
|
||||
use ide_build::maven::{
|
||||
PomGoto, PomManagedDeclaration, PomNavigationOptions, default_local_repo, local_repository_of, user_settings_file,
|
||||
};
|
||||
use ide_build::pom_edit::{ArtifactKey, Exclusion};
|
||||
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
|
||||
use ide_core::settings::Settings;
|
||||
@@ -74,14 +76,7 @@ fn maven_modules(
|
||||
/// the Maven home and options from Settings › Maven.
|
||||
pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
let jdk = ide_sdk::apply::project_jdk(root, settings);
|
||||
let mut model = ide_build::load_linked_with_jdk(
|
||||
root,
|
||||
cache,
|
||||
ide_sdk::apply::maven_local_repository(root, settings),
|
||||
&settings.languages.java.maven,
|
||||
&settings.languages.java.gradle,
|
||||
ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major),
|
||||
);
|
||||
let mut model = load_synced(root, cache, settings);
|
||||
if let Some(m) = &mut model.maven {
|
||||
let mvn = ide_sdk::apply::maven_command(root, settings);
|
||||
let options = ide_sdk::apply::maven_options(root, settings);
|
||||
@@ -127,6 +122,49 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
model
|
||||
}
|
||||
|
||||
/// The build model as [`sync_options`] syncs it: a load that differs in the JDK or the linked
|
||||
/// projects finds its own last sync out of date.
|
||||
fn load_synced(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
|
||||
ide_build::load_linked_with_jdk(
|
||||
root,
|
||||
cache,
|
||||
ide_sdk::apply::maven_local_repository(root, settings),
|
||||
&settings.languages.java.maven,
|
||||
&settings.languages.java.gradle,
|
||||
maven_jdk_version(root, settings),
|
||||
)
|
||||
}
|
||||
|
||||
/// The JDK `<activation><jdk>` profiles are matched against.
|
||||
fn maven_jdk_version(root: &Path, settings: &Settings) -> Option<u32> {
|
||||
ide_sdk::apply::maven_jdk(root, settings, None).map(|jdk| jdk.major)
|
||||
}
|
||||
|
||||
fn sync_options(
|
||||
root: &Path,
|
||||
settings: &Settings,
|
||||
current: &BuildModel,
|
||||
offline: bool,
|
||||
profiles: &[String],
|
||||
) -> SyncOptions {
|
||||
let env = current
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|m| m.projects.iter().find(|p| !p.env.is_empty()))
|
||||
.map(|p| p.env.clone())
|
||||
.unwrap_or_default();
|
||||
SyncOptions {
|
||||
offline,
|
||||
profiles: profiles.to_vec(),
|
||||
env,
|
||||
jdk_version: maven_jdk_version(root, settings),
|
||||
maven_command: ide_sdk::apply::maven_command(root, settings).map(|p| p.to_string_lossy().into_owned()),
|
||||
maven_options: ide_sdk::apply::maven_options(root, settings),
|
||||
maven_settings: settings.languages.java.maven.clone(),
|
||||
gradle_command: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// POM navigation follows the same profile choices as the last Maven sync and
|
||||
/// resolves JDK-activated profiles with the project's selected Maven runtime.
|
||||
fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigationOptions {
|
||||
@@ -140,7 +178,7 @@ fn pom_navigation_options(project: &Project, settings: &Settings) -> PomNavigati
|
||||
local_repo: ide_sdk::apply::maven_local_repository(&project.root, settings)
|
||||
.or_else(ide_build::maven::default_local_repo),
|
||||
profiles,
|
||||
jdk_version: ide_sdk::apply::maven_jdk(&project.root, settings, None).map(|jdk| jdk.major),
|
||||
jdk_version: maven_jdk_version(&project.root, settings),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,6 +239,57 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
|
||||
blocking(move || workspace::load_project(&project, &config)).await
|
||||
}
|
||||
|
||||
/// Settings › Build Tools › Maven: the local repository the field's placeholder shows —
|
||||
/// the `<localRepository>` of the user settings file (the configured one, else
|
||||
/// `~/.m2/settings.xml`), then of the Maven home's global `conf/settings.xml`, then
|
||||
/// `~/.m2/repository`. Reads files only; `home` may name `bin` or the `mvn` executable.
|
||||
#[command(trust = always)]
|
||||
pub async fn maven_local_repository(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
home: Option<String>,
|
||||
user_settings: Option<String>,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
let settings =
|
||||
ide_core::settings::MavenSettings { user_settings: user_settings.unwrap_or_default(), ..Default::default() };
|
||||
blocking(move || {
|
||||
let user = user_settings_file(&root, &settings);
|
||||
let global = home
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(maven_installation_root)
|
||||
.map(|h| h.join("conf").join("settings.xml"));
|
||||
let repository = user
|
||||
.and_then(|settings| local_repository_of(&settings))
|
||||
.or_else(|| global.and_then(|settings| local_repository_of(&settings)))
|
||||
.or_else(default_local_repo);
|
||||
Ok(repository.map(|p| ide_core::ipc_path::to_ipc(&p)))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// The Maven installation `home` names: a path to `bin`, `bin/mvn(.cmd|.bat)` or `mvn`
|
||||
/// itself is reduced to the installation root. Either separator is accepted, so a Windows
|
||||
/// path is reduced on any host.
|
||||
fn maven_installation_root(home: &str) -> PathBuf {
|
||||
let mut root = home.trim().trim_end_matches(['/', '\\']);
|
||||
fn last(s: &str) -> String {
|
||||
s.rsplit(['/', '\\']).next().unwrap_or(s).to_ascii_lowercase()
|
||||
}
|
||||
fn parent(s: &str) -> &str {
|
||||
s.rfind(['/', '\\']).map_or("", |i| &s[..i])
|
||||
}
|
||||
if matches!(last(root).as_str(), "bin" | "mvn" | "mvn.cmd" | "mvn.bat") {
|
||||
root = parent(root);
|
||||
if last(root) == "bin" {
|
||||
root = parent(root);
|
||||
}
|
||||
}
|
||||
PathBuf::from(root)
|
||||
}
|
||||
|
||||
/// Settings › CMake and the toolbar switcher: every profile, saved ones then presets (with
|
||||
/// whether each is enabled), and why the presets file cannot be read, if it cannot.
|
||||
#[derive(Clone, Debug, serde::Serialize, specta::Type)]
|
||||
@@ -524,21 +613,7 @@ pub async fn build_sync(
|
||||
false
|
||||
});
|
||||
}
|
||||
let env = current
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|m| m.projects.iter().find(|p| !p.env.is_empty()))
|
||||
.map(|p| p.env.clone())
|
||||
.unwrap_or_default();
|
||||
let options = SyncOptions {
|
||||
offline,
|
||||
profiles: profiles.clone(),
|
||||
env,
|
||||
maven_command: ide_sdk::apply::maven_command(root, settings).map(|p| p.to_string_lossy().into_owned()),
|
||||
maven_options: ide_sdk::apply::maven_options(root, settings),
|
||||
maven_settings: settings.languages.java.maven.clone(),
|
||||
gradle_command: None,
|
||||
};
|
||||
let options = sync_options(root, settings, ¤t, offline, &profiles);
|
||||
let progress = |p: SyncProgress| {
|
||||
let _ = on_progress.send(p);
|
||||
};
|
||||
@@ -808,14 +883,7 @@ pub(crate) fn analyzed_dependencies(
|
||||
) -> IdeResult<crate::plugins::BuildGraph> {
|
||||
let mut graph = crate::plugins::BuildGraph::default();
|
||||
for scope in workspace::scopes(project, config)?.iter().filter(|s| root == project.root || s.root == root) {
|
||||
let settings = &scope.settings;
|
||||
let model = ide_build::load_linked(
|
||||
&scope.root,
|
||||
&scope.cache,
|
||||
ide_sdk::apply::maven_local_repository(&scope.root, settings),
|
||||
&settings.languages.java.maven,
|
||||
&settings.languages.java.gradle,
|
||||
);
|
||||
let model = load_synced(&scope.root, &scope.cache, &scope.settings);
|
||||
graph.maven.extend(model.maven.into_iter().flat_map(|m| m.projects));
|
||||
for build in &model.gradle {
|
||||
let reports =
|
||||
@@ -1513,6 +1581,53 @@ pub async fn build_dotnet_format(
|
||||
request: RequestId,
|
||||
clear: Vec<std::path::PathBuf>,
|
||||
on_event: Channel<BuildEvent>,
|
||||
) -> IdeResult<BuildResult> {
|
||||
let plan = move |file: &Path| compile::dotnet_format_plan(file, verify);
|
||||
run_dotnet_plan(host, window, file, plan, request, clear, on_event).await
|
||||
}
|
||||
|
||||
/// Publish a .NET project: `dotnet publish <file> <options>`, streaming like a build;
|
||||
/// cancellable with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn build_dotnet_publish(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
file: std::path::PathBuf,
|
||||
options: Vec<String>,
|
||||
request: RequestId,
|
||||
clear: Vec<std::path::PathBuf>,
|
||||
on_event: Channel<BuildEvent>,
|
||||
) -> IdeResult<BuildResult> {
|
||||
let plan = move |file: &Path| compile::dotnet_publish_plan(file, &options);
|
||||
run_dotnet_plan(host, window, file, plan, request, clear, on_event).await
|
||||
}
|
||||
|
||||
/// `dotnet build` / `clean` / `restore` of a solution or project from the .NET tool window,
|
||||
/// streaming like a build; cancellable with `cancel_request(request)`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn build_dotnet_command(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
file: std::path::PathBuf,
|
||||
command: compile::DotnetCommand,
|
||||
options: Vec<String>,
|
||||
request: RequestId,
|
||||
clear: Vec<std::path::PathBuf>,
|
||||
on_event: Channel<BuildEvent>,
|
||||
) -> IdeResult<BuildResult> {
|
||||
let plan = move |file: &Path| compile::dotnet_command_plan(file, command, &options);
|
||||
run_dotnet_plan(host, window, file, plan, request, clear, on_event).await
|
||||
}
|
||||
|
||||
async fn run_dotnet_plan(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
file: std::path::PathBuf,
|
||||
plan: impl FnOnce(&Path) -> IdeResult<compile::BuildPlan> + Send + 'static,
|
||||
request: RequestId,
|
||||
clear: Vec<std::path::PathBuf>,
|
||||
on_event: Channel<BuildEvent>,
|
||||
) -> IdeResult<BuildResult> {
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
@@ -1527,7 +1642,7 @@ pub async fn build_dotnet_format(
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
let plan = compile::dotnet_format_plan(&file, verify)?;
|
||||
let plan = plan(&file)?;
|
||||
let result = compile::run(&root, &plan, &token, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})?;
|
||||
@@ -1740,6 +1855,58 @@ mod build_tool_settings_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each root (a project, or a member of a workspace) with its own JDK and a linked reactor.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_maven_sync_is_current_for_the_jdk_of_its_root() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let mvn = base.join("maven/bin/mvn");
|
||||
std::fs::create_dir_all(mvn.parent().unwrap()).unwrap();
|
||||
std::fs::write(&mvn, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&mvn, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
for (name, version) in [("jdk8", "1.8"), ("jdk17", "17"), ("jdk21", "21")] {
|
||||
let home = base.join(name);
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("bin/java"), "").unwrap();
|
||||
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"{version}\"\n")).unwrap();
|
||||
}
|
||||
let reactor = |dir: &Path, jdk: &str| {
|
||||
std::fs::create_dir_all(dir.join("extra")).unwrap();
|
||||
let pom = format!(
|
||||
"<project><groupId>g</groupId><artifactId>a</artifactId><version>1</version><packaging>pom</packaging>\
|
||||
<profiles><profile><id>p</id><activation><jdk>{jdk}</jdk></activation>\
|
||||
<modules><module>extra</module></modules></profile></profiles></project>"
|
||||
);
|
||||
std::fs::write(dir.join("pom.xml"), pom).unwrap();
|
||||
let module = "<project><groupId>g</groupId><artifactId>extra</artifactId><version>1</version></project>";
|
||||
std::fs::write(dir.join("extra/pom.xml"), module).unwrap();
|
||||
};
|
||||
let scope = |name: &str, jdk: &str| {
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.jdk = base.join(jdk).to_string_lossy().into_owned();
|
||||
settings.languages.java.maven.home = base.join("maven").to_string_lossy().into_owned();
|
||||
settings.languages.java.maven.linked_projects = vec!["linked/pom.xml".into()];
|
||||
(base.join(name), base.join(name).join("cache"), settings)
|
||||
};
|
||||
let maven = |(root, cache, settings): &(PathBuf, PathBuf, Settings)| {
|
||||
load(root, cache, settings).maven.map(|m| (m.projects.len(), m.stale)).unwrap()
|
||||
};
|
||||
let scopes = [scope("first", "jdk8"), scope("second", "jdk17"), scope("third", "jdk21")];
|
||||
for scope in &scopes {
|
||||
let (root, cache, settings) = scope;
|
||||
reactor(root, "[11,)");
|
||||
reactor(&root.join("linked"), "[21,)");
|
||||
let current = load(root, cache, settings);
|
||||
let options = sync_options(root, settings, ¤t, false, &[]);
|
||||
ide_build::sync_maven(root, cache, &options, &ide_core::CancellationToken::new(), &|_| {}).unwrap();
|
||||
}
|
||||
assert_eq!(scopes.each_ref().map(maven), [(2, false), (3, false), (4, false)]);
|
||||
assert_eq!(maven(&scope("second", "jdk8")), (2, true));
|
||||
assert_eq!(maven(&scope("second", "jdk21")), (4, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_for_sync_tasks_and_compile_uses_gradle_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1931,7 +2098,9 @@ mod maven_completion_tests {
|
||||
ide_command::domain!(
|
||||
build:
|
||||
build_compile_file,
|
||||
build_dotnet_command,
|
||||
build_dotnet_format,
|
||||
build_dotnet_publish,
|
||||
build_model,
|
||||
build_run,
|
||||
build_sync,
|
||||
@@ -1946,11 +2115,29 @@ ide_command::domain!(
|
||||
maven_dependency_declaration,
|
||||
maven_exclude_dependency,
|
||||
maven_goto_declaration,
|
||||
maven_local_repository,
|
||||
maven_managed_declarations,
|
||||
toolchain_check,
|
||||
toolchains_detect,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod maven_installation_root_tests {
|
||||
use super::maven_installation_root;
|
||||
|
||||
#[test]
|
||||
fn reduces_bin_and_mvn_paths_to_the_installation_root() {
|
||||
assert_eq!(maven_installation_root("/opt/maven-3.9"), std::path::PathBuf::from("/opt/maven-3.9"));
|
||||
assert_eq!(maven_installation_root("/opt/maven-3.9/bin"), std::path::PathBuf::from("/opt/maven-3.9"));
|
||||
assert_eq!(maven_installation_root("/opt/maven-3.9/bin/mvn"), std::path::PathBuf::from("/opt/maven-3.9"));
|
||||
assert_eq!(
|
||||
maven_installation_root("C:\\tools\\maven\\bin\\mvn.cmd"),
|
||||
std::path::PathBuf::from("C:\\tools\\maven")
|
||||
);
|
||||
assert_eq!(maven_installation_root(" /opt/maven-3.9/ "), std::path::PathBuf::from("/opt/maven-3.9"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cmake_reset_tests {
|
||||
use super::reset_cmake_cache;
|
||||
|
||||
@@ -2369,6 +2369,7 @@ pub async fn lsp_execute_command(host: &Host, window: &str, doc: DocId, command:
|
||||
path: snap.path.0.clone(),
|
||||
language: snap.language.0,
|
||||
selections: vec![],
|
||||
visible_lines: None,
|
||||
}),
|
||||
selected_paths: vec![snap.path.0],
|
||||
..Default::default()
|
||||
@@ -2410,6 +2411,7 @@ async fn run_plugin_server_command(
|
||||
path: snap.path.0.clone(),
|
||||
language: snap.language.0,
|
||||
selections: vec![],
|
||||
visible_lines: None,
|
||||
}),
|
||||
selected_paths: vec![snap.path.0],
|
||||
..Default::default()
|
||||
|
||||
@@ -527,6 +527,10 @@ async fn start_inner(
|
||||
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
|
||||
}
|
||||
let run_dir = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
// A single Java source file runs on the project's JDK: JDK 6/8 compile it with javac
|
||||
// first (their launchers have no JEP 330 source mode), and its Eclipse module's class
|
||||
// path is honoured. The rewritten command starts below like any other.
|
||||
java_file::prepare(&project.root, root, &settings, &mut config, &on_output, cancel).await?;
|
||||
add_java_agents(&mut config, &on_output, Some(&run_dir));
|
||||
if config.command == ide_sdk::godot::COMMAND {
|
||||
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
|
||||
@@ -930,6 +934,7 @@ pub async fn run_attach(host: &Host, window: &str, id: RunId, on_output: Channel
|
||||
|
||||
pub mod commands;
|
||||
pub(crate) mod container;
|
||||
mod java_file;
|
||||
pub use commands::*;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,609 @@
|
||||
//! One Java source file run from the gutter (`kind == "java-file"`).
|
||||
//!
|
||||
//! JDK 11+ starts the file with the source launcher (`java Hi.java`, JEP 330). Older JDKs
|
||||
//! have no source launcher, so the file is compiled with that JDK's `javac` and started
|
||||
//! with `java -cp`. A nearby Eclipse project's `.classpath` supplies the source folders,
|
||||
//! library jars and encoding, together with the workspace projects it references (legacy
|
||||
//! code shares classes between projects); the compiled classes go to a cache directory,
|
||||
//! never into the project.
|
||||
use super::Emit;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_run::{OutputChunk, RunConfig};
|
||||
use ide_sdk::java::Jdk;
|
||||
use ide_workspace::roots::eclipse;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A large project can take a while to compile; the run is cancelled with the request.
|
||||
const COMPILE_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
/// What the Eclipse project around the file declares in its `.classpath`.
|
||||
#[derive(Debug)]
|
||||
struct JavaFileModule {
|
||||
/// Directory of the Eclipse project (holds `.classpath`).
|
||||
dir: PathBuf,
|
||||
sources: Vec<PathBuf>,
|
||||
libraries: Vec<PathBuf>,
|
||||
/// Eclipse's per-project source encoding (`GBK`, `UTF-8`, …), when it declares one.
|
||||
encoding: Option<String>,
|
||||
}
|
||||
|
||||
impl JavaFileModule {
|
||||
/// The innermost Eclipse project above `file` (within `boundary`).
|
||||
fn of(file: &Path, boundary: &Path) -> Option<Self> {
|
||||
let mut ancestors = file.parent()?.ancestors().take_while(|dir| dir.starts_with(boundary));
|
||||
let (dir, cp) = ancestors.find_map(|dir| eclipse::classpath(dir).map(|cp| (dir, cp)))?;
|
||||
Self::at(dir, &cp, boundary)
|
||||
}
|
||||
|
||||
/// The module `dir` itself declares, if it has a `.classpath`, and its Eclipse project
|
||||
/// references: legacy workspaces share the model between projects (`/htlib`, `/htmzbase`).
|
||||
fn at(dir: &Path, cp: &eclipse::EclipseClasspath, boundary: &Path) -> Option<Self> {
|
||||
let mut module = Self {
|
||||
dir: dir.to_path_buf(),
|
||||
sources: Vec::new(),
|
||||
libraries: Vec::new(),
|
||||
encoding: eclipse_encoding(dir),
|
||||
};
|
||||
let mut seen = Vec::new();
|
||||
collect_eclipse(dir, cp, boundary, false, &mut seen, &mut module);
|
||||
Some(module)
|
||||
}
|
||||
}
|
||||
|
||||
/// Eclipse's build path: the project's source folders and jars, and those of every Eclipse
|
||||
/// project it references (their output folder, jars and sources, transitively). The module's
|
||||
/// own output folder is left out: the file is compiled into a fresh directory, not against
|
||||
/// classes of an older build.
|
||||
fn collect_eclipse(
|
||||
dir: &Path,
|
||||
cp: &eclipse::EclipseClasspath,
|
||||
boundary: &Path,
|
||||
referenced: bool,
|
||||
seen: &mut Vec<PathBuf>,
|
||||
module: &mut JavaFileModule,
|
||||
) {
|
||||
if seen.iter().any(|seen| seen == dir) {
|
||||
return;
|
||||
}
|
||||
seen.push(dir.to_path_buf());
|
||||
let resolve = |path: &str| ide_core::project_roots::resolve(dir, Path::new(path));
|
||||
for (source, _) in &cp.sources {
|
||||
push_unique(&mut module.sources, resolve(source), Path::is_dir);
|
||||
}
|
||||
if referenced && let Some(output) = &cp.output {
|
||||
push_unique(&mut module.libraries, resolve(output), Path::exists);
|
||||
}
|
||||
for library in &cp.libraries {
|
||||
// `/OtherProject/lib.jar` names a jar of another project of the workspace.
|
||||
let path = match library.strip_prefix('/').and_then(|rest| rest.split_once('/')) {
|
||||
Some((project, rest)) => eclipse::referenced_project(dir, project, boundary).map(|dir| dir.join(rest)),
|
||||
None => Some(resolve(library)),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
push_unique(&mut module.libraries, path, Path::exists);
|
||||
}
|
||||
}
|
||||
for project in &cp.projects {
|
||||
let Some(other) = eclipse::referenced_project(dir, project, boundary) else { continue };
|
||||
if let Some(cp) = eclipse::classpath(&other) {
|
||||
collect_eclipse(&other, &cp, boundary, true, seen, module);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_unique(paths: &mut Vec<PathBuf>, path: PathBuf, usable: impl Fn(&Path) -> bool) {
|
||||
if usable(&path) && !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The JDK the file runs on: the module's, the project's, else one that can compile the
|
||||
/// project's language level (JDK 6 is a full JDK and works here).
|
||||
fn java_jdk(root: &Path, module: Option<&Path>, settings: &Settings) -> Option<Jdk> {
|
||||
let module = module.unwrap_or(root);
|
||||
ide_sdk::apply::module_jdk(root, module, settings).or_else(|| {
|
||||
let level = ide_sdk::apply::effective_java_language_level(root, module, settings)
|
||||
.and_then(ide_build::compile::language_release);
|
||||
let installed = ide_sdk::java::installed_jdks();
|
||||
ide_sdk::java::pick_jdk(&installed, level).cloned()
|
||||
})
|
||||
}
|
||||
|
||||
fn jdk_bin(home: &Path, name: &str) -> PathBuf {
|
||||
let name = if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
|
||||
home.join("bin").join(name)
|
||||
}
|
||||
|
||||
/// Whether a launcher argument names a Java source file; no lowercased copy is allocated.
|
||||
fn is_java_source(arg: &str) -> bool {
|
||||
arg.as_bytes().get(arg.len().saturating_sub(5)..).is_some_and(|tail| tail.eq_ignore_ascii_case(b".java"))
|
||||
}
|
||||
|
||||
fn file_name(path: &Path) -> String {
|
||||
path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Eclipse's source encoding for the project at `dir`
|
||||
/// (`.settings/org.eclipse.core.resources.prefs`, `encoding/<project>=…`).
|
||||
fn eclipse_encoding(dir: &Path) -> Option<String> {
|
||||
let prefs = std::fs::read_to_string(dir.join(".settings/org.eclipse.core.resources.prefs")).ok()?;
|
||||
let key = std::fs::read_to_string(dir.join(".project"))
|
||||
.ok()
|
||||
.and_then(|project| project_name(&project))
|
||||
.map(|name| format!("encoding/{name}"));
|
||||
prefs.lines().find_map(|line| {
|
||||
let (line_key, value) = line.split_once('=')?;
|
||||
let line_key = line_key.trim();
|
||||
let wanted = key.as_deref().map_or_else(|| line_key.starts_with("encoding/"), |key| line_key == key);
|
||||
wanted.then(|| value.trim().to_owned()).filter(|value| !value.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
/// The `<name>` of an Eclipse `.project` file.
|
||||
fn project_name(project: &str) -> Option<String> {
|
||||
let start = project.find("<name>")? + "<name>".len();
|
||||
let end = project[start..].find("</name>")? + start;
|
||||
Some(project[start..end].trim().to_owned())
|
||||
}
|
||||
|
||||
fn join_paths(paths: &[PathBuf]) -> String {
|
||||
std::env::join_paths(paths).map(|paths| paths.to_string_lossy().into_owned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The class javac writes for the file: its package declaration and the file stem.
|
||||
fn class_name(file: &Path, package: Option<&str>) -> String {
|
||||
let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
match package {
|
||||
Some(package) => format!("{package}.{stem}"),
|
||||
None => stem,
|
||||
}
|
||||
}
|
||||
|
||||
/// The source root the package declaration implies (`…/src/main/java` for
|
||||
/// `…/src/main/java/com/example/Hi.java` in `com.example`), else the file's folder.
|
||||
fn package_root(file: &Path, package: Option<&str>) -> Option<PathBuf> {
|
||||
let mut dir = file.parent()?;
|
||||
for part in package.unwrap_or_default().split('.').filter(|part| !part.is_empty()).rev() {
|
||||
if dir.file_name().is_none_or(|name| name != part) {
|
||||
return file.parent().map(Path::to_path_buf);
|
||||
}
|
||||
dir = dir.parent()?;
|
||||
}
|
||||
Some(dir.to_path_buf())
|
||||
}
|
||||
|
||||
/// The package declaration sits at the top; no need to read a large source file whole.
|
||||
const PACKAGE_SCAN_BYTES: u64 = 64 * 1024;
|
||||
|
||||
/// The `package a.b.c;` declaration, read as ASCII so a legacy (GBK) file still works.
|
||||
fn package_name(file: &Path) -> Option<String> {
|
||||
let mut head = Vec::new();
|
||||
std::fs::File::open(file).ok()?.take(PACKAGE_SCAN_BYTES).read_to_end(&mut head).ok()?;
|
||||
String::from_utf8_lossy(&head).lines().find_map(|line| {
|
||||
let rest = line.trim().strip_prefix("package ")?;
|
||||
Some(rest.split(';').next()?.trim().to_owned()).filter(|name| !name.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
/// A stable directory per source file, so a rebuild reuses classes of unchanged files.
|
||||
fn compile_dir(file: &Path) -> PathBuf {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
file.hash(&mut hasher);
|
||||
let stem: String = file
|
||||
.file_stem()
|
||||
.map(|stem| stem.to_string_lossy().into_owned())
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' })
|
||||
.collect();
|
||||
std::env::temp_dir().join("openidea-run").join(format!("java-{stem}-{:x}", hasher.finish()))
|
||||
}
|
||||
|
||||
/// Replaces `config` with `java -cp <project> <class>` after compiling the file with the
|
||||
/// JDK's own `javac`; leaves it alone when the JDK supports the source launcher and the
|
||||
/// file needs no project class path.
|
||||
pub(super) async fn prepare(
|
||||
project_root: &Path,
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
config: &mut RunConfig,
|
||||
on_output: &Emit<OutputChunk>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<()> {
|
||||
if config.kind != "java-file" {
|
||||
return Ok(());
|
||||
}
|
||||
// Debugging prefixes the launcher's arguments with the JDWP agent and the configuration's
|
||||
// VM options (`java -agentlib:jdwp=… Hi.java`); they stay in front of the rewritten
|
||||
// command, and anything after the file is a program argument. The other launcher form,
|
||||
// `javac … && java -cp …`, has no source file among its arguments and is left alone.
|
||||
let at = ide_run::java_cmdline::vm_options_end(&config.args);
|
||||
if !config.args.get(at).is_some_and(|arg| is_java_source(arg)) {
|
||||
return Ok(());
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// The process starts in the project root plus `cwd` (see `start_inner`); the argument
|
||||
// is relative to that, not to a workspace member's settings root.
|
||||
let cwd = project_root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
let file = {
|
||||
let path = PathBuf::from(&config.args[at]);
|
||||
if path.is_absolute() { path } else { ide_core::project_roots::resolve(&cwd, &path) }
|
||||
};
|
||||
if !file.is_file() {
|
||||
// The launcher reports the missing file with its own message.
|
||||
return Ok(());
|
||||
}
|
||||
// Reading `.classpath` files and the first scan for installed JDKs touch the disk.
|
||||
let (module, jdk) = {
|
||||
let (file, project_root, root, settings) =
|
||||
(file.clone(), project_root.to_path_buf(), root.to_path_buf(), settings.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let module = JavaFileModule::of(&file, &project_root);
|
||||
let jdk = java_jdk(&root, module.as_ref().map(|m| m.dir.as_path()), &settings);
|
||||
(module, jdk)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
};
|
||||
let Some(jdk) = jdk else {
|
||||
// No JDK resolved: keep the bare `java` of the configuration.
|
||||
return Ok(());
|
||||
};
|
||||
let java = ide_sdk::java::java_executable(&jdk.home);
|
||||
let has_module_classpath = module.as_ref().is_some_and(|m| !m.sources.is_empty() || !m.libraries.is_empty());
|
||||
if jdk.major >= 11 && !has_module_classpath {
|
||||
// A standalone file: the source launcher is enough, on the project's own JDK.
|
||||
config.command = java.to_string_lossy().into_owned();
|
||||
return Ok(());
|
||||
}
|
||||
let javac = jdk_bin(&jdk.home, "javac");
|
||||
if !javac.is_file() {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Running '{}' on JDK {} needs javac, and {} does not exist. Set a full JDK as the project SDK.",
|
||||
file_name(&file),
|
||||
jdk.major,
|
||||
javac.display()
|
||||
)));
|
||||
}
|
||||
let sources = module.as_ref().map(|m| m.sources.as_slice()).unwrap_or_default();
|
||||
let libraries = module.as_ref().map(|m| m.libraries.as_slice()).unwrap_or_default();
|
||||
let out = compile_dir(&file);
|
||||
std::fs::create_dir_all(&out).map_err(|e| IdeError::internal(format!("Cannot create {} ({e})", out.display())))?;
|
||||
let mut args: Vec<String> = vec!["-g".into(), "-d".into(), out.to_string_lossy().into_owned()];
|
||||
if !libraries.is_empty() {
|
||||
args.extend(["-cp".into(), join_paths(libraries)]);
|
||||
}
|
||||
// Sources outside the file's own file are compiled on demand (`-implicit`), so a
|
||||
// reference to another class of the project ends up in the same output directory.
|
||||
let package = package_name(&file);
|
||||
let source_path = if sources.is_empty() {
|
||||
package_root(&file, package.as_deref()).into_iter().collect()
|
||||
} else {
|
||||
sources.to_vec()
|
||||
};
|
||||
if !source_path.is_empty() {
|
||||
args.extend(["-sourcepath".into(), join_paths(&source_path)]);
|
||||
}
|
||||
if let Some(encoding) = module.as_ref().and_then(|m| m.encoding.as_deref()) {
|
||||
args.extend(["-encoding".into(), encoding.to_owned()]);
|
||||
}
|
||||
args.push(file.to_string_lossy().into_owned());
|
||||
|
||||
let class = class_name(&file, package.as_deref());
|
||||
let cwd = file.parent().map(Path::to_path_buf).unwrap_or(cwd);
|
||||
let javac_args = args;
|
||||
let javac_program = javac.clone();
|
||||
let compiled = tokio::time::timeout(
|
||||
COMPILE_TIMEOUT,
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut command = Command::new(&javac_program);
|
||||
command.args(&javac_args).current_dir(&cwd).stdin(Stdio::null());
|
||||
// A release build is a GUI process: without CREATE_NO_WINDOW, Windows opens a
|
||||
// console window for javac (a dev build shares its launcher's console instead).
|
||||
ide_core::process::prepare(&mut command).output()
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable("Compiling the Java file timed out"))?
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let output = match compiled {
|
||||
Ok(output) => output,
|
||||
Err(e) => {
|
||||
return Err(IdeError::unavailable(format!("Cannot run {} ({e})", javac.display())));
|
||||
}
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let stdout = ide_core::output_encoding::decode_tool_output(&output.stdout);
|
||||
let stderr = ide_core::output_encoding::decode_tool_output(&output.stderr);
|
||||
// The first diagnostic is the failure message; take it before `stderr` is emitted.
|
||||
let failure = (!output.status.success())
|
||||
.then(|| stderr.lines().find(|line| !line.trim().is_empty()).unwrap_or("javac failed").trim().to_owned());
|
||||
if !stdout.trim().is_empty() {
|
||||
on_output(OutputChunk::System { text: with_newline(stdout) });
|
||||
}
|
||||
if !stderr.trim().is_empty() {
|
||||
on_output(OutputChunk::Stderr { text: with_newline(stderr) });
|
||||
}
|
||||
if let Some(detail) = failure {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Compiling '{}' with JDK {} failed: {detail}",
|
||||
file_name(&file),
|
||||
jdk.major
|
||||
)));
|
||||
}
|
||||
let class_file = out.join(format!("{}.class", class.replace('.', "/")));
|
||||
if !class_file.is_file() {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"javac did not write {}; check the package and the public class name of the file",
|
||||
class_file.display()
|
||||
)));
|
||||
}
|
||||
let mut class_paths = vec![out];
|
||||
class_paths.extend(libraries.iter().cloned());
|
||||
let mut rewritten = config.args[..at].to_vec();
|
||||
rewritten.extend(["-cp".into(), join_paths(&class_paths), class]);
|
||||
rewritten.extend(config.args[at + 1..].iter().cloned());
|
||||
config.command = java.to_string_lossy().into_owned();
|
||||
config.args = rewritten;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn with_newline(mut text: String) -> String {
|
||||
if !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::settings::Settings;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn write(path: &Path, text: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn file_config(_file: &Path, args: Vec<String>) -> RunConfig {
|
||||
RunConfig {
|
||||
id: "java-file:test".into(),
|
||||
name: "Hi".into(),
|
||||
kind: "java-file".into(),
|
||||
command: "java".into(),
|
||||
args,
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: true,
|
||||
is_test: false,
|
||||
debug_adapter: Some("java-debug".into()),
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn no_output() -> Emit<OutputChunk> {
|
||||
Arc::new(|_chunk: OutputChunk| {})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn class_names_follow_the_source_root_and_the_package_declaration() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let src = dir.path().join("src");
|
||||
let file = src.join("com/example/Hi.java");
|
||||
write(&file, "package com.example;\nclass Hi {}\n");
|
||||
let package = package_name(&file);
|
||||
assert_eq!(class_name(&file, package.as_deref()), "com.example.Hi");
|
||||
assert_eq!(package_root(&file, package.as_deref()), Some(src));
|
||||
// A Maven layout: the root is where the package path starts, not the `src` folder.
|
||||
let maven = dir.path().join("app/src/main/java/a/b/Hi.java");
|
||||
write(&maven, "package a.b;\npublic class Hi {}\n");
|
||||
let package = package_name(&maven);
|
||||
assert_eq!(class_name(&maven, package.as_deref()), "a.b.Hi");
|
||||
assert_eq!(package_root(&maven, package.as_deref()), Some(dir.path().join("app/src/main/java")));
|
||||
// A folder that does not match the package: javac still finds the file itself.
|
||||
let loose = dir.path().join("other/Hi.java");
|
||||
write(&loose, "package a.b;\npublic class Hi {}\n");
|
||||
let package = package_name(&loose);
|
||||
assert_eq!(class_name(&loose, package.as_deref()), "a.b.Hi");
|
||||
assert_eq!(package_root(&loose, package.as_deref()), Some(dir.path().join("other")));
|
||||
assert_eq!(package_root(&loose, None), Some(dir.path().join("other")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eclipse_modules_supply_sources_libraries_and_the_source_encoding() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let project = dir.path().join("proj");
|
||||
write(
|
||||
&project.join(".classpath"),
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<classpath>
|
||||
<classpathentry kind="src" path="src"/>
|
||||
<classpathentry kind="lib" path="lib/dep.jar"/>
|
||||
<classpathentry kind="output" path="bin"/>
|
||||
</classpath>"#,
|
||||
);
|
||||
write(&project.join(".project"), "<projectDescription><name>demo</name></projectDescription>");
|
||||
write(
|
||||
&project.join(".settings/org.eclipse.core.resources.prefs"),
|
||||
"eclipse.preferences.version=1\nencoding/demo=GBK\n",
|
||||
);
|
||||
std::fs::create_dir_all(project.join("src")).unwrap();
|
||||
write(&project.join("lib/dep.jar"), "");
|
||||
let file = project.join("src/p/Hi.java");
|
||||
write(&file, "package p;\nclass Hi {}\n");
|
||||
let module = JavaFileModule::of(&file, dir.path()).unwrap();
|
||||
assert_eq!(module.dir, project);
|
||||
assert_eq!(module.sources, [project.join("src")]);
|
||||
assert_eq!(module.libraries, [project.join("lib/dep.jar")]);
|
||||
assert_eq!(module.encoding.as_deref(), Some("GBK"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eclipse_project_references_supply_their_sources_output_and_jars() {
|
||||
// svcLocalInpInfo → /htlib: the referenced project's bin, its jars and its sources.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let workspace = dir.path();
|
||||
let app = workspace.join("app");
|
||||
let lib = workspace.join("htlib");
|
||||
write(&app.join(".project"), "<projectDescription><name>app</name></projectDescription>");
|
||||
write(
|
||||
&app.join(".classpath"),
|
||||
r#"<classpath>
|
||||
<classpathentry kind="src" path="src"/>
|
||||
<classpathentry kind="src" path="/htlib"/>
|
||||
<classpathentry kind="lib" path="lib/own.jar"/>
|
||||
<classpathentry kind="lib" path="/htlib/htxs-system.jar"/>
|
||||
<classpathentry kind="output" path="bin"/>
|
||||
</classpath>"#,
|
||||
);
|
||||
std::fs::create_dir_all(app.join("src")).unwrap();
|
||||
std::fs::create_dir_all(app.join("bin")).unwrap();
|
||||
write(&app.join("lib/own.jar"), "");
|
||||
write(&lib.join(".project"), "<projectDescription><name>htlib</name></projectDescription>");
|
||||
write(
|
||||
&lib.join(".classpath"),
|
||||
r#"<classpath>
|
||||
<classpathentry kind="src" path="src"/>
|
||||
<classpathentry kind="lib" path="htxs-system.jar"/>
|
||||
<classpathentry kind="lib" path="lib/jdom.jar"/>
|
||||
<classpathentry kind="output" path="bin"/>
|
||||
</classpath>"#,
|
||||
);
|
||||
std::fs::create_dir_all(lib.join("src")).unwrap();
|
||||
std::fs::create_dir_all(lib.join("bin")).unwrap();
|
||||
write(&lib.join("htxs-system.jar"), "");
|
||||
write(&lib.join("lib/jdom.jar"), "");
|
||||
let file = app.join("src/p/Hi.java");
|
||||
write(&file, "package p;\nclass Hi {}\n");
|
||||
let module = JavaFileModule::of(&file, workspace).unwrap();
|
||||
assert_eq!(module.dir, app);
|
||||
assert_eq!(module.sources, [app.join("src"), lib.join("src")]);
|
||||
// The app's own `bin` is not trusted; the referenced project's is Eclipse's model.
|
||||
assert_eq!(
|
||||
module.libraries,
|
||||
[app.join("lib/own.jar"), lib.join("htxs-system.jar"), lib.join("bin"), lib.join("lib/jdom.jar")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_jdk_6_project_sdk_is_used_for_the_file() {
|
||||
// A JDK 6 install has no `release` file: `jdk_at` reads `rt.jar`'s manifest.
|
||||
use std::io::Write;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let home = dir.path().join("jdk6");
|
||||
write(&home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" }), "");
|
||||
std::fs::create_dir_all(home.join("jre/lib")).unwrap();
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(home.join("jre/lib/rt.jar")).unwrap());
|
||||
zip.start_file("META-INF/MANIFEST.MF", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
zip.write_all(b"Manifest-Version: 1.0\r\nSpecification-Version: 1.6\r\n\r\n").unwrap();
|
||||
zip.finish().unwrap();
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.jdk = home.to_string_lossy().into_owned();
|
||||
let jdk = java_jdk(dir.path(), None, &settings).expect("the configured JDK 6");
|
||||
assert_eq!(jdk.major, 6);
|
||||
}
|
||||
|
||||
/// A file of an Eclipse module with a JDK that has no source launcher is compiled with
|
||||
/// `javac` and started from a class path. Skipped when no JDK is configured.
|
||||
#[tokio::test]
|
||||
async fn a_project_file_is_compiled_and_started_from_a_class_path() {
|
||||
let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from) else { return };
|
||||
if !jdk_bin(&home, "javac").is_file() || !jdk_bin(&home, "java").is_file() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let project = dir.path().join("proj");
|
||||
write(&project.join(".classpath"), "<classpath><classpathentry kind=\"src\" path=\"src\"/></classpath>");
|
||||
write(&project.join(".project"), "<projectDescription><name>demo</name></projectDescription>");
|
||||
let file = project.join("src/p/Hi.java");
|
||||
write(
|
||||
&file,
|
||||
"package p; public class Hi { public static void main(String[] args) { System.out.println(\"hi\"); } }",
|
||||
);
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.jdk = home.to_string_lossy().into_owned();
|
||||
let mut config = file_config(&file, vec![file.to_string_lossy().into_owned()]);
|
||||
let output = Arc::new(std::sync::Mutex::new(String::new()));
|
||||
let sink: Emit<OutputChunk> = {
|
||||
let output = output.clone();
|
||||
Arc::new(move |chunk: OutputChunk| {
|
||||
if let OutputChunk::Stderr { text } = chunk {
|
||||
output.lock().unwrap().push_str(&text);
|
||||
}
|
||||
})
|
||||
};
|
||||
prepare(&project, &project, &settings, &mut config, &sink, &CancellationToken::new()).await.unwrap();
|
||||
assert_eq!(config.args.first().map(String::as_str), Some("-cp"));
|
||||
assert_eq!(config.args.last().map(String::as_str), Some("p.Hi"));
|
||||
let run = Command::new(&config.command).args(&config.args).output().unwrap();
|
||||
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||
assert_eq!(String::from_utf8_lossy(&run.stdout).trim(), "hi");
|
||||
}
|
||||
|
||||
/// Debugging a file puts the JDWP agent (and the configuration's VM options) before the
|
||||
/// file; the compile-and-run rewrite keeps them in front of `-cp` and the program
|
||||
/// arguments after the class. Skipped when no JDK is configured.
|
||||
#[tokio::test]
|
||||
async fn a_debug_launch_keeps_the_jdwp_agent_and_the_program_arguments() {
|
||||
let Some(home) = std::env::var_os("JAVA_HOME").map(PathBuf::from) else { return };
|
||||
if !jdk_bin(&home, "javac").is_file() || !jdk_bin(&home, "java").is_file() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let project = dir.path().join("proj");
|
||||
write(&project.join(".classpath"), "<classpath><classpathentry kind=\"src\" path=\"src\"/></classpath>");
|
||||
write(&project.join(".project"), "<projectDescription><name>demo</name></projectDescription>");
|
||||
let file = project.join("src/p/Hi.java");
|
||||
write(
|
||||
&file,
|
||||
"package p; public class Hi { public static void main(String[] args) { System.out.println(args[0]); } }",
|
||||
);
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.java.jdk = home.to_string_lossy().into_owned();
|
||||
let agent = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:0";
|
||||
let args =
|
||||
vec![agent.to_owned(), "-Xmx1g".to_owned(), file.to_string_lossy().into_owned(), "argument".to_owned()];
|
||||
let mut config = file_config(&file, args);
|
||||
prepare(&project, &project, &settings, &mut config, &no_output(), &CancellationToken::new()).await.unwrap();
|
||||
assert_eq!(config.args[..2], [agent, "-Xmx1g"]);
|
||||
assert_eq!(config.args[2], "-cp");
|
||||
assert_eq!(config.args[4], "p.Hi");
|
||||
assert_eq!(config.args.last().map(String::as_str), Some("argument"));
|
||||
let run = Command::new(&config.command).args(&config.args).output().unwrap();
|
||||
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||
// Some JDKs print the JDWP listener line on stdout; the program's output follows it.
|
||||
let stdout = String::from_utf8_lossy(&run.stdout);
|
||||
assert!(stdout.trim_end().ends_with("argument"), "{stdout}");
|
||||
}
|
||||
|
||||
/// The other launcher form compiles first itself (`javac … && java -cp …`) and names no
|
||||
/// source file among its arguments: it is left alone.
|
||||
#[tokio::test]
|
||||
async fn a_compiled_launcher_line_is_left_alone() {
|
||||
let settings = Settings::default();
|
||||
let mut config = file_config(Path::new("Hi.java"), Vec::new());
|
||||
config.command = "javac -d out Hi.java && java -cp out Hi".into();
|
||||
prepare(Path::new("."), Path::new("."), &settings, &mut config, &no_output(), &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(config.command, "javac -d out Hi.java && java -cp out Hi");
|
||||
assert!(config.args.is_empty());
|
||||
// A VM option's value that happens to end in `.java` is not the source file either.
|
||||
let mut option = file_config(Path::new("Hi.java"), vec!["-Dscript=run.java".into()]);
|
||||
prepare(Path::new("."), Path::new("."), &settings, &mut option, &no_output(), &CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(option.args, ["-Dscript=run.java"]);
|
||||
}
|
||||
}
|
||||
@@ -258,6 +258,53 @@ pub struct SvnProperty {
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
/// Working copy vs `BASE` comparison of one Subversion property.
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnPropertyDiff {
|
||||
pub name: String,
|
||||
pub value: Option<String>,
|
||||
pub base_value: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnCleanupOptions {
|
||||
#[serde(default)]
|
||||
pub remove_unversioned: bool,
|
||||
#[serde(default)]
|
||||
pub remove_ignored: bool,
|
||||
#[serde(default)]
|
||||
pub include_externals: bool,
|
||||
#[serde(default)]
|
||||
pub vacuum_pristines: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnUpdateOptions {
|
||||
#[serde(default)]
|
||||
pub revision: Option<String>,
|
||||
#[serde(default)]
|
||||
pub depth: Option<SvnDepth>,
|
||||
#[serde(default)]
|
||||
pub set_depth: bool,
|
||||
#[serde(default)]
|
||||
pub ignore_externals: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnUpdateResult {
|
||||
pub revision: Option<u32>,
|
||||
pub updated: u32,
|
||||
pub added: u32,
|
||||
pub deleted: u32,
|
||||
pub merged: u32,
|
||||
pub conflicted: u32,
|
||||
pub output: Vec<String>,
|
||||
}
|
||||
|
||||
/// VCS › Subversion › Properties: the properties of a file or folder.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_properties(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<SvnProperty>> {
|
||||
@@ -328,20 +375,34 @@ pub async fn svn_version(host: &Host, window: &str, executable: String) -> IdeRe
|
||||
.await
|
||||
}
|
||||
|
||||
/// Get from Version Control › Subversion: `svn checkout` of `url` into `dest`, with the
|
||||
/// window's project settings when it has a project, the global ones otherwise. svn's progress
|
||||
/// lines go to `on_output`; `cancel_request(request)` stops it (as Git's clone).
|
||||
#[command(trust = always)]
|
||||
pub async fn svn_checkout(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
url: String,
|
||||
dest: PathBuf,
|
||||
on_output: crate::ops::Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
/// One entry returned by `svn_list_url` for the Repository Browser.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnRemoteEntry {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
pub size: Option<f64>,
|
||||
pub revision: Option<u32>,
|
||||
pub author: String,
|
||||
pub time_ms: f64,
|
||||
}
|
||||
|
||||
impl From<ide_svn::RemoteEntry> for SvnRemoteEntry {
|
||||
fn from(entry: ide_svn::RemoteEntry) -> Self {
|
||||
Self {
|
||||
name: entry.name,
|
||||
kind: entry.kind,
|
||||
size: entry.size.map(|n| n as f64),
|
||||
revision: entry.revision.and_then(|r| u32::try_from(r).ok()),
|
||||
author: entry.author,
|
||||
time_ms: entry.time_ms,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn svn_context_for_window(host: &Host, window: &str) -> Arc<ide_svn::SvnContext> {
|
||||
let project = host.project(window).ok();
|
||||
let ctx = match project.as_ref().and_then(|p| p.svn.clone()) {
|
||||
match project.as_ref().and_then(|p| p.svn.clone()) {
|
||||
Some(ctx) => {
|
||||
if let Some(p) = &project {
|
||||
p.apply_svn_settings();
|
||||
@@ -354,13 +415,196 @@ pub async fn svn_checkout(
|
||||
ctx.set_settings(crate::svn::settings(&host.global_settings.read_effective(|s| s.vcs.svn.clone())));
|
||||
ctx
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Get from Version Control › Subversion: `svn checkout` of `url` into `dest`, with the
|
||||
/// window's project settings when it has a project, the global ones otherwise. svn's progress
|
||||
/// lines go to `on_output`; `cancel_request(request)` stops it (as Git's clone).
|
||||
#[command(trust = always)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn svn_checkout(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
url: String,
|
||||
dest: PathBuf,
|
||||
on_output: crate::ops::Channel<String>,
|
||||
revision: Option<String>,
|
||||
depth: Option<SvnDepth>,
|
||||
ignore_externals: Option<bool>,
|
||||
) -> IdeResult<()> {
|
||||
let ctx = svn_context_for_window(host, window);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let report = |line: String| {
|
||||
let _ = on_output.send(line);
|
||||
};
|
||||
WorkingCopy::checkout_reporting(&url, None, &dest, ide_svn::Depth::Infinity, ctx, &cancel, &report).map(|_| ())
|
||||
WorkingCopy::checkout_with_options(
|
||||
&url,
|
||||
revision.as_deref(),
|
||||
&dest,
|
||||
depth.map(Into::into).unwrap_or_default(),
|
||||
ignore_externals.unwrap_or(false),
|
||||
ctx,
|
||||
&cancel,
|
||||
&report,
|
||||
)
|
||||
.map(|_| ())
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Lists direct child entries of a remote repository URL (`svn list --xml`).
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn svn_list_url(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
url: String,
|
||||
revision: Option<String>,
|
||||
) -> IdeResult<Vec<SvnRemoteEntry>> {
|
||||
let ctx = svn_context_for_window(host, window);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
ide_svn::list_url(&url, revision.as_deref(), ctx, &cancel).map(|v| v.into_iter().map(Into::into).collect())
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Fetches recent commits for a remote Subversion URL (`svn log --xml`).
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn svn_remote_log(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
url: String,
|
||||
revision: Option<String>,
|
||||
limit: Option<u32>,
|
||||
) -> IdeResult<Vec<ide_vcs::Commit>> {
|
||||
let ctx = svn_context_for_window(host, window);
|
||||
let cancel = host.begin_request(request);
|
||||
let count = limit.unwrap_or(100) as usize;
|
||||
let result = blocking(move || ide_svn::remote_log(&url, revision.as_deref(), count, ctx, &cancel)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads the text contents of a remote file URL (`svn cat`, max 4 MiB).
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn svn_cat_url(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
url: String,
|
||||
revision: Option<String>,
|
||||
) -> IdeResult<String> {
|
||||
let ctx = svn_context_for_window(host, window);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || ide_svn::cat_url(&url, revision.as_deref(), ctx, &cancel)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Exports an unversioned tree from a repository URL or working copy path into `dest`.
|
||||
#[command(trust = outside_restricted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn svn_export(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
source: String,
|
||||
dest: PathBuf,
|
||||
revision: Option<String>,
|
||||
depth: Option<SvnDepth>,
|
||||
ignore_externals: Option<bool>,
|
||||
overwrite: Option<bool>,
|
||||
on_output: crate::ops::Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let ctx = svn_context_for_window(host, window);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let report = |line: String| {
|
||||
let _ = on_output.send(line);
|
||||
};
|
||||
ide_svn::export_url(
|
||||
&source,
|
||||
&dest,
|
||||
revision.as_deref(),
|
||||
depth.map(Into::into).unwrap_or_default(),
|
||||
ignore_externals.unwrap_or(false),
|
||||
overwrite.unwrap_or(false),
|
||||
ctx,
|
||||
&cancel,
|
||||
&report,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Creates a directory at a remote repository URL (`svn mkdir --parents`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_remote_mkdir(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
url: String,
|
||||
message: String,
|
||||
) -> IdeResult<Option<u32>> {
|
||||
host.require_trust(window)?;
|
||||
let ctx = svn_context_for_window(host, window);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
ide_svn::remote_mkdir(&url, &message, ctx, &cancel).map(|r| r.and_then(|n| u32::try_from(n).ok()))
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Copies a remote repository URL to another URL (`svn copy --parents`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_remote_copy(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
source_url: String,
|
||||
dest_url: String,
|
||||
revision: Option<String>,
|
||||
message: String,
|
||||
) -> IdeResult<Option<u32>> {
|
||||
host.require_trust(window)?;
|
||||
let ctx = svn_context_for_window(host, window);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
ide_svn::remote_copy(&source_url, &dest_url, revision.as_deref(), &message, ctx, &cancel)
|
||||
.map(|r| r.and_then(|n| u32::try_from(n).ok()))
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Deletes a remote repository URL (`svn delete`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_remote_delete(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
url: String,
|
||||
message: String,
|
||||
) -> IdeResult<Option<u32>> {
|
||||
host.require_trust(window)?;
|
||||
let ctx = svn_context_for_window(host, window);
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
ide_svn::remote_delete(&url, &message, ctx, &cancel).map(|r| r.and_then(|n| u32::try_from(n).ok()))
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
@@ -426,6 +670,190 @@ pub async fn svn_eligible_revisions(
|
||||
result
|
||||
}
|
||||
|
||||
/// Incoming remote change returned by `svn_incoming`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnIncomingChange {
|
||||
pub path: String,
|
||||
pub rel_path: String,
|
||||
pub item: String,
|
||||
pub props: String,
|
||||
pub revision: Option<u32>,
|
||||
pub author: String,
|
||||
pub time_ms: f64,
|
||||
pub has_local_change: bool,
|
||||
pub locked_by: Option<String>,
|
||||
}
|
||||
|
||||
impl From<ide_svn::IncomingChange> for SvnIncomingChange {
|
||||
fn from(c: ide_svn::IncomingChange) -> Self {
|
||||
Self {
|
||||
path: c.path,
|
||||
rel_path: c.rel_path,
|
||||
item: c.item,
|
||||
props: c.props,
|
||||
revision: c.revision.and_then(|r| u32::try_from(r).ok()),
|
||||
author: c.author,
|
||||
time_ms: c.time_ms,
|
||||
has_local_change: c.has_local_change,
|
||||
locked_by: c.locked_by,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Working copy metadata returned by `svn_working_copy_info`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnWorkingCopyInfo {
|
||||
pub root: String,
|
||||
pub url: String,
|
||||
pub repository_root: String,
|
||||
pub uuid: String,
|
||||
pub revision: Option<u32>,
|
||||
pub last_changed_rev: Option<u32>,
|
||||
pub last_changed_author: String,
|
||||
pub last_changed_time_ms: f64,
|
||||
pub depth: String,
|
||||
pub format: Option<String>,
|
||||
pub is_switched: bool,
|
||||
}
|
||||
|
||||
impl From<ide_svn::WorkingCopyInfo> for SvnWorkingCopyInfo {
|
||||
fn from(w: ide_svn::WorkingCopyInfo) -> Self {
|
||||
Self {
|
||||
root: w.root,
|
||||
url: w.url,
|
||||
repository_root: w.repository_root,
|
||||
uuid: w.uuid,
|
||||
revision: w.revision.and_then(|r| u32::try_from(r).ok()),
|
||||
last_changed_rev: w.last_changed_rev.and_then(|r| u32::try_from(r).ok()),
|
||||
last_changed_author: w.last_changed_author,
|
||||
last_changed_time_ms: w.last_changed_time_ms,
|
||||
depth: w.depth,
|
||||
format: w.format,
|
||||
is_switched: w.is_switched,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One discovered branch or tag folder returned inside `SvnBranchLayout`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnBranchEntry {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub kind: String,
|
||||
pub revision: Option<u32>,
|
||||
pub time_ms: f64,
|
||||
}
|
||||
|
||||
/// Repository trunk and branch/tag layout returned by `svn_branch_layout`.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnBranchLayout {
|
||||
pub current_url: String,
|
||||
pub repository_root: String,
|
||||
pub trunk_url: Option<String>,
|
||||
pub branch_locations: Vec<String>,
|
||||
pub branches: Vec<SvnBranchEntry>,
|
||||
}
|
||||
|
||||
/// One entry returned by `svn_compare_with_url`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SvnBranchCompareEntry {
|
||||
pub path: String,
|
||||
pub item: String,
|
||||
pub props: String,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
/// Lists incoming remote updates for a Subversion working copy (`svn status -u --xml`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_incoming(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
repo: Option<PathBuf>,
|
||||
) -> IdeResult<Vec<SvnIncomingChange>> {
|
||||
let project = host.project(window)?;
|
||||
project.require_trust()?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
with_working_copy(&project, repo.as_deref(), |wc| {
|
||||
Ok(wc.incoming(&cancel)?.into_iter().map(Into::into).collect())
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads metadata for one Subversion working copy (`repo = Some`) or all Subversion working copies in the project.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_working_copy_info(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
) -> IdeResult<Vec<SvnWorkingCopyInfo>> {
|
||||
let project = host.project(window)?;
|
||||
project.require_trust()?;
|
||||
blocking(move || {
|
||||
if let Some(path) = repo.as_deref() {
|
||||
return with_working_copy(&project, Some(path), |wc| Ok(vec![wc.working_copy_info_for(path)?.into()]));
|
||||
}
|
||||
let mut infos: Vec<SvnWorkingCopyInfo> = Vec::new();
|
||||
for backend in project.backends() {
|
||||
if let Some(wc) = as_svn(backend.as_ref()) {
|
||||
infos.extend(wc.working_copy_infos()?.into_iter().map(Into::into));
|
||||
}
|
||||
}
|
||||
infos.sort_by(|a, b| a.root.cmp(&b.root));
|
||||
infos.dedup_by(|a, b| a.root == b.root);
|
||||
Ok(infos)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Lists configured or standard-layout branches and tags for a Subversion working copy.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_branch_layout(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
repo: Option<PathBuf>,
|
||||
) -> IdeResult<SvnBranchLayout> {
|
||||
let project = host.project(window)?;
|
||||
project.require_trust()?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
project.apply_svn_settings();
|
||||
with_working_copy(&project, repo.as_deref(), |wc| {
|
||||
let layout = wc.branch_layout(None, &cancel)?;
|
||||
Ok(SvnBranchLayout {
|
||||
current_url: layout.current_url,
|
||||
repository_root: layout.repository_root,
|
||||
trunk_url: layout.trunk_url,
|
||||
branch_locations: layout.branch_locations,
|
||||
branches: layout
|
||||
.branches
|
||||
.into_iter()
|
||||
.map(|b| SvnBranchEntry {
|
||||
name: b.name,
|
||||
url: b.url,
|
||||
kind: b.kind,
|
||||
revision: b.revision.and_then(|n| u32::try_from(n).ok()),
|
||||
time_ms: b.time_ms,
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// VCS › Subversion › Merge From…: runs `svn merge` with streaming output.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_merge(
|
||||
@@ -465,6 +893,34 @@ pub async fn svn_merge(
|
||||
result
|
||||
}
|
||||
|
||||
/// Summarizes differences between the selected working-copy item (or the whole working copy) and `target_url`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_compare_with_url(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
repo: Option<PathBuf>,
|
||||
target_url: String,
|
||||
path: Option<PathBuf>,
|
||||
) -> IdeResult<Vec<SvnBranchCompareEntry>> {
|
||||
let project = host.project(window)?;
|
||||
project.require_trust()?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let lookup = path.as_deref().or(repo.as_deref());
|
||||
with_working_copy(&project, lookup, |wc| {
|
||||
Ok(wc
|
||||
.compare_with_url(&target_url, path.as_deref(), &cancel)?
|
||||
.into_iter()
|
||||
.map(|e| SvnBranchCompareEntry { path: e.path, item: e.item, props: e.props, kind: e.kind })
|
||||
.collect())
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Subversion Log › Reverse Merge Revision (`svn merge -c -REV`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_revert_revision(
|
||||
@@ -490,21 +946,203 @@ pub async fn svn_revert_revision(
|
||||
result
|
||||
}
|
||||
|
||||
/// Switches a Subversion working copy (or subtree target when `repo` points inside a checkout)
|
||||
/// to an arbitrary repository URL with optional revision/depth.
|
||||
#[command(trust = trusted)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn svn_switch_url(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: ide_core::RequestId,
|
||||
repo: Option<PathBuf>,
|
||||
url: String,
|
||||
revision: Option<String>,
|
||||
depth: Option<SvnDepth>,
|
||||
ignore_ancestry: Option<bool>,
|
||||
) -> IdeResult<Option<u32>> {
|
||||
let project = host.project(window)?;
|
||||
project.require_trust()?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let rev = with_working_copy(&project, repo.as_deref(), |wc| {
|
||||
wc.switch_path_with_options(
|
||||
repo.as_deref(),
|
||||
&url,
|
||||
revision.as_deref(),
|
||||
depth.map(Into::into),
|
||||
ignore_ancestry.unwrap_or(false),
|
||||
&cancel,
|
||||
)
|
||||
})?;
|
||||
project.vcs_changed();
|
||||
Ok(rev.and_then(|r| u32::try_from(r).ok()))
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Adds `pattern` to the `svn:ignore` property of `path`'s parent directory.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_ignore_pattern(host: &Host, window: &str, path: PathBuf, pattern: String) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let dir = path
|
||||
.parent()
|
||||
.filter(|p| !p.as_os_str().is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("cannot ignore a working copy root"))?
|
||||
.to_path_buf();
|
||||
with_working_copy(&project, Some(&dir), |wc| wc.ignore(&dir, &pattern))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Working copy vs `BASE` Subversion properties of `path`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_properties_diff(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<SvnPropertyDiff>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
with_working_copy(&project, Some(&path), |wc| {
|
||||
Ok(wc
|
||||
.properties_diff(&path)?
|
||||
.into_iter()
|
||||
.map(|p| SvnPropertyDiff { name: p.name, value: p.value, base_value: p.base_value })
|
||||
.collect())
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Sets or deletes property `name` of `path`, optionally recursively (`-R`).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_set_property_options(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: PathBuf,
|
||||
name: String,
|
||||
value: Option<String>,
|
||||
recursive: bool,
|
||||
) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
with_working_copy(&project, Some(&path), |wc| {
|
||||
wc.set_property_recursive(&path, &name, value.as_deref(), recursive)
|
||||
})?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// VCS › Subversion › Cleanup with unversioned/ignored removal, externals, and pristine vacuuming.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_cleanup_options(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
options: SvnCleanupOptions,
|
||||
) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let opts = ide_svn::CleanupOptions {
|
||||
remove_unversioned: options.remove_unversioned,
|
||||
remove_ignored: options.remove_ignored,
|
||||
include_externals: options.include_externals,
|
||||
vacuum_pristines: options.vacuum_pristines,
|
||||
target: None,
|
||||
};
|
||||
with_working_copy(&project, repo.as_deref(), |wc| wc.cleanup_with_options(&opts, &CancellationToken::new()))?;
|
||||
project.vcs_changed();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// VCS › Subversion › Update Directory… with explicit revision, depth, set-depth, and ignore-externals.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_update_options(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
repo: Option<PathBuf>,
|
||||
request: ide_core::RequestId,
|
||||
paths: Vec<PathBuf>,
|
||||
options: SvnUpdateOptions,
|
||||
on_output: crate::ops::Channel<String>,
|
||||
) -> IdeResult<SvnUpdateResult> {
|
||||
let project = host.project(window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let report = |line: String| {
|
||||
let _ = on_output.send(line);
|
||||
};
|
||||
let opts = ide_svn::UpdateOptions {
|
||||
revision: options.revision,
|
||||
depth: options.depth.map(Into::into),
|
||||
set_depth: options.set_depth,
|
||||
ignore_externals: options.ignore_externals,
|
||||
};
|
||||
let target_hint = repo.as_deref().or_else(|| paths.first().map(PathBuf::as_path));
|
||||
let res =
|
||||
with_working_copy(&project, target_hint, |wc| wc.update_with_options(&paths, &opts, &cancel, &report))?;
|
||||
project.refresh_backends();
|
||||
project.vcs_changed();
|
||||
Ok(SvnUpdateResult {
|
||||
revision: res.revision.and_then(|r| u32::try_from(r).ok()),
|
||||
updated: res.updated,
|
||||
added: res.added,
|
||||
deleted: res.deleted,
|
||||
merged: res.merged,
|
||||
conflicted: res.conflicted,
|
||||
output: res.output,
|
||||
})
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Repository URL of `path` inside a Subversion working copy.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn svn_item_url(host: &Host, window: &str, path: PathBuf) -> IdeResult<String> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || with_working_copy(&project, Some(&path), |wc| wc.url_of(&path))).await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
svn:
|
||||
svn_accept_incoming_delete,
|
||||
svn_branch_layout,
|
||||
svn_cat_url,
|
||||
svn_checkout,
|
||||
svn_cleanup,
|
||||
svn_cleanup_options,
|
||||
svn_compare_with_url,
|
||||
svn_eligible_revisions,
|
||||
svn_export,
|
||||
svn_incoming,
|
||||
svn_list_url,
|
||||
svn_ignore_pattern,
|
||||
svn_item_url,
|
||||
svn_lock,
|
||||
svn_merge,
|
||||
svn_merge_sources,
|
||||
svn_properties,
|
||||
svn_properties_diff,
|
||||
svn_relocate,
|
||||
svn_remote_copy,
|
||||
svn_remote_delete,
|
||||
svn_remote_log,
|
||||
svn_remote_mkdir,
|
||||
svn_repository_file_at,
|
||||
svn_repository_info,
|
||||
svn_revert_revision,
|
||||
svn_set_property,
|
||||
svn_set_property_options,
|
||||
svn_switch_url,
|
||||
svn_unlock,
|
||||
svn_update_options,
|
||||
svn_version,
|
||||
svn_working_copy_info,
|
||||
);
|
||||
@@ -725,13 +725,22 @@ pub async fn vcs_check_incoming(
|
||||
result
|
||||
}
|
||||
|
||||
/// Whether an editor file reached through a symlink has a tracked file at its target's HEAD.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_linked_file_has_history(host: &Host, window: &str, path: PathBuf) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || project.linked_file_has_history(&path)).await
|
||||
}
|
||||
|
||||
/// Gutter change markers for a file, computed against its current (unsaved) text.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_line_hunks(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<LineHunk>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let text = project.text_of(&path)?;
|
||||
project.with_backend_of(&path, |r| r.line_hunks(&path, &text, false, project.vcs_encoding(&path, None)?))
|
||||
project.with_editor_backend_of(&path, |repo, repo_path| {
|
||||
let text = project.text_of(&path)?;
|
||||
repo.line_hunks(repo_path, &text, false, project.vcs_encoding(&path, None)?)
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -745,6 +754,11 @@ pub async fn vcs_staging_line_hunks(
|
||||
) -> IdeResult<Option<ide_vcs::StagingLineHunks>> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
// A linked editor file uses the target's HEAD for markers, not the
|
||||
// index of a repository that might track the link itself.
|
||||
if project.linked_file_target(&path).is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let text = project.text_of(&path)?;
|
||||
project.with_repo_of(&path, |repo| {
|
||||
repo.staging_line_hunks(
|
||||
@@ -881,14 +895,20 @@ pub async fn vcs_blame(
|
||||
// An explicit text wins (merge view annotates its side panes, not the worktree).
|
||||
blocking(move || {
|
||||
let text = text.or_else(|| project.documents.text_of(&path));
|
||||
project.with_backend_of(&path, |backend| {
|
||||
project.with_editor_backend_of(&path, |backend, repo_path| {
|
||||
let encoding = project.vcs_encoding(&path, revision.as_deref())?;
|
||||
let text = text.as_deref();
|
||||
let revision = revision.as_deref();
|
||||
if let Some(repo) = backend.as_git() {
|
||||
repo.blame_with_options(&path, text, revision, encoding, project.settings.effective().vcs.git.annotate)
|
||||
repo.blame_with_options(
|
||||
repo_path,
|
||||
text,
|
||||
revision,
|
||||
encoding,
|
||||
project.settings.effective().vcs.git.annotate,
|
||||
)
|
||||
} else {
|
||||
backend.blame(&path, text, revision, encoding)
|
||||
backend.blame(repo_path, text, revision, encoding)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -2863,8 +2883,10 @@ pub async fn vcs_add_worktree(
|
||||
});
|
||||
// A worktree below the project is a new repository: rescan so its files
|
||||
// join the status and gutter queries (the watcher picks the gitfile up
|
||||
// too, but only as a debounced event later).
|
||||
// too, but only as a debounced event later), and refresh detected roots
|
||||
// so the nested worktree is excluded from indexing and search at once.
|
||||
project.refresh_repositories();
|
||||
project.refresh_detected_roots();
|
||||
result
|
||||
})
|
||||
.await;
|
||||
@@ -2897,6 +2919,7 @@ pub async fn vcs_remove_worktree(
|
||||
)?;
|
||||
let result = project.with_repo_at(repo.as_deref(), |r| r.remove_worktree(&path, force));
|
||||
project.refresh_repositories();
|
||||
project.refresh_detected_roots();
|
||||
result
|
||||
})
|
||||
.await
|
||||
@@ -2917,6 +2940,7 @@ pub async fn vcs_move_worktree(
|
||||
check_worktree_away_from_project(&project.root, &path, "Cannot move a worktree containing the open project.")?;
|
||||
let result = project.with_repo_at(repo.as_deref(), |r| r.move_worktree(&path, &to));
|
||||
project.refresh_repositories();
|
||||
project.refresh_detected_roots();
|
||||
result
|
||||
})
|
||||
.await
|
||||
@@ -3770,6 +3794,7 @@ ide_command::domain!(
|
||||
vcs_has_hook,
|
||||
vcs_ignore_blame_revision,
|
||||
vcs_init,
|
||||
vcs_linked_file_has_history,
|
||||
vcs_line_hunks,
|
||||
vcs_staging_line_hunks,
|
||||
vcs_log,
|
||||
|
||||
@@ -129,6 +129,15 @@ pub trait PluginWorkspace: Send + Sync {
|
||||
fn build_graph(&self, _root: &Path) -> Result<super::BuildGraph, HostError> {
|
||||
Ok(super::BuildGraph::default())
|
||||
}
|
||||
/// Installed interpreters / JDKs / toolchains relevant to `root` (API 1.21).
|
||||
fn sdks(&self, _root: &Path, kind: Option<&str>) -> Result<Vec<ide_plugin::SdkInfo>, HostError> {
|
||||
super::build_graph::parse_sdk_kind_list(kind)?;
|
||||
Ok(Vec::new())
|
||||
}
|
||||
/// Project Structure › Artifacts definitions of the project at `root` (API 1.21).
|
||||
fn artifacts(&self, _root: &Path) -> Result<Vec<ide_plugin::ArtifactInfo>, HostError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
/// Current index of the project rooted at `root`; never reads disk or calls LSP.
|
||||
fn symbols(
|
||||
&self,
|
||||
@@ -1747,6 +1756,32 @@ impl PluginApi {
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginApi {
|
||||
fn database_for_client(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
source_id: Option<&str>,
|
||||
) -> Result<(Arc<crate::Host>, Arc<ide_db::DbManager>), HostError> {
|
||||
let (host, fallback) = self.database_host(root)?;
|
||||
// Connections belong to windows, even when several windows open the same root.
|
||||
// Prefer the invoking window; background calls may use any matching connected instance.
|
||||
let db = client
|
||||
.and_then(|client| host.project(client).ok())
|
||||
.filter(|project| project.root == root)
|
||||
.map(|project| project.db.clone())
|
||||
.or_else(|| {
|
||||
let target = source_id?;
|
||||
host.projects()
|
||||
.into_iter()
|
||||
.find(|project| project.root == root && project.db.is_connected(target))
|
||||
.map(|project| project.db.clone())
|
||||
})
|
||||
.unwrap_or(fallback);
|
||||
Ok((host, db))
|
||||
}
|
||||
}
|
||||
|
||||
impl HostApi for PluginApi {
|
||||
fn database_table_schema(
|
||||
&self,
|
||||
@@ -1757,21 +1792,69 @@ impl HostApi for PluginApi {
|
||||
timeout: Duration,
|
||||
) -> Result<ide_plugin::PluginDatabaseTableSchema, HostError> {
|
||||
self.require_api("database table schema", 20)?;
|
||||
let (host, fallback) = self.database_host(root)?;
|
||||
// Connections belong to windows, even when several windows open the same root.
|
||||
// Prefer the invoking window; background calls may use any connected instance.
|
||||
let db = client
|
||||
let (host, db) = self.database_for_client(root, client, Some(&table.source_id))?;
|
||||
host.runtime.block_on(super::database::table_schema(&db, table, cancel, timeout))
|
||||
}
|
||||
fn database_connected_sources(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
) -> Result<Vec<ide_plugin::PluginConnectedDataSource>, HostError> {
|
||||
self.require_api("database connected sources", 21)?;
|
||||
let (host, _) = self.database_host(root)?;
|
||||
if let Some(db) = client
|
||||
.and_then(|client| host.project(client).ok())
|
||||
.filter(|project| project.root == root)
|
||||
.map(|project| project.db.clone())
|
||||
.or_else(|| {
|
||||
host.projects()
|
||||
.into_iter()
|
||||
.find(|project| project.root == root && project.db.is_connected(&table.source_id))
|
||||
.map(|project| project.db.clone())
|
||||
})
|
||||
.unwrap_or(fallback);
|
||||
host.runtime.block_on(super::database::table_schema(&db, table, cancel, timeout))
|
||||
{
|
||||
return super::database::connected_sources(&db);
|
||||
}
|
||||
let dbs: Vec<_> = host
|
||||
.projects()
|
||||
.into_iter()
|
||||
.filter(|project| project.root == root)
|
||||
.map(|project| project.db.clone())
|
||||
.collect();
|
||||
super::database::connected_sources_across(&dbs)
|
||||
}
|
||||
fn database_list_schemas(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
source_id: &str,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<String>, HostError> {
|
||||
self.require_api("database schema listing", 21)?;
|
||||
let (host, db) = self.database_for_client(root, client, Some(source_id))?;
|
||||
host.runtime.block_on(super::database::list_schemas(&db, source_id, cancel, timeout))
|
||||
}
|
||||
fn database_list_tables(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
source_id: &str,
|
||||
schema: &str,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<ide_plugin::PluginDatabaseTableSummary>, HostError> {
|
||||
self.require_api("database table listing", 21)?;
|
||||
let (host, db) = self.database_for_client(root, client, Some(source_id))?;
|
||||
host.runtime.block_on(super::database::list_tables(&db, source_id, schema, cancel, timeout))
|
||||
}
|
||||
fn database_execute_query(
|
||||
&self,
|
||||
root: &Path,
|
||||
client: Option<&str>,
|
||||
source_id: &str,
|
||||
sql: &str,
|
||||
max_rows: Option<u32>,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<ide_plugin::PluginDatabaseQueryResult, HostError> {
|
||||
self.require_api("database query execution", 21)?;
|
||||
let (host, db) = self.database_for_client(root, client, Some(source_id))?;
|
||||
host.runtime.block_on(super::database::execute_query(&db, source_id, sql, max_rows, cancel, timeout))
|
||||
}
|
||||
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
|
||||
let (host, db) = self.database_host(root)?;
|
||||
@@ -2949,6 +3032,24 @@ impl HostApi for PluginApi {
|
||||
super::build_graph::dependency_nodes(&workspace.build_graph(root)?, module)
|
||||
}
|
||||
|
||||
fn build_sdks(&self, root: &Path, kind: Option<&str>) -> Result<Vec<ide_plugin::SdkInfo>, HostError> {
|
||||
self.require_api("`build.sdks`", 21)?;
|
||||
let workspace = self.shared.workspace().ok_or_else(|| HostError::NotFound("no project is open".into()))?;
|
||||
if !workspace.trusted(root) {
|
||||
return Err(HostError::Denied("project is not trusted".into()));
|
||||
}
|
||||
workspace.sdks(root, kind)
|
||||
}
|
||||
|
||||
fn build_artifacts(&self, root: &Path) -> Result<Vec<ide_plugin::ArtifactInfo>, HostError> {
|
||||
self.require_api("`build.artifacts`", 21)?;
|
||||
let workspace = self.shared.workspace().ok_or_else(|| HostError::NotFound("no project is open".into()))?;
|
||||
if !workspace.trusted(root) {
|
||||
return Err(HostError::Denied("project is not trusted".into()));
|
||||
}
|
||||
workspace.artifacts(root)
|
||||
}
|
||||
|
||||
fn find_files(&self, root: &Path, glob: &str, limit: usize) -> Result<Vec<String>, HostError> {
|
||||
let matcher = globset::GlobBuilder::new(glob)
|
||||
.literal_separator(true)
|
||||
@@ -4234,6 +4335,22 @@ impl PluginWorkspace for HostWorkspace {
|
||||
crate::ops::build::analyzed_dependencies(&project, &host.config_dir, root).map_err(failed)
|
||||
}
|
||||
|
||||
fn sdks(&self, root: &Path, kind: Option<&str>) -> Result<Vec<ide_plugin::SdkInfo>, HostError> {
|
||||
let host = self.0.upgrade().ok_or(HostError::Cancelled)?;
|
||||
let project = HostWorkspace::project_covering(self, root)
|
||||
.ok_or_else(|| HostError::NotFound("the project is no longer open".into()))?;
|
||||
let settings = project.settings.effective();
|
||||
super::build_graph::discover_sdks(&host, &project.root, &settings, kind)
|
||||
}
|
||||
|
||||
fn artifacts(&self, root: &Path) -> Result<Vec<ide_plugin::ArtifactInfo>, HostError> {
|
||||
let project = HostWorkspace::project_covering(self, root)
|
||||
.ok_or_else(|| HostError::NotFound("the project is no longer open".into()))?;
|
||||
let settings = project.settings.effective();
|
||||
let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &settings);
|
||||
Ok(super::build_graph::discover_artifacts(&project.root, &model, &settings))
|
||||
}
|
||||
|
||||
fn trusted(&self, root: &Path) -> bool {
|
||||
// A workspace member is as trusted as the group's project it was opened with.
|
||||
HostWorkspace::project_covering(self, root).is_some_and(|p| p.is_trusted())
|
||||
@@ -5897,4 +6014,29 @@ mod workbench_tests {
|
||||
api.vcs_diff(&root, None, None, &cancel).unwrap();
|
||||
assert!(!marker.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_sdks_and_artifacts_gate_api_version_and_trust() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
|
||||
// Older plugin (`^1.4`) cannot call API 1.21 build.sdks / build.artifacts.
|
||||
let old = api(&root, true, None);
|
||||
assert!(matches!(old.build_sdks(&root, None), Err(HostError::Invalid(_))));
|
||||
assert!(matches!(old.build_artifacts(&root), Err(HostError::Invalid(_))));
|
||||
|
||||
let manifest21 = ide_extension::Manifest::parse(
|
||||
"id = \"test\"\nname = \"Test\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.21\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let new = PluginApi { pkg: Package::new(manifest21.clone(), root.clone()), shared: old.shared.clone() };
|
||||
assert!(new.build_sdks(&root, Some("jdk")).unwrap().is_empty());
|
||||
assert!(matches!(new.build_sdks(&root, Some("cobol")), Err(HostError::Invalid(_))));
|
||||
assert!(new.build_artifacts(&root).unwrap().is_empty());
|
||||
|
||||
let untrusted = api(&root, false, None);
|
||||
let new_untrusted = PluginApi { pkg: Package::new(manifest21, root.clone()), shared: untrusted.shared.clone() };
|
||||
assert!(matches!(new_untrusted.build_sdks(&root, None), Err(HostError::Denied(_))));
|
||||
assert!(matches!(new_untrusted.build_artifacts(&root), Err(HostError::Denied(_))));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
//! `build.dependencies`: the Dependency Analyzer's Maven / Gradle trees as the flat
|
||||
//! list the plugin API passes (records can't nest), each module a root.
|
||||
|
||||
use ide_build::{GradleDependency, GradleReport, MavenDependency, MavenProject, Omission};
|
||||
use ide_plugin::{DependencyNode, DependencyStatus, HostError};
|
||||
use ide_build::{BuildModel, GradleDependency, GradleReport, MavenDependency, MavenProject, Omission};
|
||||
use ide_core::ipc_path::to_ipc;
|
||||
use ide_core::settings::{ArtifactKind as SettingsArtifactKind, Settings};
|
||||
use ide_plugin::{ArtifactInfo, ArtifactKind, ArtifactOrigin, DependencyNode, DependencyStatus, HostError, SdkInfo};
|
||||
use ide_sdk::SdkKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Most nodes one call returns.
|
||||
const MAX_NODES: usize = 100_000;
|
||||
@@ -62,6 +66,135 @@ pub fn dependency_nodes(graph: &BuildGraph, module: Option<&str>) -> Result<Vec<
|
||||
}
|
||||
}
|
||||
|
||||
const ALL_SDK_KINDS: [(&str, SdkKind); 14] = [
|
||||
("jdk", SdkKind::Jdk),
|
||||
("maven", SdkKind::Maven),
|
||||
("python", SdkKind::Python),
|
||||
("node", SdkKind::Node),
|
||||
("php", SdkKind::Php),
|
||||
("package-manager", SdkKind::PackageManager),
|
||||
("rust", SdkKind::Rust),
|
||||
("go", SdkKind::Go),
|
||||
("typescript", SdkKind::TypeScript),
|
||||
("ruby", SdkKind::Ruby),
|
||||
("zig", SdkKind::Zig),
|
||||
("dotnet", SdkKind::Dotnet),
|
||||
("flutter", SdkKind::Flutter),
|
||||
("xcode", SdkKind::Xcode),
|
||||
];
|
||||
|
||||
pub(super) fn parse_sdk_kind_list(kind: Option<&str>) -> Result<Vec<(&'static str, SdkKind)>, HostError> {
|
||||
match kind {
|
||||
None => Ok(ALL_SDK_KINDS.to_vec()),
|
||||
Some(raw) => ALL_SDK_KINDS
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|(name, _)| *name == raw)
|
||||
.map(|pair| vec![pair])
|
||||
.ok_or_else(|| HostError::Invalid(format!("unknown SDK kind `{raw}`"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn normalized_path(p: &Path) -> PathBuf {
|
||||
std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
|
||||
}
|
||||
|
||||
fn active_sdk_path(root: &Path, settings: &Settings, kind: SdkKind) -> Option<PathBuf> {
|
||||
match kind {
|
||||
SdkKind::Jdk => ide_sdk::apply::project_jdk(root, settings).map(|j| j.home),
|
||||
SdkKind::Maven => ide_sdk::apply::setting_path(root, &settings.languages.java.maven.home),
|
||||
SdkKind::Python => ide_sdk::apply::python_interpreter(root, settings),
|
||||
SdkKind::Node => ide_sdk::apply::setting_path(root, &settings.languages.node.interpreter),
|
||||
SdkKind::Php => ide_sdk::apply::setting_path(root, &settings.languages.php.interpreter),
|
||||
SdkKind::PackageManager => ide_sdk::apply::setting_path(root, &settings.languages.node.package_manager),
|
||||
SdkKind::Rust => ide_sdk::apply::setting_path(root, &settings.languages.rust.toolchain),
|
||||
SdkKind::Go => ide_sdk::apply::setting_path(root, &settings.languages.go.goroot),
|
||||
SdkKind::TypeScript => ide_sdk::apply::tsdk(root, settings),
|
||||
SdkKind::Ruby => ide_sdk::apply::ruby_interpreter(root, settings),
|
||||
SdkKind::Zig => ide_sdk::apply::setting_path(root, &settings.languages.zig.zig),
|
||||
SdkKind::Dotnet => None,
|
||||
SdkKind::Flutter => ide_sdk::apply::setting_path(root, &settings.languages.flutter.sdk),
|
||||
SdkKind::Xcode => ide_sdk::apply::setting_path(root, &settings.languages.swift.xcode),
|
||||
}
|
||||
.map(|p| normalized_path(&p))
|
||||
}
|
||||
|
||||
/// Discovers installed SDKs / toolchains relevant to the project at `root`,
|
||||
/// marking the active configured selection per kind.
|
||||
pub fn discover_sdks(
|
||||
host: &crate::Host,
|
||||
root: &Path,
|
||||
settings: &Settings,
|
||||
kind: Option<&str>,
|
||||
) -> Result<Vec<SdkInfo>, HostError> {
|
||||
let kinds = parse_sdk_kind_list(kind)?;
|
||||
if kinds.iter().any(|(_, k)| *k == SdkKind::Jdk) {
|
||||
host.apply_added_jdks();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for (kind_name, sdk_kind) in kinds {
|
||||
let active = active_sdk_path(root, settings, sdk_kind);
|
||||
let mut sdks = ide_sdk::detect(sdk_kind, Some(root));
|
||||
if sdk_kind == SdkKind::Python
|
||||
&& let Some(py_path) = ide_sdk::apply::python_interpreter(root, settings)
|
||||
&& !sdks.iter().any(|s| normalized_path(&s.path) == normalized_path(&py_path))
|
||||
&& let Some(sdk) = ide_sdk::python_interpreter_sdk(&py_path, Some(root))
|
||||
{
|
||||
sdks.push(sdk);
|
||||
}
|
||||
for sdk in sdks {
|
||||
let is_active = active.as_ref().is_some_and(|act| {
|
||||
normalized_path(&sdk.path) == *act || sdk.home.as_deref().is_some_and(|h| normalized_path(h) == *act)
|
||||
});
|
||||
out.push(SdkInfo {
|
||||
kind: kind_name.to_owned(),
|
||||
name: sdk.name,
|
||||
path: to_ipc(&sdk.path),
|
||||
version: sdk.version,
|
||||
source: sdk.source,
|
||||
home: sdk.home.as_deref().map(to_ipc),
|
||||
active: is_active,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Returns deployable WAR modules discovered from the project's build model
|
||||
/// followed by user-configured `projectStructure.artifacts`.
|
||||
pub fn discover_artifacts(root: &Path, model: &BuildModel, settings: &Settings) -> Vec<ArtifactInfo> {
|
||||
let mut out: Vec<ArtifactInfo> = ide_build::web::artifacts(root, model)
|
||||
.into_iter()
|
||||
.map(|a| ArtifactInfo {
|
||||
id: a.id,
|
||||
origin: ArtifactOrigin::BuildModel,
|
||||
tool: a.tool,
|
||||
name: a.name,
|
||||
kind: ArtifactKind::War,
|
||||
module: a.module,
|
||||
output_directory: String::new(),
|
||||
main_class: String::new(),
|
||||
include_libraries: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
out.extend(settings.project_structure.artifacts.iter().map(|a| ArtifactInfo {
|
||||
id: format!("project:{}", a.name),
|
||||
origin: ArtifactOrigin::ProjectStructure,
|
||||
tool: "project".into(),
|
||||
name: a.name.clone(),
|
||||
kind: match a.kind {
|
||||
SettingsArtifactKind::Jar => ArtifactKind::Jar,
|
||||
SettingsArtifactKind::War => ArtifactKind::War,
|
||||
SettingsArtifactKind::WarExploded => ArtifactKind::WarExploded,
|
||||
},
|
||||
module: a.module.clone(),
|
||||
output_directory: a.output_directory.clone(),
|
||||
main_class: a.main_class.clone(),
|
||||
include_libraries: a.include_libraries.clone(),
|
||||
}));
|
||||
out
|
||||
}
|
||||
|
||||
struct Nodes(Vec<DependencyNode>);
|
||||
|
||||
impl Nodes {
|
||||
@@ -334,4 +467,90 @@ mod tests {
|
||||
assert!(!exact_version(v), "{v}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sdk_kinds_and_artifacts() {
|
||||
assert_eq!(parse_sdk_kind_list(None).unwrap().len(), 14);
|
||||
assert_eq!(parse_sdk_kind_list(Some("jdk")).unwrap(), vec![("jdk", SdkKind::Jdk)]);
|
||||
assert!(matches!(parse_sdk_kind_list(Some("unknown")), Err(HostError::Invalid(_))));
|
||||
|
||||
let mut maven = ide_build::MavenModel::default();
|
||||
maven.projects = vec![
|
||||
MavenProject {
|
||||
pom: "app/pom.xml".into(),
|
||||
dir: "app".into(),
|
||||
artifact_id: "demo-app".into(),
|
||||
packaging: "war".into(),
|
||||
..Default::default()
|
||||
},
|
||||
MavenProject {
|
||||
pom: "core/pom.xml".into(),
|
||||
dir: "core".into(),
|
||||
artifact_id: "core".into(),
|
||||
packaging: "jar".into(),
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let model = BuildModel {
|
||||
maven: Some(maven),
|
||||
gradle: vec![ide_build::GradleModel {
|
||||
projects: vec![ide_build::GradleProject {
|
||||
path: ":web".into(),
|
||||
name: "web".into(),
|
||||
dir: "web".into(),
|
||||
tasks: vec![ide_build::GradleTask { name: "war".into(), group: "build".into(), description: None }],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}],
|
||||
sbt: Vec::new(),
|
||||
};
|
||||
let mut settings = Settings::default();
|
||||
settings.project_structure.artifacts.push(ide_core::settings::ArtifactConfig {
|
||||
name: "app:war exploded".into(),
|
||||
kind: SettingsArtifactKind::WarExploded,
|
||||
module: "web".into(),
|
||||
output_directory: "web/target/app".into(),
|
||||
main_class: String::new(),
|
||||
include_libraries: vec!["spring".into()],
|
||||
});
|
||||
assert_eq!(
|
||||
discover_artifacts(Path::new("/project"), &model, &settings),
|
||||
vec![
|
||||
ArtifactInfo {
|
||||
id: "maven:app/pom.xml".into(),
|
||||
origin: ArtifactOrigin::BuildModel,
|
||||
tool: "maven".into(),
|
||||
name: "demo-app".into(),
|
||||
kind: ArtifactKind::War,
|
||||
module: "app".into(),
|
||||
output_directory: String::new(),
|
||||
main_class: String::new(),
|
||||
include_libraries: Vec::new(),
|
||||
},
|
||||
ArtifactInfo {
|
||||
id: "gradle::web".into(),
|
||||
origin: ArtifactOrigin::BuildModel,
|
||||
tool: "gradle".into(),
|
||||
name: "web".into(),
|
||||
kind: ArtifactKind::War,
|
||||
module: "web".into(),
|
||||
output_directory: String::new(),
|
||||
main_class: String::new(),
|
||||
include_libraries: Vec::new(),
|
||||
},
|
||||
ArtifactInfo {
|
||||
id: "project:app:war exploded".into(),
|
||||
origin: ArtifactOrigin::ProjectStructure,
|
||||
tool: "project".into(),
|
||||
name: "app:war exploded".into(),
|
||||
kind: ArtifactKind::WarExploded,
|
||||
module: "web".into(),
|
||||
output_directory: "web/target/app".into(),
|
||||
main_class: String::new(),
|
||||
include_libraries: vec!["spring".into()],
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,11 @@
|
||||
use super::api::PluginApi;
|
||||
use super::{PluginHost, WindowRequest};
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbProperty};
|
||||
use ide_plugin::{HostError, PluginDataSource};
|
||||
use ide_db::{DataSource, DbDriver, DbProperty, DbTableKind};
|
||||
use ide_plugin::{
|
||||
HostError, PluginConnectedDataSource, PluginDataSource, PluginDatabaseQueryColumn, PluginDatabaseQueryResult,
|
||||
PluginDatabaseTableSummary,
|
||||
};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -253,6 +256,199 @@ pub(super) async fn table_schema(
|
||||
})
|
||||
}
|
||||
|
||||
fn driver_name(driver: DbDriver) -> &'static str {
|
||||
match driver {
|
||||
DbDriver::Sqlite => "sqlite",
|
||||
DbDriver::Postgres => "postgres",
|
||||
DbDriver::Mysql => "mysql",
|
||||
DbDriver::SqlServer => "sqlServer",
|
||||
DbDriver::Clickhouse => "clickhouse",
|
||||
DbDriver::Oracle => "oracle",
|
||||
DbDriver::Snowflake => "snowflake",
|
||||
DbDriver::Jdbc => "jdbc",
|
||||
}
|
||||
}
|
||||
|
||||
fn table_kind_name(kind: DbTableKind) -> &'static str {
|
||||
match kind {
|
||||
DbTableKind::Table => "table",
|
||||
DbTableKind::View => "view",
|
||||
DbTableKind::MaterializedView => "materializedView",
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_db_ident(value: &str, non_empty: bool) -> bool {
|
||||
(!non_empty || !value.is_empty()) && value.len() <= 4096 && !value.contains('\0')
|
||||
}
|
||||
|
||||
pub(super) fn connected_sources(db: &ide_db::DbManager) -> Result<Vec<PluginConnectedDataSource>, HostError> {
|
||||
Ok(db
|
||||
.connected_sources()
|
||||
.into_iter()
|
||||
.take(4096)
|
||||
.map(|s| PluginConnectedDataSource {
|
||||
source_id: s.source_id,
|
||||
name: s.name,
|
||||
driver: driver_name(s.driver).to_owned(),
|
||||
database: s.database,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(super) fn connected_sources_across(
|
||||
dbs: &[Arc<ide_db::DbManager>],
|
||||
) -> Result<Vec<PluginConnectedDataSource>, HostError> {
|
||||
let mut by_id = std::collections::BTreeMap::new();
|
||||
for db in dbs {
|
||||
for s in db.connected_sources() {
|
||||
by_id.entry(s.source_id.clone()).or_insert_with(|| PluginConnectedDataSource {
|
||||
source_id: s.source_id,
|
||||
name: s.name,
|
||||
driver: driver_name(s.driver).to_owned(),
|
||||
database: s.database,
|
||||
});
|
||||
if by_id.len() >= 4096 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if by_id.len() >= 4096 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(by_id.into_values().collect())
|
||||
}
|
||||
|
||||
pub(super) async fn list_schemas(
|
||||
db: &ide_db::DbManager,
|
||||
source_id: &str,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<String>, HostError> {
|
||||
if !valid_db_ident(source_id, true) {
|
||||
return Err(HostError::Invalid("invalid database source id".into()));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
let read = db.connected_schemas(source_id);
|
||||
let mut schemas = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(HostError::Cancelled),
|
||||
result = tokio::time::timeout(timeout, read) => result
|
||||
.map_err(|_| HostError::Failed("Database schemas request timed out".into()))?.map_err(error)?,
|
||||
};
|
||||
schemas.truncate(4096);
|
||||
Ok(schemas)
|
||||
}
|
||||
|
||||
pub(super) async fn list_tables(
|
||||
db: &ide_db::DbManager,
|
||||
source_id: &str,
|
||||
schema: &str,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<PluginDatabaseTableSummary>, HostError> {
|
||||
if !valid_db_ident(source_id, true) || !valid_db_ident(schema, false) {
|
||||
return Err(HostError::Invalid("invalid database schema reference".into()));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
let read = db.connected_tables(source_id, schema);
|
||||
let tables = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(HostError::Cancelled),
|
||||
result = tokio::time::timeout(timeout, read) => result
|
||||
.map_err(|_| HostError::Failed("Database tables request timed out".into()))?.map_err(error)?,
|
||||
};
|
||||
Ok(tables
|
||||
.into_iter()
|
||||
.take(4096)
|
||||
.map(|t| PluginDatabaseTableSummary {
|
||||
name: t.name,
|
||||
kind: table_kind_name(t.kind).to_owned(),
|
||||
comment: t.comment,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(super) async fn execute_query(
|
||||
db: &ide_db::DbManager,
|
||||
source_id: &str,
|
||||
sql: &str,
|
||||
max_rows: Option<u32>,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Duration,
|
||||
) -> Result<PluginDatabaseQueryResult, HostError> {
|
||||
if !valid_db_ident(source_id, true) {
|
||||
return Err(HostError::Invalid("invalid database source id".into()));
|
||||
}
|
||||
if sql.trim().is_empty() || sql.len() > 262_144 || sql.contains('\0') {
|
||||
return Err(HostError::Invalid("invalid SQL statement".into()));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
let limit = max_rows.unwrap_or(100).clamp(1, 1000) as usize;
|
||||
let query_cancel = cancel.child_token();
|
||||
let timer_cancel = query_cancel.clone();
|
||||
let timed_out = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let timed_out_flag = timed_out.clone();
|
||||
let timer = tokio::spawn(async move {
|
||||
tokio::time::sleep(timeout).await;
|
||||
timed_out_flag.store(true, std::sync::atomic::Ordering::Release);
|
||||
timer_cancel.cancel();
|
||||
});
|
||||
// Allow a brief grace window after cancelling `query_cancel` so drivers can send server-side
|
||||
// cancel (`pg_cancel_backend` / `KILL QUERY`) and discard the interrupted connection cleanly.
|
||||
let grace = timeout.saturating_add(Duration::from_secs(2));
|
||||
let run = db.connected_execute(source_id, sql, limit, &query_cancel);
|
||||
let outcome = tokio::select! {
|
||||
biased;
|
||||
result = tokio::time::timeout(grace, run) => result,
|
||||
_ = async {
|
||||
cancel.cancelled().await;
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
} => {
|
||||
timer.abort();
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
};
|
||||
timer.abort();
|
||||
let mut result = match outcome {
|
||||
Err(_) => {
|
||||
return Err(if cancel.is_cancelled() {
|
||||
HostError::Cancelled
|
||||
} else {
|
||||
HostError::Failed("Database query execution timed out".into())
|
||||
});
|
||||
}
|
||||
Ok(Ok(result)) => result,
|
||||
Ok(Err(err)) => {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
if timed_out.load(std::sync::atomic::Ordering::Acquire) && err.kind == ide_core::error::ErrorKind::Cancelled
|
||||
{
|
||||
return Err(HostError::Failed("Database query execution timed out".into()));
|
||||
}
|
||||
return Err(error(err));
|
||||
}
|
||||
};
|
||||
result.cap_cells(8192);
|
||||
Ok(PluginDatabaseQueryResult {
|
||||
columns: result
|
||||
.columns
|
||||
.into_iter()
|
||||
.map(|c| PluginDatabaseQueryColumn { name: c.name, type_name: c.type_name })
|
||||
.collect(),
|
||||
rows: result.rows,
|
||||
affected: result.affected.and_then(|v| (v.is_finite() && v >= 0.0).then_some(v as u64)),
|
||||
has_more: result.has_more,
|
||||
elapsed_ms: if result.elapsed_ms.is_finite() { result.elapsed_ms.max(0.0) as u64 } else { 0 },
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Lets the event pump sleep until something needs it, instead of for a fixed period.
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// A flag the event pump waits on between [`flush_events`](super::PluginHost::flush_events)
|
||||
/// calls: waking it early costs one notification, an idle pump still wakes only on its
|
||||
/// timeout. A notification made while the pump is busy is kept for its next wait.
|
||||
#[derive(Default)]
|
||||
pub struct EventWake {
|
||||
signalled: Mutex<bool>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
impl EventWake {
|
||||
/// Makes the current or next [`wait`](Self::wait) return at once.
|
||||
pub fn notify(&self) {
|
||||
*self.signalled.lock() = true;
|
||||
self.changed.notify_one();
|
||||
}
|
||||
|
||||
/// Blocks until [`notify`](Self::notify) or `timeout`; true when it was notified.
|
||||
pub fn wait(&self, timeout: Duration) -> bool {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut signalled = self.signalled.lock();
|
||||
while !*signalled {
|
||||
if self.changed.wait_until(&mut signalled, deadline).timed_out() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::mem::take(&mut *signalled)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn a_notification_ends_the_wait_and_is_consumed() {
|
||||
let wake = EventWake::default();
|
||||
assert!(!wake.wait(Duration::from_millis(10)), "times out when idle");
|
||||
wake.notify();
|
||||
assert!(wake.wait(Duration::from_secs(5)), "kept for the next wait");
|
||||
assert!(!wake.wait(Duration::ZERO), "consumed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiting_pump_wakes_early() {
|
||||
let wake = Arc::new(EventWake::default());
|
||||
let start = Instant::now();
|
||||
let waiter = {
|
||||
let wake = wake.clone();
|
||||
std::thread::spawn(move || wake.wait(Duration::from_secs(30)))
|
||||
};
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
wake.notify();
|
||||
assert!(waiter.join().unwrap());
|
||||
assert!(start.elapsed() < Duration::from_secs(10));
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ pub struct NavigationFiles {
|
||||
pub indexing: bool,
|
||||
pub extensions: Vec<String>,
|
||||
/// In-scope files matching `extensions`; `paths` holds the first
|
||||
/// `MAX_NAVIGATION_FILES` of them.
|
||||
/// `MAX_NAVIGATION_FILES` of them by path.
|
||||
pub total: u32,
|
||||
pub truncated: bool,
|
||||
}
|
||||
@@ -19,9 +19,11 @@ pub struct NavigationFiles {
|
||||
/// on the first ones instead of none.
|
||||
const MAX_NAVIGATION_FILES: usize = 20_000;
|
||||
|
||||
/// The first `limit` files `in_scope` accepts, and how many it accepts in all.
|
||||
/// The first `limit` files by path that `in_scope` accepts, and how many it accepts in all.
|
||||
/// Sorting keeps the covered files the same across index rebuilds.
|
||||
fn first_in_scope(files: Vec<PathBuf>, in_scope: impl Fn(&PathBuf) -> bool, limit: usize) -> (Vec<PathBuf>, usize) {
|
||||
let mut files: Vec<_> = files.into_iter().filter(in_scope).collect();
|
||||
files.sort_unstable();
|
||||
let total = files.len();
|
||||
files.truncate(limit);
|
||||
(files, total)
|
||||
@@ -239,7 +241,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn discovery_keeps_the_first_in_scope_files_and_counts_them_all() {
|
||||
let files: Vec<PathBuf> = (0..7).map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
|
||||
let files: Vec<PathBuf> = (0..7).rev().map(|i| PathBuf::from(format!("/p/{}/f{i}.xml", i % 2))).collect();
|
||||
let (kept, total) = first_in_scope(files, |p| p.starts_with("/p/0"), 3);
|
||||
// Out-of-scope files neither take a slot nor count toward the total.
|
||||
assert_eq!(total, 4);
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Linked plugins (`openidea-plugin link`) are read in place, so editing their files
|
||||
//! reloads them: a theme regenerated by a script, a rebuilt `dist/plugin.wasm`.
|
||||
//!
|
||||
//! Every linked plugin folder is watched recursively. The watcher already coalesces a
|
||||
//! burst (a write-then-rename, a build touching many files) into one batch, so a batch
|
||||
//! with a relevant change marks its folder as changed and wakes the event pump
|
||||
//! ([`super::PluginHost::event_wake`]); [`super::PluginHost::flush_events_at`] then
|
||||
//! reloads the plugin right away. Installed copies and project plugins are never watched.
|
||||
use super::event_wake::EventWake;
|
||||
use ide_core::NullSink;
|
||||
use ide_vfs::{FsBatch, Watcher};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Folders whose contents never belong to a plugin package.
|
||||
const SKIPPED_DIRS: [&str; 3] = [".git", "target", "node_modules"];
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct LinkedWatches {
|
||||
watchers: Mutex<BTreeMap<PathBuf, Watcher>>,
|
||||
/// Folders with a change that has not been reloaded yet.
|
||||
changed: Arc<Mutex<BTreeSet<PathBuf>>>,
|
||||
/// Signalled when a folder is added to `changed`.
|
||||
wake: Arc<EventWake>,
|
||||
/// Folders that could not be watched, so the warning is given once.
|
||||
failed: Mutex<BTreeSet<PathBuf>>,
|
||||
}
|
||||
|
||||
impl LinkedWatches {
|
||||
/// What the event pump waits on; signalled when a linked folder changes.
|
||||
pub fn wake(&self) -> Arc<EventWake> {
|
||||
self.wake.clone()
|
||||
}
|
||||
|
||||
/// Watches exactly `dirs`: starts the missing watchers, stops the others.
|
||||
pub fn sync(&self, dirs: &BTreeSet<PathBuf>) {
|
||||
let mut watchers = self.watchers.lock();
|
||||
watchers.retain(|dir, _| dirs.contains(dir));
|
||||
self.changed.lock().retain(|dir| dirs.contains(dir));
|
||||
self.failed.lock().retain(|dir| dirs.contains(dir));
|
||||
for dir in dirs {
|
||||
if watchers.contains_key(dir) {
|
||||
continue;
|
||||
}
|
||||
match self.watch(dir) {
|
||||
Ok(watcher) => {
|
||||
watchers.insert(dir.clone(), watcher);
|
||||
}
|
||||
Err(e) => {
|
||||
if self.failed.lock().insert(dir.clone()) {
|
||||
tracing::warn!("linked plugin {} is not reloaded on change: {e}", dir.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn watch(&self, dir: &Path) -> ide_core::IdeResult<Watcher> {
|
||||
let changed = Arc::downgrade(&self.changed);
|
||||
let wake = Arc::downgrade(&self.wake);
|
||||
// Events carry canonical paths.
|
||||
let root = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
|
||||
let key = dir.to_path_buf();
|
||||
let on_change = Box::new(move |batch: &FsBatch| {
|
||||
if !affects_plugin(&root, batch) {
|
||||
return;
|
||||
}
|
||||
let (Some(changed), Some(wake)) = (changed.upgrade(), wake.upgrade()) else { return };
|
||||
changed.lock().insert(key.clone());
|
||||
wake.notify();
|
||||
});
|
||||
let excludes = SKIPPED_DIRS.iter().map(|d| (*d).to_owned()).collect();
|
||||
Watcher::start(dir, excludes, Arc::new(NullSink), on_change)
|
||||
}
|
||||
|
||||
/// The folders changed since the last call.
|
||||
pub fn take_changed(&self) -> Vec<PathBuf> {
|
||||
std::mem::take(&mut *self.changed.lock()).into_iter().collect()
|
||||
}
|
||||
|
||||
/// Stops every watch.
|
||||
pub fn clear(&self) {
|
||||
self.watchers.lock().clear();
|
||||
self.changed.lock().clear();
|
||||
self.failed.lock().clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `batch` holds a change that can affect the package in `root`. Ignored files
|
||||
/// count: a generated theme is often listed in the package's `.gitignore`.
|
||||
fn affects_plugin(root: &Path, batch: &FsBatch) -> bool {
|
||||
batch.created.iter().chain(&batch.modified).chain(&batch.removed).chain(&batch.ignored).any(|p| relevant(root, p))
|
||||
}
|
||||
|
||||
fn relevant(root: &Path, path: &Path) -> bool {
|
||||
let rel = path.strip_prefix(root).unwrap_or(path);
|
||||
if rel.components().any(|c| matches!(c, Component::Normal(n) if SKIPPED_DIRS.iter().any(|d| n == *d))) {
|
||||
return false;
|
||||
}
|
||||
let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return true };
|
||||
!(name.ends_with('~')
|
||||
|| name.ends_with(".swp")
|
||||
|| name.ends_with(".swx")
|
||||
|| name.starts_with(".#")
|
||||
|| (name.starts_with('#') && name.ends_with('#'))
|
||||
|| name == "4913"
|
||||
|| name == ".DS_Store")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn only_package_files_count() {
|
||||
let root = Path::new("/links/theme");
|
||||
for kept in ["theme.json", "themes/dark.json", "dist/plugin.wasm", "plugin.toml", ".hidden.json"] {
|
||||
assert!(relevant(root, &root.join(kept)), "{kept}");
|
||||
}
|
||||
for skipped in [
|
||||
".git/index",
|
||||
"target/debug/build.rs",
|
||||
"sub/node_modules/x/package.json",
|
||||
"theme.json~",
|
||||
".theme.json.swp",
|
||||
".#theme.json",
|
||||
"#theme.json#",
|
||||
"4913",
|
||||
".DS_Store",
|
||||
] {
|
||||
assert!(!relevant(root, &root.join(skipped)), "{skipped}");
|
||||
}
|
||||
// A plugin that itself lives below a `target` folder is still watched.
|
||||
let nested = Path::new("/work/target/plugin");
|
||||
assert!(relevant(nested, &nested.join("theme.json")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_is_taken_once_and_wakes_the_pump() {
|
||||
let watches = LinkedWatches::default();
|
||||
let dir = PathBuf::from("/links/theme");
|
||||
let wake = watches.wake();
|
||||
assert!(watches.take_changed().is_empty());
|
||||
assert!(!wake.wait(Duration::ZERO));
|
||||
watches.changed.lock().insert(dir.clone());
|
||||
watches.changed.lock().insert(dir.clone());
|
||||
assert_eq!(watches.take_changed(), vec![dir]);
|
||||
assert!(watches.take_changed().is_empty(), "reloaded once");
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ pub(crate) mod diagnostics;
|
||||
pub mod docs;
|
||||
mod endpoints;
|
||||
mod event_paths;
|
||||
mod event_wake;
|
||||
mod execution;
|
||||
mod external_watch;
|
||||
mod files_changed;
|
||||
@@ -44,6 +45,7 @@ pub mod intellij;
|
||||
mod ipc;
|
||||
mod java_agents;
|
||||
pub mod language_features;
|
||||
mod linked_watch;
|
||||
mod market;
|
||||
mod mcp;
|
||||
pub mod navigation;
|
||||
@@ -68,6 +70,7 @@ mod websocket;
|
||||
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use build_graph::{BuildGraph, GradleModule};
|
||||
pub use docs::{MAX_PLUGIN_DOC, PluginDocs, explain_capabilities, plugin_docs};
|
||||
pub use event_wake::EventWake;
|
||||
pub(crate) use execution::plugin_run_config_owner;
|
||||
pub(crate) use hover::merge as merge_hover;
|
||||
pub use icons::{
|
||||
@@ -419,6 +422,8 @@ pub struct PluginHost {
|
||||
queues: Mutex<BTreeMap<QueueKey, EventQueue>>,
|
||||
/// Serializes loading / unloading so concurrent windows can't race.
|
||||
lifecycle: Mutex<()>,
|
||||
/// Watches of the linked plugins' folders: their changes reload them.
|
||||
linked_watches: linked_watch::LinkedWatches,
|
||||
/// Set once the first [`load_all`](Self::load_all) has finished.
|
||||
initial_load: (Mutex<bool>, Condvar),
|
||||
/// `on-startup-finished` has fired.
|
||||
@@ -544,6 +549,7 @@ impl PluginHost {
|
||||
shared,
|
||||
queues: Mutex::default(),
|
||||
lifecycle: Mutex::new(()),
|
||||
linked_watches: Default::default(),
|
||||
initial_load: (Mutex::new(false), Condvar::new()),
|
||||
startup_finished: AtomicBool::new(false),
|
||||
fired_activations: Mutex::new(Vec::new()),
|
||||
@@ -636,6 +642,7 @@ impl PluginHost {
|
||||
for plugin in self.in_start_order(to_start) {
|
||||
self.start(&plugin);
|
||||
}
|
||||
self.watch_linked();
|
||||
let (done, cv) = &self.initial_load;
|
||||
*done.lock() = true;
|
||||
cv.notify_all();
|
||||
@@ -830,6 +837,41 @@ impl PluginHost {
|
||||
self.reconcile();
|
||||
self.changed();
|
||||
}
|
||||
self.watch_linked();
|
||||
}
|
||||
|
||||
/// Watches the folders of the loaded linked plugins and no others.
|
||||
fn watch_linked(&self) {
|
||||
let dirs = self
|
||||
.plugins
|
||||
.read()
|
||||
.values()
|
||||
.filter(|p| p.source == PluginSource::Linked)
|
||||
.map(|p| p.dir().to_path_buf())
|
||||
.collect();
|
||||
self.linked_watches.sync(&dirs);
|
||||
}
|
||||
|
||||
/// What the event pump waits on instead of sleeping: signalled when a linked
|
||||
/// plugin's files change, so [`flush_events`](Self::flush_events) can reload it at once.
|
||||
/// Hold it rather than the host, which the pump must be able to let go of.
|
||||
pub fn event_wake(&self) -> Arc<EventWake> {
|
||||
self.linked_watches.wake()
|
||||
}
|
||||
|
||||
/// Reloads the linked plugins whose files changed. A plugin that no longer loads
|
||||
/// shows its error like after Reload; the next valid write loads it again.
|
||||
fn reload_changed_links(&self) {
|
||||
for dir in self.linked_watches.take_changed() {
|
||||
let id = {
|
||||
let plugins = self.plugins.read();
|
||||
plugins.values().find(|p| p.source == PluginSource::Linked && p.dir() == dir).map(|p| p.id().to_owned())
|
||||
};
|
||||
let Some(id) = id else { continue };
|
||||
if let Err(e) = self.reload(&id) {
|
||||
tracing::info!(plugin = %id, "reload after a file change: {}", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Links a development plugin folder (loaded until unlinked; granted by path).
|
||||
@@ -2375,13 +2417,15 @@ impl PluginHost {
|
||||
/// Delivers queued events: to running plugins right away, to idle ones
|
||||
/// (which must be activated) after [`IDLE_BATCH`], so frequent events
|
||||
/// don't keep waking them. Filesystem events are already debounced by
|
||||
/// the watcher and bypass that delay. Call it a few times a second.
|
||||
/// the watcher and bypass that delay. Call it a few times a second, and
|
||||
/// whenever [`event_wake`](Self::event_wake) is signalled.
|
||||
pub fn flush_events(&self) {
|
||||
self.flush_events_at(Instant::now());
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn flush_events_at(&self, now: Instant) {
|
||||
self.reload_changed_links();
|
||||
self.queue_watched_changes(now);
|
||||
let running: BTreeSet<String> = self
|
||||
.plugins
|
||||
@@ -2828,6 +2872,7 @@ impl PluginHost {
|
||||
|
||||
/// Deactivates every plugin (also done on drop).
|
||||
pub fn shutdown(&self) {
|
||||
self.linked_watches.clear();
|
||||
let (ids, actors): (Vec<String>, Vec<_>) = {
|
||||
let plugins = self.plugins.read();
|
||||
let ids = plugins.keys().cloned().collect();
|
||||
|
||||
@@ -12,7 +12,8 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
pub const MAX_DOCUMENT_BYTES: usize = ide_lsp::MAX_INJECTED_DOCUMENT_BYTES;
|
||||
const MAX_FILES: usize = 20_000;
|
||||
/// Files one plugin's graph covers per project and window.
|
||||
pub const MAX_FILES: usize = 20_000;
|
||||
const MAX_EDGES: usize = 4096;
|
||||
|
||||
pub struct Snapshot<'a> {
|
||||
@@ -237,6 +238,13 @@ impl PluginHost {
|
||||
}
|
||||
let lines: Vec<_> = text.split('\n').map(|l| l.encode_utf16().count()).collect();
|
||||
for plugin in plugins {
|
||||
// A full graph keeps the files it covers; discovery already told the user
|
||||
// the rest are left out, so they are skipped without running the plugin.
|
||||
if self.navigation.lock().projects.get(&project_key).and_then(|g| g.get(plugin.id())).is_some_and(|g| {
|
||||
g.instance.ptr_eq(&Arc::downgrade(&plugin)) && g.files.len() >= MAX_FILES && !g.files.contains_key(path)
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
let (actor, activated) = self.ensure_active(&plugin, invocation.client.as_deref())?;
|
||||
if activated {
|
||||
self.changed();
|
||||
@@ -315,7 +323,7 @@ impl PluginHost {
|
||||
*graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() };
|
||||
}
|
||||
if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) {
|
||||
return Err(IdeError::unavailable("navigation file limit reached"));
|
||||
continue;
|
||||
}
|
||||
graph.remove(path);
|
||||
if graph.edges
|
||||
|
||||
@@ -99,6 +99,7 @@ pub fn register_builtin_points(
|
||||
registry.register(Arc::new(UiPoint::new(p::DIALOGS, ui.clone(), p::dialog)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::RUN_CONFIG_TYPES, ui.clone(), p::run_config_type)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::RUN_ANYTHING, ui.clone(), p::run_anything)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::CLONE_SOURCES, ui.clone(), p::clone_source)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::MARKER_ICONS, ui.clone(), p::marker_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_TEMPLATES, ui.clone(), p::file_template)))?;
|
||||
|
||||
@@ -30,8 +30,8 @@ use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The server command the desktop calls with its packages.
|
||||
pub const SYNC_PACKAGES: &str = "plugin_sync_packages";
|
||||
@@ -319,7 +319,7 @@ impl RemotePlugins {
|
||||
ide_run::set_external_detection(Some(host.run_detection()));
|
||||
host.load_all();
|
||||
host.startup_finished();
|
||||
spawn_supervision(Arc::downgrade(&host))?;
|
||||
spawn_supervision(&host)?;
|
||||
Ok(Arc::new(Self { host, incoming: data_dir.join(INCOMING_DIR), sync: Mutex::new(()) }))
|
||||
}
|
||||
|
||||
@@ -453,13 +453,17 @@ impl RemotePlugins {
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_supervision(host: Weak<PluginHost>) -> IdeResult<()> {
|
||||
fn spawn_supervision(host: &Arc<PluginHost>) -> IdeResult<()> {
|
||||
let wake = host.event_wake();
|
||||
let host = Arc::downgrade(host);
|
||||
std::thread::Builder::new().name("remote-plugins".into()).spawn(move || {
|
||||
for n in 1u32.. {
|
||||
std::thread::sleep(EVENT_FLUSH);
|
||||
let mut tick_due = Instant::now() + EVENT_FLUSH * TICKS_PER_SUPERVISION;
|
||||
loop {
|
||||
wake.wait(EVENT_FLUSH);
|
||||
let Some(host) = host.upgrade() else { return };
|
||||
host.flush_events();
|
||||
if n % TICKS_PER_SUPERVISION == 0 {
|
||||
if Instant::now() >= tick_due {
|
||||
tick_due = Instant::now() + EVENT_FLUSH * TICKS_PER_SUPERVISION;
|
||||
host.tick();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,11 +463,19 @@ pub struct PluginEditor {
|
||||
pub path: String,
|
||||
pub language: String,
|
||||
pub selections: Vec<ide_core::Range>,
|
||||
/// First and last document line on screen (0-based, inclusive); absent from older clients.
|
||||
#[serde(default)]
|
||||
pub visible_lines: Option<(u32, u32)>,
|
||||
}
|
||||
|
||||
impl PluginEditor {
|
||||
pub fn context(self) -> ide_plugin::EditorContext {
|
||||
ide_plugin::EditorContext { path: self.path.into(), language: self.language, selections: self.selections }
|
||||
ide_plugin::EditorContext {
|
||||
path: self.path.into(),
|
||||
language: self.language,
|
||||
selections: self.selections,
|
||||
visible_lines: self.visible_lines,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,8 @@
|
||||
//!
|
||||
//! [[contributes.statusBar]]
|
||||
//! id = "branch"
|
||||
//! text = "…" # code replaces it with `set-status-item("branch", …)`
|
||||
//! icon = "icons/branch.svg" # API 1.21: built-in name or package SVG (`iconDark` for dark themes); optional if `text` is given
|
||||
//! text = "…" # optional when `icon` is given (API 1.21); code replaces it with `set-status-item("branch", …)`
|
||||
//! command = "show"
|
||||
//!
|
||||
//! [contributes.settings]
|
||||
@@ -109,8 +110,11 @@ pub const OVERLAYS: &str = "overlays";
|
||||
pub const DIALOGS: &str = "dialogs";
|
||||
pub const RUN_CONFIG_TYPES: &str = "runConfigTypes";
|
||||
pub const RUN_ANYTHING: &str = "runAnything";
|
||||
/// Entries of the Clone Repository dialog's source list, each a web page.
|
||||
pub const CLONE_SOURCES: &str = "cloneSources";
|
||||
/// The points whose declarations can name a `web` page (served, messaged, sent view events).
|
||||
pub const WEB_POINTS: [&str; 6] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS, RUN_CONFIG_TYPES];
|
||||
pub const WEB_POINTS: [&str; 7] =
|
||||
[VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS, RUN_CONFIG_TYPES, CLONE_SOURCES];
|
||||
pub const FILE_ICONS: &str = "fileIcons";
|
||||
pub const MARKER_ICONS: &str = "markerIcons";
|
||||
pub const FILE_TEMPLATES: &str = "fileTemplates";
|
||||
@@ -269,7 +273,7 @@ struct KeymapDecl {
|
||||
const ESCAPE: &str = "Escape";
|
||||
|
||||
const MODIFIERS: [&str; 4] = ["Meta", "Ctrl", "Alt", "Shift"];
|
||||
const NAMED_KEYS: [&str; 22] = [
|
||||
const NAMED_KEYS: [&str; 24] = [
|
||||
"Enter",
|
||||
"Escape",
|
||||
"Tab",
|
||||
@@ -292,6 +296,8 @@ const NAMED_KEYS: [&str; 22] = [
|
||||
"Slash",
|
||||
"Semicolon",
|
||||
"Quote",
|
||||
"Backslash",
|
||||
"Backquote",
|
||||
];
|
||||
|
||||
/// `Ctrl+Alt+C`, `Meta+K Meta+C` (a chord): at least one modifier per
|
||||
@@ -340,16 +346,25 @@ pub(super) fn keymap(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String>
|
||||
if binding != ESCAPE {
|
||||
validate_binding(binding).map_err(|e| format!("contributes.keymaps: {e}"))?;
|
||||
}
|
||||
let key_names = binding.split_whitespace().filter_map(|stroke| stroke.rsplit('+').next());
|
||||
if key_names.into_iter().any(|key| key == "Backslash" || key == "Backquote") {
|
||||
pkg.manifest.needs_api("contributes.keymaps key `Backslash` / `Backquote`", 21)?;
|
||||
}
|
||||
}
|
||||
Ok(UiDecl::new(d.command.clone(), d.key.clone(), json(&d)?))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct StatusDecl {
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
text: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
icon_dark: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
tooltip: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
command: Option<String>,
|
||||
@@ -363,11 +378,22 @@ fn right() -> String {
|
||||
"right".into()
|
||||
}
|
||||
|
||||
/// Asset id of a status bar item's SVG (`dark`: its dark-theme variant).
|
||||
pub fn status_bar_icon_asset(id: &str, dark: bool) -> String {
|
||||
format!("statusBarIcon/{id}/{}", if dark { "dark" } else { "light" })
|
||||
}
|
||||
|
||||
pub(super) fn status_item(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: StatusDecl = decode(STATUS_BAR, decl)?;
|
||||
validate_item_id(&d.id, "status bar item id")?;
|
||||
if d.text.is_empty() || d.text.len() > 128 || d.tooltip.as_ref().is_some_and(|t| t.len() > 1024) {
|
||||
return Err(format!("status bar item {:?}: `text` 1–128 bytes, `tooltip` up to 1 KiB", d.id));
|
||||
if d.icon.is_some() || d.icon_dark.is_some() || d.text.is_empty() {
|
||||
pkg.manifest.needs_api(&format!("status bar item {:?}: `icon` / empty `text`", d.id), 21)?;
|
||||
}
|
||||
if d.text.len() > 128 || d.tooltip.as_ref().is_some_and(|t| t.len() > 1024) {
|
||||
return Err(format!("status bar item {:?}: `text` up to 128 bytes, `tooltip` up to 1 KiB", d.id));
|
||||
}
|
||||
if d.text.is_empty() && d.icon.is_none() {
|
||||
return Err(format!("status bar item {:?}: `text` (1–128 bytes) or `icon` is required", d.id));
|
||||
}
|
||||
if d.align != "left" && d.align != "right" {
|
||||
return Err(format!("status bar item {:?}: `align` is left or right", d.id));
|
||||
@@ -378,7 +404,32 @@ pub(super) fn status_item(pkg: &Package, decl: toml::Value) -> Result<UiDecl, St
|
||||
if let Some(c) = &d.command {
|
||||
declared_command(pkg, STATUS_BAR, c)?;
|
||||
}
|
||||
Ok(UiDecl::new(d.id.clone(), d.text.clone(), json(&d)?))
|
||||
let mut files = Vec::new();
|
||||
let mut assets = Vec::new();
|
||||
if let Some(icon) = &d.icon {
|
||||
if icon.ends_with(".svg") {
|
||||
let path = PathBuf::from(icon);
|
||||
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
|
||||
files.push(path);
|
||||
assets.push((status_bar_icon_asset(&d.id, false), svg));
|
||||
} else if icon.trim().is_empty() || icon.len() > 128 || icon.chars().any(char::is_control) {
|
||||
return Err(format!("status bar item {:?}: `icon` is 1–128 bytes without controls", d.id));
|
||||
}
|
||||
}
|
||||
if let Some(dark) = &d.icon_dark {
|
||||
if !d.icon.as_deref().is_some_and(|i| i.ends_with(".svg")) || !dark.ends_with(".svg") {
|
||||
return Err(format!("status bar item {:?}: `iconDark` requires an .svg `icon` and an .svg path", d.id));
|
||||
}
|
||||
let path = PathBuf::from(dark);
|
||||
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
|
||||
files.push(path);
|
||||
assets.push((status_bar_icon_asset(&d.id, true), svg));
|
||||
}
|
||||
let label = if d.text.is_empty() { d.tooltip.clone().unwrap_or_else(|| d.id.clone()) } else { d.text.clone() };
|
||||
let mut out = UiDecl::new(d.id.clone(), label, json(&d)?);
|
||||
out.files = files;
|
||||
out.assets = assets;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -1297,6 +1348,10 @@ struct DialogDecl {
|
||||
web: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// API 1.21: a lightweight popup (the title in its header, no title bar) that closes when
|
||||
/// the user clicks outside it or switches to another window, as Search Everywhere does.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
popup: bool,
|
||||
}
|
||||
|
||||
const DIALOG_WIDTH: std::ops::RangeInclusive<u32> = 320..=1600;
|
||||
@@ -1311,6 +1366,9 @@ pub(super) fn dialog(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String>
|
||||
pkg.manifest.needs_api(&format!("contributes.{DIALOGS}"), 18)?;
|
||||
validate_item_id(&d.id, "dialog id")?;
|
||||
let what = format!("dialog {:?}", d.id);
|
||||
if d.popup {
|
||||
pkg.manifest.needs_api(&format!("{what}: `popup`"), 21)?;
|
||||
}
|
||||
// `views.reveal(id)` opens it, so it can't share an id with a tool window.
|
||||
if pkg.manifest.declarations(VIEWS).iter().any(|v| v.get("id").and_then(|i| i.as_str()) == Some(&d.id)) {
|
||||
return Err(format!("{what}: a view has the same id"));
|
||||
@@ -1482,6 +1540,48 @@ pub(super) fn run_config_type(pkg: &Package, decl: toml::Value) -> Result<UiDecl
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CloneSourceDecl {
|
||||
id: String,
|
||||
label: String,
|
||||
/// An IDE icon name (`branch`, `git-pull`) or a package SVG (`icons/gitee.svg`),
|
||||
/// as on a view: the pane lists the service's own logo.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
/// The page that lists repositories and posts the chosen clone URL.
|
||||
/// Required: the dialog has nothing else to show for a source.
|
||||
web: String,
|
||||
}
|
||||
|
||||
pub(super) fn clone_source(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: CloneSourceDecl = decode(CLONE_SOURCES, decl)?;
|
||||
pkg.manifest.needs_api(&format!("contributes.{CLONE_SOURCES}"), 21)?;
|
||||
validate_item_id(&d.id, "clone source id")?;
|
||||
title(CLONE_SOURCES, &d.label)?;
|
||||
let what = format!("clone source {:?}", d.id);
|
||||
if d.icon.as_ref().is_some_and(|i| i.len() > 64) {
|
||||
return Err(format!("clone source {:?}: icon names are up to 64 bytes", d.id));
|
||||
}
|
||||
let files = super::web::web_files(pkg, &d.web, &what)?;
|
||||
// The key is namespaced with the point: a source's page is served, messaged
|
||||
// and sent view events under it, and it cannot collide with a view's id.
|
||||
let mut out = UiDecl::new(format!("{CLONE_SOURCES}/{}", d.id), d.label.clone(), json(&d)?);
|
||||
out.files = files;
|
||||
if let Some(icon) = d.icon.as_deref().filter(|i| i.ends_with(".svg")) {
|
||||
let path = std::path::PathBuf::from(icon);
|
||||
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
|
||||
out.assets.push((clone_source_icon_asset(&d.id), svg));
|
||||
out.files.push(path);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Asset id of a clone source's SVG icon, fetched by the workbench for the dialog.
|
||||
pub fn clone_source_icon_asset(id: &str) -> String {
|
||||
format!("cloneSourceIcon/{id}")
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct FileIconDecl {
|
||||
@@ -2567,7 +2667,11 @@ height = 600
|
||||
serde_json::json!({"id": "preview", "title": "SQL Preview", "web": "web/preview.html", "width": 900, "height": 600})
|
||||
);
|
||||
assert_eq!(valid.files, [PathBuf::from("web/preview.html")]);
|
||||
// API 1.21: a popup dialog.
|
||||
let popup = source.replace("^1.18", "^1.21").replace("height = 600", "height = 600\npopup = true");
|
||||
assert_eq!(check(&popup).unwrap().json["popup"], true);
|
||||
for (bad, error) in [
|
||||
(source.replace("height = 600", "height = 600\npopup = true"), "1.21"),
|
||||
(source.replace("^1.18", "^1.17"), "1.18"),
|
||||
(source.replace("width = 900", "width = 319"), "320–1600"),
|
||||
(source.replace("height = 600", "height = 1201"), "`height`"),
|
||||
@@ -2731,6 +2835,76 @@ title = \"Prepare\"\n"
|
||||
assert_eq!(decl.assets.iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(), ["locale/fr", "locale/zh-CN"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backslash_and_backquote_keys_need_api_1_21() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let check = |engines: &str, key: &str| {
|
||||
let source = format!(
|
||||
"id = \"p\"\nname = \"P\"\nversion = \"0.1.0\"\nengines.openidea = \"{engines}\"\n\n[[contributes.commands]]\nid = \"go\"\ntitle = \"Go\"\n\n[[contributes.keymaps]]\ncommand = \"go\"\nkey = \"{key}\"\n"
|
||||
);
|
||||
let manifest = ide_extension::Manifest::parse(&source)?;
|
||||
let decl = manifest.declarations(KEYMAPS).into_iter().next().unwrap();
|
||||
keymap(&Package::new(manifest, dir.path().to_path_buf()), decl)
|
||||
};
|
||||
assert!(check("^1.21", "Ctrl+Backslash").is_ok());
|
||||
assert!(check("^1.21", "Meta+K Ctrl+Backquote").is_ok());
|
||||
assert!(check("^1.20", "Ctrl+Backslash").unwrap_err().contains("1.21"));
|
||||
assert!(check("^1.20", "Ctrl+Slash").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_bar_validates_icon_and_empty_text() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("icons")).unwrap();
|
||||
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M0 0h16v16H0z"/></svg>"#;
|
||||
std::fs::write(dir.path().join("icons/status.svg"), svg).unwrap();
|
||||
std::fs::write(dir.path().join("icons/status_dark.svg"), svg).unwrap();
|
||||
|
||||
let check = |source: &str| {
|
||||
let manifest = ide_extension::Manifest::parse(source)?;
|
||||
let decl = manifest.declarations(STATUS_BAR).into_iter().next().unwrap();
|
||||
status_item(&Package::new(manifest, dir.path().to_path_buf()), decl)
|
||||
};
|
||||
|
||||
let legacy = "id = \"p\"\nname = \"P\"\nversion = \"0.1.0\"\nengines.openidea = \"^1.0\"\n\n[[contributes.statusBar]]\nid = \"s\"\ntext = \"Hello\"\n";
|
||||
let legacy_out = check(legacy).unwrap();
|
||||
assert_eq!(legacy_out.label, "Hello");
|
||||
assert!(legacy_out.assets.is_empty());
|
||||
|
||||
let svg_only = "id = \"p\"\nname = \"P\"\nversion = \"0.1.0\"\nengines.openidea = \"^1.21\"\n\n[[contributes.statusBar]]\nid = \"s\"\nicon = \"icons/status.svg\"\niconDark = \"icons/status_dark.svg\"\ntooltip = \"My Status\"\n";
|
||||
let svg_out = check(svg_only).unwrap();
|
||||
assert_eq!(svg_out.label, "My Status");
|
||||
assert_eq!(svg_out.files, [PathBuf::from("icons/status.svg"), PathBuf::from("icons/status_dark.svg")]);
|
||||
assert_eq!(
|
||||
svg_out.assets.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
|
||||
["statusBarIcon/s/light", "statusBarIcon/s/dark"]
|
||||
);
|
||||
|
||||
let builtin = "id = \"p\"\nname = \"P\"\nversion = \"0.1.0\"\nengines.openidea = \"^1.21\"\n\n[[contributes.statusBar]]\nid = \"s\"\nicon = \"terminal\"\n";
|
||||
let builtin_out = check(builtin).unwrap();
|
||||
assert_eq!(builtin_out.label, "s");
|
||||
assert!(builtin_out.assets.is_empty());
|
||||
|
||||
for (bad, error) in [
|
||||
(svg_only.replace("^1.21", "^1.20"), "1.21"),
|
||||
(legacy.replace("text = \"Hello\"", "text = \"\"").replace("^1.0", "^1.20"), "1.21"),
|
||||
(
|
||||
"id = \"p\"\nname = \"P\"\nversion = \"0.1.0\"\nengines.openidea = \"^1.21\"\n\n[[contributes.statusBar]]\nid = \"s\"\n"
|
||||
.to_owned(),
|
||||
"`text`",
|
||||
),
|
||||
(
|
||||
"id = \"p\"\nname = \"P\"\nversion = \"0.1.0\"\nengines.openidea = \"^1.21\"\n\n[[contributes.statusBar]]\nid = \"s\"\nicon = \"terminal\"\niconDark = \"icons/status_dark.svg\"\n"
|
||||
.to_owned(),
|
||||
"`iconDark`",
|
||||
),
|
||||
(svg_only.replace("icons/status.svg", "icons/missing.svg"), "no such file"),
|
||||
] {
|
||||
let err = check(&bad).unwrap_err();
|
||||
assert!(err.contains(error), "{bad}\n→ {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_catalogs_are_refused() {
|
||||
for (name, text) in [
|
||||
|
||||
@@ -25,7 +25,12 @@ pub fn view_invocation(
|
||||
Some(doc) => {
|
||||
let project = project.as_ref().ok_or_else(|| IdeError::not_found("no project is open in this window"))?;
|
||||
let info = project.documents.snapshot(doc)?;
|
||||
Some(EditorContext { path: info.path.0, language: info.language.0, selections: Vec::new() })
|
||||
Some(EditorContext {
|
||||
path: info.path.0,
|
||||
language: info.language.0,
|
||||
selections: Vec::new(),
|
||||
visible_lines: None,
|
||||
})
|
||||
}
|
||||
};
|
||||
Ok(Invocation {
|
||||
@@ -56,8 +61,9 @@ pub async fn plugin_view_render(
|
||||
}
|
||||
|
||||
/// A user action in a plugin view or custom editor (`doc`, `editor`: as for rendering).
|
||||
/// Clone-source pages live in projectless Get from VCS windows; Restricted Mode still runs no plugin code.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn plugin_view_event(
|
||||
host: &crate::Host,
|
||||
plugins: &Arc<PluginHost>,
|
||||
@@ -129,7 +135,12 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let host = Host::new(HostConfig::for_test(tmp.path()));
|
||||
let range = ide_core::Range::new(ide_core::Pos::new(1, 0), ide_core::Pos::new(1, 4));
|
||||
let active = PluginEditor { path: "/p/a.rs".into(), language: "rust".into(), selections: vec![range] };
|
||||
let active = PluginEditor {
|
||||
path: "/p/a.rs".into(),
|
||||
language: "rust".into(),
|
||||
selections: vec![range],
|
||||
visible_lines: None,
|
||||
};
|
||||
let inv = view_invocation(&host, "main", None, Some(active)).unwrap();
|
||||
let editor = inv.editor.expect("the active editor");
|
||||
assert_eq!((editor.path.to_string_lossy().as_ref(), editor.selections.as_slice()), ("/p/a.rs", &[range][..]));
|
||||
|
||||
@@ -274,6 +274,7 @@ impl Host {
|
||||
{
|
||||
let settings = settings.clone();
|
||||
let root = root.clone();
|
||||
let detected_roots = detected_roots.clone();
|
||||
let data_dir = self.local_data_dir.clone();
|
||||
let config_dir = self.config_dir.clone();
|
||||
let build_cache = self.local_data_dir.join("cache").join(&project_key).join("build");
|
||||
@@ -416,11 +417,35 @@ impl Host {
|
||||
ide_sdk::php::configure_intelephense_storage(cfg, &data_dir);
|
||||
if cfg.name == "jdtls" {
|
||||
let (excluded_poms, build_files) = jdtls_maven_import(root, &effective);
|
||||
// Only the agent worktree folders that exist: another excluded folder
|
||||
// gives jdtls a fresh workspace, which every Java project would pay for.
|
||||
let mut excluded_folders: Vec<String> = AGENT_WORKTREE_DIRS
|
||||
.iter()
|
||||
.filter(|dir| root.join(dir).is_dir())
|
||||
.map(|dir| (*dir).to_owned())
|
||||
.chain(effective.project_structure.excluded.iter().cloned())
|
||||
.collect();
|
||||
let detected = if root == window_root {
|
||||
detected_roots.read().clone()
|
||||
} else {
|
||||
ide_workspace::roots::detect(root)
|
||||
};
|
||||
for folder in linked_roots(root, &effective, &detected).roots {
|
||||
if folder.is_detected_worktree()
|
||||
&& !excluded_folders.iter().any(|existing| {
|
||||
let existing = existing.trim_matches('/');
|
||||
folder.path == existing
|
||||
|| folder.path.strip_prefix(existing).is_some_and(|rest| rest.starts_with('/'))
|
||||
})
|
||||
{
|
||||
excluded_folders.push(folder.path);
|
||||
}
|
||||
}
|
||||
ide_sdk::apply::configure_maven_import(
|
||||
cfg,
|
||||
root,
|
||||
&excluded_poms,
|
||||
&effective.project_structure.excluded,
|
||||
&excluded_folders,
|
||||
build_files.as_deref(),
|
||||
);
|
||||
ide_sdk::apply::configure_gradle_import(
|
||||
@@ -616,28 +641,6 @@ impl Host {
|
||||
sink.clone(),
|
||||
);
|
||||
}
|
||||
// Build files / conventional folders changed: re-detect roots.
|
||||
let touched = changed.iter().chain(&batch.removed).filter_map(|p| p.strip_prefix(&root).ok());
|
||||
if touched.into_iter().any(ide_workspace::roots::affects_roots) {
|
||||
ide_build::gradle::forget_build_dirs(&root);
|
||||
let fresh = ide_workspace::roots::detect(&root);
|
||||
if *detected_roots.read() != fresh {
|
||||
// Detected excluded folders (`target`, `build`) leave the index too.
|
||||
let effective = settings.effective();
|
||||
let members = member_excludes.read();
|
||||
index.set_scope(
|
||||
index_roots(
|
||||
&root,
|
||||
content_roots(&effective, &root, &build_cache, trusted.load(Ordering::Acquire)),
|
||||
&effective,
|
||||
&members,
|
||||
),
|
||||
exclude_globs(&root, &effective, &fresh, &members),
|
||||
);
|
||||
*detected_roots.write() = fresh;
|
||||
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
|
||||
}
|
||||
}
|
||||
// A repository was cloned / initialised / removed below the project:
|
||||
// its `.git/HEAD` appeared or went. A linked worktree's `.git` is a
|
||||
// plain gitfile, and that file is the only marker written inside the
|
||||
@@ -688,6 +691,40 @@ impl Host {
|
||||
// the signal. A `git clone` / `git init` inside the project already arrives
|
||||
// through the `.git` paths above; this covers the whole tree being brought in.
|
||||
git_dirs |= batch.created.iter().any(|p| p.join(".git").exists());
|
||||
// Build files, conventional folders, or linked Git worktrees changed: re-detect roots.
|
||||
let touched = changed.iter().chain(&batch.removed).filter_map(|p| p.strip_prefix(&root).ok());
|
||||
let build_roots_changed = touched.into_iter().any(ide_workspace::roots::affects_roots);
|
||||
let removed_worktree = !batch.removed.is_empty()
|
||||
&& detected_roots.read().iter().any(|r| {
|
||||
r.is_detected_worktree() && batch.removed.iter().any(|p| *p == root.join(&r.path))
|
||||
});
|
||||
if build_roots_changed || git_dirs || removed_worktree {
|
||||
if build_roots_changed {
|
||||
ide_build::gradle::forget_build_dirs(&root);
|
||||
}
|
||||
let fresh = ide_workspace::roots::detect(&root);
|
||||
if *detected_roots.read() != fresh {
|
||||
// Detected excluded folders (`target`, `build`, linked worktrees)
|
||||
// leave the index and watcher too.
|
||||
let effective = settings.effective();
|
||||
let members = member_excludes.read();
|
||||
let fresh_excludes = exclude_globs(&root, &effective, &fresh, &members);
|
||||
index.set_scope(
|
||||
index_roots(
|
||||
&root,
|
||||
content_roots(&effective, &root, &build_cache, trusted.load(Ordering::Acquire)),
|
||||
&effective,
|
||||
&members,
|
||||
),
|
||||
fresh_excludes.clone(),
|
||||
);
|
||||
if let Some(watcher) = watcher_weak.get().and_then(std::sync::Weak::upgrade) {
|
||||
watcher.set_excludes(&fresh_excludes);
|
||||
}
|
||||
*detected_roots.write() = fresh;
|
||||
sink.emit(IdeEvent::ProjectRootsChanged { root: root.clone().into() });
|
||||
}
|
||||
}
|
||||
if git_dirs {
|
||||
scan_repositories(
|
||||
&root,
|
||||
@@ -1491,15 +1528,17 @@ fn repository_scan_skips(settings: &ide_core::settings::Settings) -> impl Fn(&Pa
|
||||
/// Whether a scan of the project at `root` would look for a repository at `dir` and keep it.
|
||||
fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::Settings) -> bool {
|
||||
settings.vcs.git.enabled
|
||||
&& !settings
|
||||
.vcs
|
||||
.mappings
|
||||
.excluded
|
||||
.iter()
|
||||
.any(|p| dunce::canonicalize(VcsMappings::resolve(root, p)).is_ok_and(|e| e == dir))
|
||||
&& !repository_excluded(root, dir, &settings.vcs.mappings)
|
||||
&& Repos::searched(root, dir, &repository_scan_skips(settings))
|
||||
}
|
||||
|
||||
fn repository_excluded(project_root: &Path, repo_root: &Path, mappings: &VcsMappings) -> bool {
|
||||
mappings.excluded.iter().any(|entry| {
|
||||
let excluded = VcsMappings::resolve(project_root, entry);
|
||||
excluded == repo_root || dunce::canonicalize(excluded).is_ok_and(|path| path == repo_root)
|
||||
})
|
||||
}
|
||||
|
||||
/// When `dir`'s working-copy marker last changed.
|
||||
fn marker_time(dir: &Path, markers: &[String]) -> Option<std::time::SystemTime> {
|
||||
markers.iter().find_map(|m| dir.join(m).metadata().and_then(|m| m.modified()).ok())
|
||||
@@ -1810,6 +1849,71 @@ impl Project {
|
||||
self.with_repo_of(path, |r| f(r as &dyn Backend))
|
||||
}
|
||||
|
||||
/// Read-only editor commands can use the worktree reached through a project symlink
|
||||
/// without registering it for status, staging or other repository operations.
|
||||
pub(crate) fn with_editor_backend_of<T>(
|
||||
&self,
|
||||
path: &Path,
|
||||
f: impl FnOnce(&dyn Backend, &Path) -> IdeResult<T>,
|
||||
) -> IdeResult<T> {
|
||||
let Some(target) = self.linked_file_target(path) else {
|
||||
return self.with_backend_of(path, |backend| f(backend, path));
|
||||
};
|
||||
let unavailable = || IdeError::unavailable(format!("{} is not in a git repository", path.display()));
|
||||
if !self.git_enabled() {
|
||||
let backend = self.backend_of(path).ok_or_else(unavailable)?;
|
||||
return f(backend.as_ref(), path);
|
||||
}
|
||||
let Some(repo) = self.linked_editor_repo(path, &target)? else {
|
||||
return self.with_backend_of(path, |backend| f(backend, path));
|
||||
};
|
||||
f(repo.as_ref(), &target)
|
||||
}
|
||||
|
||||
pub(crate) fn linked_file_has_history(&self, path: &Path) -> IdeResult<bool> {
|
||||
if !self.git_enabled() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(target) = self.linked_file_target(path) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(repo) = self.linked_editor_repo(path, &target)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
Ok(repo.file_mode_at(&target, None)?.is_some_and(|mode| mode.starts_with("100")))
|
||||
}
|
||||
|
||||
fn linked_editor_repo(&self, path: &Path, target: &Path) -> IdeResult<Option<Arc<Repo>>> {
|
||||
let Some(repo) = Repo::discover(target)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mappings = self.settings.read_effective(|settings| settings.vcs.mappings.clone());
|
||||
if repository_excluded(&self.root, repo.root(), &mappings) {
|
||||
return Err(IdeError::unavailable(format!("{} is not in a git repository", path.display())));
|
||||
}
|
||||
// An unregistered target may have its own Git filters and executable settings.
|
||||
// Use the restricted read policy even when the editor's project is trusted.
|
||||
Ok(Some(self.repos().at_root(repo.root()).cloned().unwrap_or_else(|| Arc::new(repo))))
|
||||
}
|
||||
|
||||
/// Resolves a file reached through a symlink under one of the workspace project folders.
|
||||
pub(crate) fn linked_file_target(&self, path: &Path) -> Option<PathBuf> {
|
||||
let project_root = self.root_of(path);
|
||||
let relative = path.strip_prefix(&project_root).ok()?;
|
||||
if relative.components().any(|component| !matches!(component, std::path::Component::Normal(_))) {
|
||||
return None;
|
||||
}
|
||||
let target = dunce::canonicalize(path).ok()?;
|
||||
if target == path || !target.is_file() {
|
||||
return None;
|
||||
}
|
||||
// A different spelling of the same path is not by itself evidence of a symlink.
|
||||
path.ancestors()
|
||||
.take_while(|ancestor| *ancestor != project_root.as_path())
|
||||
.any(|ancestor| ancestor.symlink_metadata().is_ok_and(|metadata| metadata.is_symlink()))
|
||||
.then_some(target)
|
||||
}
|
||||
|
||||
fn run_in<T>(&self, repo: &Repo, f: impl FnOnce(&Repo) -> IdeResult<T>) -> IdeResult<T> {
|
||||
let settings = self.settings.effective();
|
||||
repo.set_ignored_names(settings.ignored_names());
|
||||
@@ -2071,6 +2175,21 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-detects project roots (build files, environments, linked worktrees) and refreshes
|
||||
/// index and watcher scopes when they changed.
|
||||
pub fn refresh_detected_roots(&self) {
|
||||
if self.light {
|
||||
return;
|
||||
}
|
||||
let fresh = ide_workspace::roots::detect(&self.root);
|
||||
if *self.detected_roots.read() == fresh {
|
||||
return;
|
||||
}
|
||||
*self.detected_roots.write() = fresh;
|
||||
self.refresh_index_scope();
|
||||
self.sink.emit(IdeEvent::ProjectRootsChanged { root: self.root.clone().into() });
|
||||
}
|
||||
|
||||
/// Applies changed content roots and exclude settings to the index (which
|
||||
/// rescans in the background) and the file watchers, without reopening the project.
|
||||
pub fn refresh_index_scope(&self) {
|
||||
@@ -2241,6 +2360,7 @@ fn root_globs(
|
||||
) -> Option<Vec<String>> {
|
||||
let own = members.get(dir)?;
|
||||
let mut globs = settings.file_excludes();
|
||||
globs.extend(agent_worktree_globs());
|
||||
globs.extend(own.iter().cloned());
|
||||
Some(globs)
|
||||
}
|
||||
@@ -2678,16 +2798,63 @@ fn with_gradle_roots(
|
||||
out
|
||||
}
|
||||
|
||||
/// Project-relative paths of explicitly attached workspace projects or content roots inside `root`.
|
||||
fn attached_in_root(root: &Path, settings: &ide_core::settings::Settings) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut push = |p: &Path| {
|
||||
if p != root
|
||||
&& let Ok(rel) = p.strip_prefix(root)
|
||||
{
|
||||
let rel = ide_workspace::roots::normalize(&rel.to_string_lossy());
|
||||
if !rel.is_empty() && !out.contains(&rel) {
|
||||
out.push(rel);
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Ok(Some(ws)) = ide_workspace::workspace::Workspace::load(root)
|
||||
&& !ws.is_container(root)
|
||||
{
|
||||
for p in &ws.projects {
|
||||
push(p);
|
||||
}
|
||||
}
|
||||
for raw in &settings.project_structure.content_roots {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let p = Path::new(trimmed);
|
||||
let abs = if p.is_absolute() { p.to_path_buf() } else { root.join(p) };
|
||||
push(&dunce::canonicalize(&abs).unwrap_or(abs));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn linked_roots(root: &Path, settings: &ide_core::settings::Settings, detected: &[SourceFolder]) -> ProjectRoots {
|
||||
let unlinked = ide_build::maven::UnlinkedProjects::load(root, &settings.languages.java.maven);
|
||||
let attached = attached_in_root(root, settings);
|
||||
let detected = detected
|
||||
.iter()
|
||||
.filter(|folder| !folder.detected_from.as_ref().is_some_and(|pom| unlinked.contains(pom)))
|
||||
.filter(|folder| {
|
||||
!(folder.is_detected_worktree()
|
||||
&& attached.iter().any(|a| {
|
||||
a == &folder.path || a.strip_prefix(&folder.path).is_some_and(|rest| rest.starts_with('/'))
|
||||
}))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
ProjectRoots::compute(detected, &settings.project_structure)
|
||||
}
|
||||
|
||||
/// Folders below a project or content root where agents put their git worktrees: copies of
|
||||
/// the project, excluded so search, indexing and navigation don't return them twice.
|
||||
const AGENT_WORKTREE_DIRS: &[&str] = &[".worktrees", ".claude/worktrees"];
|
||||
|
||||
fn agent_worktree_globs() -> impl Iterator<Item = String> {
|
||||
AGENT_WORKTREE_DIRS.iter().map(|dir| format!("/{dir}"))
|
||||
}
|
||||
|
||||
fn exclude_globs(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::Settings,
|
||||
@@ -2695,6 +2862,7 @@ fn exclude_globs(
|
||||
members: &BTreeMap<PathBuf, Vec<String>>,
|
||||
) -> Vec<String> {
|
||||
let mut globs = settings.file_excludes();
|
||||
globs.extend(agent_worktree_globs());
|
||||
globs.extend(linked_roots(root, settings, detected).excluded_globs());
|
||||
globs.extend(nested_member_globs(root, members));
|
||||
globs
|
||||
@@ -3605,6 +3773,14 @@ mod content_roots_tests {
|
||||
let own = root_globs(&settings, &members, &other).unwrap();
|
||||
assert!(own.contains(&"/gen".to_owned()) && !own.contains(&"/target".to_owned()));
|
||||
assert_eq!(root_globs(&settings, &members, &root), None, "the project folder has the project's");
|
||||
// Agent worktree folders are excluded in each project, at its root only.
|
||||
for globs in [&globs, &own] {
|
||||
let matcher = ide_vfs::ExcludeMatcher::new(globs);
|
||||
assert!(matcher.is_excluded(Path::new(".worktrees/topic/src/A.java")));
|
||||
assert!(matcher.is_excluded(Path::new(".claude/worktrees/topic")));
|
||||
assert!(!matcher.is_excluded(Path::new(".claude/settings.json")));
|
||||
assert!(!matcher.is_excluded(Path::new("src/.worktrees")));
|
||||
}
|
||||
|
||||
// A workspace folder's own excluded folders apply in every member, as before.
|
||||
let ws = base.join("ws");
|
||||
|
||||
@@ -396,6 +396,8 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
|
||||
| IdeEvent::ProjectRootsChanged { .. }
|
||||
| IdeEvent::Askpass { .. }
|
||||
| IdeEvent::AskpassDone { .. }
|
||||
| IdeEvent::FileApiConfirm { .. }
|
||||
| IdeEvent::FileApiConfirmDone { .. }
|
||||
| IdeEvent::NotebookKernel { .. } => true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,13 +228,18 @@ pub(crate) fn read_login_env(shell: &str, timeout: std::time::Duration) -> Optio
|
||||
Some(vars)
|
||||
}
|
||||
|
||||
/// Windows has no login shell to read: new children follow the registry environment's
|
||||
/// changes from here on instead (a program installed while the IDE runs).
|
||||
#[cfg(not(unix))]
|
||||
pub fn inherit_login_shell_path(_identifier: &str) -> Option<fn()> {
|
||||
ide_core::process::record_startup_registry_env();
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
pub fn inherit_login_shell_env(_identifier: &str) {}
|
||||
pub fn inherit_login_shell_env(_identifier: &str) {
|
||||
ide_core::process::record_startup_registry_env();
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
|
||||
@@ -40,11 +40,22 @@ pub(crate) fn context(sink: &SharedSink, prompts: bool) -> Arc<SvnContext> {
|
||||
/// the app's askpass like git's.
|
||||
pub(crate) fn settings(svn: &ide_core::workflow_settings::SvnSettings) -> Settings {
|
||||
let path = |s: &str| (!s.trim().is_empty()).then(|| PathBuf::from(s.trim()));
|
||||
let branch_configurations = svn
|
||||
.branch_configurations
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
(
|
||||
k.clone(),
|
||||
ide_svn::BranchConfig { trunk_url: v.trunk_url.clone(), branch_locations: v.branch_locations.clone() },
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Settings {
|
||||
executable: path(&svn.executable),
|
||||
interactive: svn.interactive,
|
||||
config_dir: if svn.use_custom_config_dir { path(&svn.config_dir) } else { None },
|
||||
env: ide_vcs::askpass_env(),
|
||||
branch_configurations,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,34 @@ pub struct TrustStore {
|
||||
struct RemoteDecisions {
|
||||
trusted: Vec<String>,
|
||||
restricted: Vec<String>,
|
||||
/// Folders trusted with everything under them (Trust Folder), per target.
|
||||
#[serde(default)]
|
||||
locations: Vec<RemoteLocation>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct RemoteLocation {
|
||||
target: String,
|
||||
folder: String,
|
||||
}
|
||||
|
||||
/// The key of a remote project's decisions: `[<target>,"<root>"]`, as `serde_json` writes the
|
||||
/// `(target, root)` tuple (the format of earlier versions). `target` is the target's JSON.
|
||||
pub fn remote_key(target: &str, root: &str) -> String {
|
||||
format!("[{target},{}]", serde_json::to_string(root).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The folder Trust Folder trusts for remote project `root`: its parent (`/`-separated).
|
||||
fn remote_parent(root: &str) -> Option<&str> {
|
||||
let root = root.trim_end_matches('/');
|
||||
let (parent, _) = root.rsplit_once('/')?;
|
||||
Some(if parent.is_empty() { "/" } else { parent })
|
||||
}
|
||||
|
||||
fn remote_under(root: &str, folder: &str) -> bool {
|
||||
let root = root.trim_end_matches('/');
|
||||
let folder = folder.trim_end_matches('/');
|
||||
root == folder || root.strip_prefix(folder).is_some_and(|rest| rest.starts_with('/'))
|
||||
}
|
||||
|
||||
/// Set by the desktop when it starts the server in a dev container of a folder the user trusts
|
||||
@@ -59,25 +87,52 @@ impl TrustStore {
|
||||
Self { file, state: Mutex::new(state), inherited: Mutex::default(), remote_file, remote: Mutex::new(remote) }
|
||||
}
|
||||
|
||||
/// The decision made on this machine for the remote project at `location` (`None`: none yet).
|
||||
/// Commands a remote window runs here follow it, not the server's own trust.
|
||||
pub fn remote_decision(&self, location: &str) -> IdeResult<Option<bool>> {
|
||||
/// The decision made on this machine for the remote project `root` of `target` (the
|
||||
/// target's JSON; `None`: none yet). Commands a remote window runs here follow it, not the
|
||||
/// server's own trust. A project under a trusted folder of the same target is trusted.
|
||||
pub fn remote_decision(&self, target: &str, root: &str) -> IdeResult<Option<bool>> {
|
||||
let remote = self.remote.lock().clone()?;
|
||||
Ok(if remote.restricted.iter().any(|l| l == location) {
|
||||
let location = remote_key(target, root);
|
||||
Ok(if remote.restricted.contains(&location) {
|
||||
Some(false)
|
||||
} else if remote.trusted.iter().any(|l| l == location) {
|
||||
} else if remote.trusted.contains(&location)
|
||||
|| remote.locations.iter().any(|l| l.target == target && remote_under(root, &l.folder))
|
||||
{
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
pub fn decide_remote(&self, location: &str, trusted: bool) -> IdeResult<()> {
|
||||
/// Records the decision for remote project `root` of `target`; `folder` also trusts its
|
||||
/// parent folder (Trust Folder).
|
||||
pub fn decide_remote(&self, target: &str, root: &str, trusted: bool, folder: bool) -> IdeResult<()> {
|
||||
let location = remote_key(target, root);
|
||||
let mut state = self.remote.lock();
|
||||
let mut next = state.clone()?;
|
||||
next.trusted.retain(|l| l != location);
|
||||
next.restricted.retain(|l| l != location);
|
||||
if trusted { &mut next.trusted } else { &mut next.restricted }.push(location.to_owned());
|
||||
next.trusted.retain(|l| *l != location);
|
||||
next.restricted.retain(|l| *l != location);
|
||||
if trusted { &mut next.trusted } else { &mut next.restricted }.push(location);
|
||||
if trusted
|
||||
&& folder
|
||||
&& let Some(parent) = remote_parent(root)
|
||||
{
|
||||
let parent = RemoteLocation { target: target.to_owned(), folder: parent.to_owned() };
|
||||
if !next.locations.contains(&parent) {
|
||||
next.locations.push(parent);
|
||||
}
|
||||
}
|
||||
persist(&self.remote_file, &next)?;
|
||||
*state = Ok(next);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Forgets trusted folder `folder` of `target` (Remove Trusted Location in a remote window).
|
||||
pub fn remove_remote_location(&self, target: &str, folder: &str) -> IdeResult<()> {
|
||||
let mut state = self.remote.lock();
|
||||
let mut next = state.clone()?;
|
||||
let folder = folder.trim_end_matches('/');
|
||||
next.locations.retain(|l| l.target != target || l.folder.trim_end_matches('/') != folder);
|
||||
persist(&self.remote_file, &next)?;
|
||||
*state = Ok(next);
|
||||
Ok(())
|
||||
@@ -439,12 +494,35 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let load = || super::TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
|
||||
let store = load();
|
||||
let here = r#"[{"kind":"ssh","config":"box"},"/srv/app"]"#;
|
||||
assert_eq!(store.remote_decision(here).unwrap(), None);
|
||||
store.decide_remote(here, true).unwrap();
|
||||
assert_eq!(store.remote_decision(here).unwrap(), Some(true));
|
||||
assert_eq!(store.remote_decision(r#"[{"kind":"ssh","config":"box"},"/srv/other"]"#).unwrap(), None);
|
||||
store.decide_remote(here, false).unwrap();
|
||||
assert_eq!(load().remote_decision(here).unwrap(), Some(false));
|
||||
let target = r#"{"kind":"ssh","config":"box"}"#;
|
||||
assert_eq!(store.remote_decision(target, "/srv/app").unwrap(), None);
|
||||
store.decide_remote(target, "/srv/app", true, false).unwrap();
|
||||
assert_eq!(store.remote_decision(target, "/srv/app").unwrap(), Some(true));
|
||||
assert_eq!(store.remote_decision(target, "/srv/other").unwrap(), None);
|
||||
store.decide_remote(target, "/srv/app", false, false).unwrap();
|
||||
assert_eq!(load().remote_decision(target, "/srv/app").unwrap(), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusting_a_remote_folder_trusts_the_projects_under_it_on_that_target() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let load = || super::TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
|
||||
let store = load();
|
||||
let target = r#"{"kind":"ssh","config":"box"}"#;
|
||||
let other = r#"{"kind":"ssh","config":"other"}"#;
|
||||
store.decide_remote(target, "/srv/work/app", true, true).unwrap();
|
||||
let store = load();
|
||||
assert_eq!(store.remote_decision(target, "/srv/work/api").unwrap(), Some(true));
|
||||
assert_eq!(store.remote_decision(target, "/srv/work/a/b").unwrap(), Some(true));
|
||||
assert_eq!(store.remote_decision(target, "/srv/workshop").unwrap(), None);
|
||||
assert_eq!(store.remote_decision(other, "/srv/work/api").unwrap(), None);
|
||||
// An explicit Don't Trust of a project under it still wins.
|
||||
store.decide_remote(target, "/srv/work/api", false, false).unwrap();
|
||||
assert_eq!(store.remote_decision(target, "/srv/work/api").unwrap(), Some(false));
|
||||
store.remove_remote_location(target, "/srv/work/").unwrap();
|
||||
assert_eq!(load().remote_decision(target, "/srv/work/lib").unwrap(), None);
|
||||
assert_eq!(load().remote_decision(target, "/srv/work/app").unwrap(), Some(true));
|
||||
store.decide_remote(target, "/app", true, true).unwrap();
|
||||
assert_eq!(store.remote_decision(target, "/anything").unwrap(), Some(true));
|
||||
}
|
||||
}
|
||||
@@ -34,11 +34,77 @@ import path from "node:path";
|
||||
import readline from "node:readline";
|
||||
|
||||
let cwd = process.cwd();
|
||||
let currentModel = "mock-fast";
|
||||
let currentEffort = "medium";
|
||||
let currentContextTier = null;
|
||||
let currentMode = "bypassPermissions";
|
||||
let lastMcpServers = [];
|
||||
let nextReqId = 100;
|
||||
const pending = new Map();
|
||||
|
||||
function buildConfigOptions() {
|
||||
const opts = [
|
||||
{
|
||||
id: "model",
|
||||
category: "model",
|
||||
name: "Model",
|
||||
type: "select",
|
||||
currentValue: currentModel,
|
||||
options: [
|
||||
{ value: "mock-fast", name: "Mock Fast" },
|
||||
{ value: "mock-pro", name: "Mock Pro" }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: "mode",
|
||||
category: "mode",
|
||||
name: "Mode",
|
||||
type: "select",
|
||||
currentValue: currentMode,
|
||||
defaultValue: "default",
|
||||
options: [
|
||||
{ value: "default", name: "Default" },
|
||||
{ value: "acceptEdits", name: "Accept Edits" },
|
||||
{ value: "bypassPermissions", name: "Bypass Permissions" }
|
||||
]
|
||||
}
|
||||
];
|
||||
const efforts = currentModel === "mock-pro"
|
||||
? [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
{ value: "xhigh", name: "Extra High" }
|
||||
]
|
||||
: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" }
|
||||
];
|
||||
opts.push({
|
||||
id: "reasoning_effort",
|
||||
category: "thought_level",
|
||||
name: "Reasoning Effort",
|
||||
type: "select",
|
||||
currentValue: currentEffort,
|
||||
options: efforts
|
||||
});
|
||||
if (currentModel === "mock-pro") {
|
||||
opts.push({
|
||||
id: "context_tier",
|
||||
category: "model_config",
|
||||
name: "Context Size",
|
||||
type: "select",
|
||||
currentValue: currentContextTier || "default",
|
||||
options: [
|
||||
{ value: "default", name: "200K" },
|
||||
{ value: "long_context", name: "1M" }
|
||||
]
|
||||
});
|
||||
}
|
||||
return opts;
|
||||
}
|
||||
|
||||
function callBuiltinMcp(server, toolCalls) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const childEnv = { ...process.env };
|
||||
@@ -136,29 +202,7 @@ rl.on("line", (line) => {
|
||||
id,
|
||||
result: {
|
||||
sessionId: "sess-mock-1",
|
||||
configOptions: [
|
||||
{
|
||||
id: "model",
|
||||
category: "model",
|
||||
name: "Model",
|
||||
type: "select",
|
||||
currentValue: "mock-fast",
|
||||
options: [{ value: "mock-fast", name: "Mock Fast" }]
|
||||
},
|
||||
{
|
||||
id: "mode",
|
||||
category: "mode",
|
||||
name: "Mode",
|
||||
type: "select",
|
||||
currentValue: currentMode,
|
||||
defaultValue: "default",
|
||||
options: [
|
||||
{ value: "default", name: "Default" },
|
||||
{ value: "acceptEdits", name: "Accept Edits" },
|
||||
{ value: "bypassPermissions", name: "Bypass Permissions" }
|
||||
]
|
||||
}
|
||||
]
|
||||
configOptions: buildConfigOptions()
|
||||
}
|
||||
});
|
||||
} else if (method === "session/load") {
|
||||
@@ -168,29 +212,7 @@ rl.on("line", (line) => {
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
configOptions: [
|
||||
{
|
||||
id: "model",
|
||||
category: "model",
|
||||
name: "Model",
|
||||
type: "select",
|
||||
currentValue: "mock-fast",
|
||||
options: [{ value: "mock-fast", name: "Mock Fast" }]
|
||||
},
|
||||
{
|
||||
id: "mode",
|
||||
category: "mode",
|
||||
name: "Mode",
|
||||
type: "select",
|
||||
currentValue: currentMode,
|
||||
defaultValue: "default",
|
||||
options: [
|
||||
{ value: "default", name: "Default" },
|
||||
{ value: "acceptEdits", name: "Accept Edits" },
|
||||
{ value: "bypassPermissions", name: "Bypass Permissions" }
|
||||
]
|
||||
}
|
||||
]
|
||||
configOptions: buildConfigOptions()
|
||||
}
|
||||
});
|
||||
} else if (method === "session/set_config_option") {
|
||||
@@ -204,34 +226,33 @@ rl.on("line", (line) => {
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result: {
|
||||
configOptions: [
|
||||
{
|
||||
id: "model",
|
||||
category: "model",
|
||||
name: "Model",
|
||||
type: "select",
|
||||
currentValue: "mock-fast",
|
||||
options: [{ value: "mock-fast", name: "Mock Fast" }]
|
||||
},
|
||||
{
|
||||
id: "mode",
|
||||
category: "mode",
|
||||
name: "Mode",
|
||||
type: "select",
|
||||
currentValue: currentMode,
|
||||
defaultValue: "default",
|
||||
options: [
|
||||
{ value: "default", name: "Default" },
|
||||
{ value: "acceptEdits", name: "Accept Edits" },
|
||||
{ value: "bypassPermissions", name: "Bypass Permissions" }
|
||||
]
|
||||
}
|
||||
]
|
||||
configOptions: buildConfigOptions()
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (params?.configId === "mode" && params?.value) currentMode = params.value;
|
||||
if (params?.configId === "model" && params?.value) {
|
||||
currentModel = params.value;
|
||||
if (currentModel === "mock-pro") {
|
||||
currentContextTier = "default";
|
||||
} else {
|
||||
currentContextTier = null;
|
||||
if (currentEffort === "xhigh") currentEffort = "medium";
|
||||
}
|
||||
send({ jsonrpc: "2.0", id, result: { configOptions: buildConfigOptions() } });
|
||||
return;
|
||||
}
|
||||
if (params?.configId === "reasoning_effort" && params?.value) {
|
||||
currentEffort = params.value;
|
||||
send({ jsonrpc: "2.0", id, result: { configOptions: buildConfigOptions() } });
|
||||
return;
|
||||
}
|
||||
if (params?.configId === "context_tier" && params?.value && currentModel === "mock-pro") {
|
||||
currentContextTier = params.value;
|
||||
send({ jsonrpc: "2.0", id, result: { configOptions: buildConfigOptions() } });
|
||||
return;
|
||||
}
|
||||
send({ jsonrpc: "2.0", id, result: {} });
|
||||
} else if (method === "session/set_mode") {
|
||||
if (process.env.MOCK_ERROR_DOWNGRADE === "1" || process.env.MOCK_REJECT_DOWNGRADE === "1") {
|
||||
@@ -377,6 +398,26 @@ rl.on("line", (line) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (text.includes("report-config")) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
messageId: "m-cfg-" + Date.now(),
|
||||
content: {
|
||||
type: "text",
|
||||
text: `CONFIG=model:${currentModel} effort:${currentEffort} context:${currentContextTier ?? "none"} mode:${currentMode}`
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
send({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } });
|
||||
return;
|
||||
}
|
||||
|
||||
if (text.includes("report-mode-cwd")) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
@@ -485,6 +526,7 @@ fn setup_host_and_repo(base: &Path) -> (Arc<Host>, PathBuf) {
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp".into(),
|
||||
name: "Mock ACP".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: Default::default(),
|
||||
@@ -2030,6 +2072,7 @@ async fn ceiling_rejection_persist_rollback_cross_owner_auth_queued_trust_and_wo
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp-stubborn".into(),
|
||||
name: "Mock ACP Stubborn".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: std::collections::BTreeMap::from([("MOCK_REJECT_DOWNGRADE".to_owned(), "1".to_owned())]),
|
||||
@@ -2040,6 +2083,7 @@ async fn ceiling_rejection_persist_rollback_cross_owner_auth_queued_trust_and_wo
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp-err".into(),
|
||||
name: "Mock ACP Error".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: std::collections::BTreeMap::from([("MOCK_ERROR_DOWNGRADE".to_owned(), "1".to_owned())]),
|
||||
@@ -2570,6 +2614,7 @@ async fn scheduled_runs_cannot_recursively_mutate_automations_via_mcp_stdio_whil
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp".into(),
|
||||
name: "Mock ACP".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: std::collections::BTreeMap::from([(
|
||||
@@ -3044,6 +3089,7 @@ async fn oneshot_self_chaining_and_override_preservation_on_edit() {
|
||||
.save_custom_agent(CustomAgentInput {
|
||||
id: "mock-acp-mcp".into(),
|
||||
name: "Mock ACP MCP".into(),
|
||||
base: None,
|
||||
command: "node".into(),
|
||||
args: vec![script_path.to_string_lossy().into_owned()],
|
||||
env: std::collections::BTreeMap::from([(
|
||||
@@ -3326,3 +3372,496 @@ async fn oneshot_self_chaining_and_override_preservation_on_edit() {
|
||||
host.mcp.stop(&host);
|
||||
host.automations.stop();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn local_host_keep_alive_respects_keep_alive_setting_without_auto_start_service() {
|
||||
struct HostGuard(Arc<Host>);
|
||||
impl Drop for HostGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.automations.stop();
|
||||
self.0.close_project("main");
|
||||
}
|
||||
}
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap_or_else(|_| tmp.path().to_path_buf());
|
||||
let (host, root) = setup_host_and_repo(&base);
|
||||
let _guard = HostGuard(host.clone());
|
||||
|
||||
let defaults = host.global_settings.effective().agents.automations;
|
||||
assert!(!defaults.auto_start_service, "autoStartService must default to false");
|
||||
assert!(defaults.keep_alive_in_background, "keepAliveInBackground must default to true");
|
||||
|
||||
// 1. No schedules and no running runs -> do not keep local host alive.
|
||||
assert!(!host.automations.keeps_local_host_alive(&host));
|
||||
|
||||
// 2. Enabled recurring schedule with default settings (`autoStartService = false`,
|
||||
// `keepAliveInBackground = true`) MUST keep the local host alive.
|
||||
let hourly = agent_automation_save(
|
||||
&host,
|
||||
"main",
|
||||
SaveAutomationInput {
|
||||
id: None,
|
||||
name: "Local Background Hourly".into(),
|
||||
enabled: true,
|
||||
prompt: AgentPrompt { text: "clean-run".into(), files: vec![], images: vec![] },
|
||||
workspace: AutomationWorkspace::Project {
|
||||
root: IpcPath(root.clone()),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
auto_clean_worktree: true,
|
||||
},
|
||||
continuity: AutomationContinuity::NewTask,
|
||||
provider: "mock-acp".into(),
|
||||
config: vec![],
|
||||
permissions: AutomationPermissionMode::AllowAll,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: AutomationTrigger::Hourly { minute: 0, time_zone: "UTC".into() },
|
||||
allow_agent_schedule: false,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: None,
|
||||
max_runs: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
host.automations.keeps_local_host_alive(&host),
|
||||
"enabled local schedule must keep host alive when keepAliveInBackground = true even if autoStartService = false"
|
||||
);
|
||||
|
||||
// Turning `keepAliveInBackground` off disables keep-alive even if `autoStartService` is on.
|
||||
host.global_settings
|
||||
.set(SettingsScope::Global, "agents.automations.keepAliveInBackground", serde_json::json!(false))
|
||||
.unwrap();
|
||||
assert!(!host.automations.keeps_local_host_alive(&host));
|
||||
host.global_settings
|
||||
.set(SettingsScope::Global, "agents.automations.autoStartService", serde_json::json!(true))
|
||||
.unwrap();
|
||||
assert!(
|
||||
!host.automations.keeps_local_host_alive(&host),
|
||||
"keepAliveInBackground = false must not keep local host alive even when autoStartService = true"
|
||||
);
|
||||
|
||||
// Turning `keepAliveInBackground` back on with `autoStartService = true` re-enables keep-alive.
|
||||
host.global_settings
|
||||
.set(SettingsScope::Global, "agents.automations.keepAliveInBackground", serde_json::json!(true))
|
||||
.unwrap();
|
||||
assert!(host.automations.keeps_local_host_alive(&host));
|
||||
|
||||
// Restore default `autoStartService = false` and pause all schedules -> returns false.
|
||||
host.global_settings
|
||||
.set(SettingsScope::Global, "agents.automations.autoStartService", serde_json::json!(false))
|
||||
.unwrap();
|
||||
agent_automation_set_enabled(&host, "main", hourly.id.clone(), false).await.unwrap();
|
||||
assert!(!host.automations.keeps_local_host_alive(&host));
|
||||
|
||||
// 3. Unpaused in-session schedule (`SendLater`) keeps local host alive under default settings.
|
||||
let t0: u64 = 1_796_400_000_000;
|
||||
host.automations.set_clock_override_ms(t0);
|
||||
let task = host
|
||||
.project("main")
|
||||
.unwrap()
|
||||
.agents
|
||||
.create(ide_agent::NewAgentTask {
|
||||
provider: "mock-acp".into(),
|
||||
prompt: AgentPrompt { text: "seed task".into(), files: vec![], images: vec![] },
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
project_root: Some(IpcPath(root.clone())),
|
||||
config: vec![],
|
||||
idle: false,
|
||||
ephemeral: false,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_until("seed task finished", || {
|
||||
host.project("main")
|
||||
.unwrap()
|
||||
.agents
|
||||
.task_snapshot(&task.id)
|
||||
.is_some_and(|t| t.status == ide_agent::AgentStatus::Ready)
|
||||
})
|
||||
.await;
|
||||
let sess = agent_session_schedule_create(
|
||||
&host,
|
||||
"main",
|
||||
CreateSessionScheduleInput {
|
||||
task_id: task.id.clone(),
|
||||
prompt: AgentPrompt { text: "later ping".into(), files: vec![], images: vec![] },
|
||||
kind: SessionScheduleKind::SendLater { run_at_ms: (t0 + 600_000) as f64 },
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(host.automations.keeps_local_host_alive(&host));
|
||||
agent_session_schedule_delete(&host, "main", sess.id.clone()).await.unwrap();
|
||||
assert!(!host.automations.keeps_local_host_alive(&host));
|
||||
|
||||
// 4. In-flight Manual run (`has_enabled_schedules() == false`, `has_running_runs() == true`)
|
||||
// MUST keep local host alive and survive window close when `keepAliveInBackground = true`.
|
||||
let manual = agent_automation_save(
|
||||
&host,
|
||||
"main",
|
||||
SaveAutomationInput {
|
||||
id: None,
|
||||
name: "Manual Run Keep Alive".into(),
|
||||
enabled: false,
|
||||
prompt: AgentPrompt { text: "ask-permission".into(), files: vec![], images: vec![] },
|
||||
workspace: AutomationWorkspace::Project {
|
||||
root: IpcPath(root.clone()),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
auto_clean_worktree: true,
|
||||
},
|
||||
continuity: AutomationContinuity::NewTask,
|
||||
provider: "mock-acp".into(),
|
||||
config: vec![],
|
||||
permissions: AutomationPermissionMode::Default,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: AutomationTrigger::Manual,
|
||||
allow_agent_schedule: false,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: None,
|
||||
max_runs: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let run = agent_automation_run_now(&host, "main", manual.id.clone()).await.unwrap();
|
||||
wait_until("manual run entered NeedsInput", || {
|
||||
host.automations.get_run(&run.id).is_some_and(|r| r.status == AutomationRunStatus::NeedsInput)
|
||||
})
|
||||
.await;
|
||||
assert!(!host.automations.has_enabled_schedules(), "Manual trigger without override is not scheduled");
|
||||
assert!(host.automations.has_running_runs(), "NeedsInput run counts as an active run");
|
||||
assert!(
|
||||
host.automations.keeps_local_host_alive(&host),
|
||||
"in-flight Manual run must keep local host alive when keepAliveInBackground = true"
|
||||
);
|
||||
|
||||
// Closing the project window retains the AgentManager headlessly and keeps the local host alive.
|
||||
let task_id = host.automations.get_run(&run.id).unwrap().task_id.unwrap();
|
||||
host.close_project("main");
|
||||
assert!(host.projects().is_empty());
|
||||
assert!(host.automations.keeps_local_host_alive(&host));
|
||||
|
||||
// Turning `keepAliveInBackground` off stops keeping the host alive even during a running run.
|
||||
host.global_settings
|
||||
.set(SettingsScope::Global, "agents.automations.keepAliveInBackground", serde_json::json!(false))
|
||||
.unwrap();
|
||||
assert!(!host.automations.keeps_local_host_alive(&host));
|
||||
host.global_settings
|
||||
.set(SettingsScope::Global, "agents.automations.keepAliveInBackground", serde_json::json!(true))
|
||||
.unwrap();
|
||||
|
||||
// Reopen the window, approve the pending permission, and verify keep-alive clears once finished.
|
||||
host.open_project("main", &root).unwrap();
|
||||
let req_id = host
|
||||
.project("main")
|
||||
.unwrap()
|
||||
.agents
|
||||
.entries(&task_id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find_map(|e| match e {
|
||||
ide_agent::AgentEntry::Permission { id, chosen: None, .. } => Some(id),
|
||||
_ => None,
|
||||
})
|
||||
.expect("retained headless AgentManager must preserve pending permission after window reopen");
|
||||
agent_respond(&host, "main", task_id, req_id, Some("allow".into())).unwrap();
|
||||
wait_until("manual run completed after approval", || {
|
||||
host.automations.get_run(&run.id).is_some_and(|r| r.status == AutomationRunStatus::Completed)
|
||||
&& host.automations.in_flight_claim_counts() == (0, 0)
|
||||
})
|
||||
.await;
|
||||
assert!(!host.automations.keeps_local_host_alive(&host));
|
||||
|
||||
// 5. OneShot that just fired (disabling its schedule while the run is still in progress)
|
||||
// MUST still keep the local host alive until the run finishes.
|
||||
let oneshot_due = t0 + 120_000;
|
||||
let oneshot = agent_automation_save(
|
||||
&host,
|
||||
"main",
|
||||
SaveAutomationInput {
|
||||
id: None,
|
||||
name: "OneShot In-Flight Keep Alive".into(),
|
||||
enabled: true,
|
||||
prompt: AgentPrompt { text: "ask-permission".into(), files: vec![], images: vec![] },
|
||||
workspace: AutomationWorkspace::Project {
|
||||
root: IpcPath(root.clone()),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
auto_clean_worktree: true,
|
||||
},
|
||||
continuity: AutomationContinuity::NewTask,
|
||||
provider: "mock-acp".into(),
|
||||
config: vec![],
|
||||
permissions: AutomationPermissionMode::Default,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: AutomationTrigger::OneShot { run_at_ms: oneshot_due as f64 },
|
||||
allow_agent_schedule: false,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: None,
|
||||
max_runs: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(host.automations.keeps_local_host_alive(&host));
|
||||
host.automations.set_clock_override_ms(oneshot_due + 1_000);
|
||||
host.automations.clone().tick_once(&host).await;
|
||||
wait_until("oneshot run entered NeedsInput after schedule disabled", || {
|
||||
host.automations
|
||||
.runs(Some(&root), Some(&oneshot.id), None, None)
|
||||
.runs
|
||||
.first()
|
||||
.is_some_and(|r| r.status == AutomationRunStatus::NeedsInput)
|
||||
})
|
||||
.await;
|
||||
assert!(!host.automations.has_enabled_schedules(), "fired OneShot without self-chaining is no longer scheduled");
|
||||
assert!(
|
||||
host.automations.keeps_local_host_alive(&host),
|
||||
"in-flight OneShot run must still keep local host alive until completion"
|
||||
);
|
||||
let oneshot_run = host.automations.runs(Some(&root), Some(&oneshot.id), None, None).runs[0].clone();
|
||||
let oneshot_task_id = oneshot_run.task_id.unwrap();
|
||||
let oneshot_req_id = host
|
||||
.project("main")
|
||||
.unwrap()
|
||||
.agents
|
||||
.entries(&oneshot_task_id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find_map(|e| match e {
|
||||
ide_agent::AgentEntry::Permission { id, chosen: None, .. } => Some(id),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
agent_respond(&host, "main", oneshot_task_id, oneshot_req_id, Some("allow".into())).unwrap();
|
||||
wait_until("oneshot run completed", || {
|
||||
host.automations.get_run(&oneshot_run.id).is_some_and(|r| r.status == AutomationRunStatus::Completed)
|
||||
&& host.automations.in_flight_claim_counts() == (0, 0)
|
||||
})
|
||||
.await;
|
||||
assert!(!host.automations.keeps_local_host_alive(&host));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn automation_applies_model_effort_and_context_tier_on_new_and_live_same_task() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (host, repo) = setup_host_and_repo(dir.path());
|
||||
host.global_settings.set(SettingsScope::Global, "agents.newTaskApprovals", serde_json::json!("ask")).unwrap();
|
||||
|
||||
// 1. NewTask automation applies model BEFORE per-model effort & context_tier even when ordered after them.
|
||||
let new_task_auto = agent_automation_save(
|
||||
&host,
|
||||
"main",
|
||||
SaveAutomationInput {
|
||||
id: None,
|
||||
name: "NewTask Model Effort Context".into(),
|
||||
enabled: false,
|
||||
prompt: AgentPrompt { text: "report-config".into(), files: vec![], images: vec![] },
|
||||
workspace: AutomationWorkspace::Project {
|
||||
root: IpcPath(repo.clone()),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
auto_clean_worktree: false,
|
||||
},
|
||||
continuity: AutomationContinuity::NewTask,
|
||||
provider: "mock-acp".into(),
|
||||
config: vec![
|
||||
ide_agent::AgentConfigChoice { id: "context_tier".into(), value: "long_context".into() },
|
||||
ide_agent::AgentConfigChoice { id: "reasoning_effort".into(), value: "xhigh".into() },
|
||||
ide_agent::AgentConfigChoice { id: "model".into(), value: "mock-pro".into() },
|
||||
],
|
||||
permissions: AutomationPermissionMode::AllowAll,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: AutomationTrigger::Manual,
|
||||
allow_agent_schedule: false,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: None,
|
||||
max_runs: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let run1 = agent_automation_run_now(&host, "main", new_task_auto.id.clone()).await.unwrap();
|
||||
wait_until("NewTask config run completes", || {
|
||||
host.automations.get_run(&run1.id).is_some_and(|r| r.status == AutomationRunStatus::Completed)
|
||||
})
|
||||
.await;
|
||||
let new_tid = host.automations.get_run(&run1.id).unwrap().task_id.unwrap();
|
||||
let new_entries = agent_entries(&host, "main", new_tid, None).await.unwrap();
|
||||
let new_texts: Vec<String> = new_entries
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
ide_agent::AgentEntry::Agent { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
new_texts.iter().any(|t| t.contains("CONFIG=model:mock-pro effort:xhigh context:long_context mode:default")),
|
||||
"NewTask automation must apply model, effort, and context_tier while respecting Ask ceiling: {new_texts:?}"
|
||||
);
|
||||
|
||||
// 2. SameTask rolling session: run 1 starts on mock-fast/low, then editing the automation to
|
||||
// mock-pro/xhigh/long_context (+ attempted bypass) updates the LIVE session on run 2 while
|
||||
// still enforcing the Ask approval ceiling!
|
||||
let rolling = agent_automation_save(
|
||||
&host,
|
||||
"main",
|
||||
SaveAutomationInput {
|
||||
id: None,
|
||||
name: "SameTask Live Config Update".into(),
|
||||
enabled: false,
|
||||
prompt: AgentPrompt { text: "report-config".into(), files: vec![], images: vec![] },
|
||||
workspace: AutomationWorkspace::Project {
|
||||
root: IpcPath(repo.clone()),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
auto_clean_worktree: false,
|
||||
},
|
||||
continuity: AutomationContinuity::SameTask,
|
||||
provider: "mock-acp".into(),
|
||||
config: vec![
|
||||
ide_agent::AgentConfigChoice { id: "model".into(), value: "mock-fast".into() },
|
||||
ide_agent::AgentConfigChoice { id: "reasoning_effort".into(), value: "low".into() },
|
||||
],
|
||||
permissions: AutomationPermissionMode::AllowAll,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: AutomationTrigger::Manual,
|
||||
allow_agent_schedule: false,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: None,
|
||||
max_runs: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let s1 = agent_automation_run_now(&host, "main", rolling.id.clone()).await.unwrap();
|
||||
wait_until("SameTask run 1 finishes", || {
|
||||
host.automations.get_run(&s1.id).is_some_and(|r| r.status == AutomationRunStatus::Completed)
|
||||
})
|
||||
.await;
|
||||
let rolling_tid = host.automations.get_run(&s1.id).unwrap().task_id.unwrap();
|
||||
|
||||
// Update the automation's model, effort, and context_tier while the SameTask session is live.
|
||||
agent_automation_save(
|
||||
&host,
|
||||
"main",
|
||||
SaveAutomationInput {
|
||||
id: Some(rolling.id.clone()),
|
||||
name: rolling.name.clone(),
|
||||
enabled: false,
|
||||
prompt: rolling.prompt.clone(),
|
||||
workspace: rolling.workspace.clone(),
|
||||
continuity: AutomationContinuity::SameTask,
|
||||
provider: "mock-acp".into(),
|
||||
config: vec![
|
||||
ide_agent::AgentConfigChoice { id: "context_tier".into(), value: "long_context".into() },
|
||||
ide_agent::AgentConfigChoice { id: "reasoning_effort".into(), value: "xhigh".into() },
|
||||
ide_agent::AgentConfigChoice { id: "model".into(), value: "mock-pro".into() },
|
||||
ide_agent::AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() },
|
||||
],
|
||||
permissions: AutomationPermissionMode::AllowAll,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: AutomationTrigger::Manual,
|
||||
allow_agent_schedule: false,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: None,
|
||||
max_runs: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let s2 = agent_automation_run_now(&host, "main", rolling.id.clone()).await.unwrap();
|
||||
wait_until("SameTask run 2 finishes", || {
|
||||
host.automations.get_run(&s2.id).is_some_and(|r| r.status == AutomationRunStatus::Completed)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(host.automations.get_run(&s2.id).unwrap().task_id.as_deref(), Some(rolling_tid.as_str()));
|
||||
|
||||
// Edit again to adjust effort & context_tier down on the same live model.
|
||||
agent_automation_save(
|
||||
&host,
|
||||
"main",
|
||||
SaveAutomationInput {
|
||||
id: Some(rolling.id.clone()),
|
||||
name: rolling.name.clone(),
|
||||
enabled: false,
|
||||
prompt: rolling.prompt.clone(),
|
||||
workspace: rolling.workspace.clone(),
|
||||
continuity: AutomationContinuity::SameTask,
|
||||
provider: "mock-acp".into(),
|
||||
config: vec![
|
||||
ide_agent::AgentConfigChoice { id: "model".into(), value: "mock-pro".into() },
|
||||
ide_agent::AgentConfigChoice { id: "reasoning_effort".into(), value: "medium".into() },
|
||||
ide_agent::AgentConfigChoice { id: "context_tier".into(), value: "default".into() },
|
||||
],
|
||||
permissions: AutomationPermissionMode::AllowAll,
|
||||
mcp_overrides: Default::default(),
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: AutomationTrigger::Manual,
|
||||
allow_agent_schedule: false,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: None,
|
||||
max_runs: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let s3 = agent_automation_run_now(&host, "main", rolling.id.clone()).await.unwrap();
|
||||
wait_until("SameTask run 3 finishes", || {
|
||||
host.automations.get_run(&s3.id).is_some_and(|r| r.status == AutomationRunStatus::Completed)
|
||||
})
|
||||
.await;
|
||||
assert_eq!(host.automations.get_run(&s3.id).unwrap().task_id.as_deref(), Some(rolling_tid.as_str()));
|
||||
|
||||
let rolling_entries = agent_entries(&host, "main", rolling_tid, None).await.unwrap();
|
||||
let rolling_texts: Vec<String> = rolling_entries
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
ide_agent::AgentEntry::Agent { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
rolling_texts,
|
||||
vec![
|
||||
"CONFIG=model:mock-fast effort:low context:none mode:default",
|
||||
"CONFIG=model:mock-pro effort:xhigh context:long_context mode:default",
|
||||
"CONFIG=model:mock-pro effort:medium context:default mode:default",
|
||||
],
|
||||
"SameTask live session must apply updated model, effort, and context_tier on each run while holding Ask ceiling"
|
||||
);
|
||||
|
||||
host.automations.stop();
|
||||
}
|
||||
@@ -40,6 +40,7 @@ async fn agent_environment_values_stay_out_of_agent_files() {
|
||||
ide_agent::CustomAgentInput {
|
||||
id: "mine".into(),
|
||||
name: "Mine".into(),
|
||||
base: None,
|
||||
command: "/opt/mine".into(),
|
||||
args: vec![],
|
||||
env: env.clone(),
|
||||
|
||||
@@ -422,3 +422,156 @@ async fn schema_reads_user_tables_without_rows_or_credentials_and_enforces_grant
|
||||
assert!(db.connected_table_details("user-source", None, "main", "users").await.is_err());
|
||||
assert!(!db.is_connected("user-source"), "schema reads cannot reconnect a disconnected source");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn schema_discovery_and_query_execution_enforce_grants_trust_and_connection_isolation() {
|
||||
let f = Harness::with_timeout(Duration::from_secs(10));
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
let db = f.host.project("main").unwrap().db.clone();
|
||||
db.save_sources(vec![ide_db::DataSource {
|
||||
id: "user-source".into(),
|
||||
name: "User SQLite".into(),
|
||||
driver: ide_db::DbDriver::Sqlite,
|
||||
file: Some(f.root.join("db.sqlite").into()),
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Disconnected sources are never listed or queried implicitly.
|
||||
let initial_sources: Vec<serde_json::Value> =
|
||||
serde_json::from_str(&f.run("connected-sources", None).unwrap().unwrap()).unwrap();
|
||||
assert!(initial_sources.is_empty());
|
||||
assert!(f.run("list-schemas", Some("user-source")).is_err());
|
||||
assert!(!db.is_connected("user-source"));
|
||||
let q_req = serde_json::json!({
|
||||
"sourceId": "user-source",
|
||||
"sql": "SELECT id, name FROM users ORDER BY id",
|
||||
"maxRows": 1
|
||||
})
|
||||
.to_string();
|
||||
assert!(f.run("execute-query", Some(&q_req)).is_err(), "query execution never connects implicitly");
|
||||
assert!(!db.is_connected("user-source"));
|
||||
|
||||
let cancel = CancellationToken::new();
|
||||
for sql in [
|
||||
"CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT NOT NULL)",
|
||||
"INSERT INTO users(name) VALUES ('alice'), ('bob')",
|
||||
] {
|
||||
db.execute("user-source", sql, 100, &cancel).await.unwrap();
|
||||
}
|
||||
|
||||
// Window isolation: second window has no connection of its own for discovery or queries.
|
||||
let second_inv = Invocation { client: Some("second".into()), ..f.invocation() };
|
||||
let second_sources: Vec<serde_json::Value> = serde_json::from_str(
|
||||
&f.plugins.run_command(ID, "connected-sources", None, second_inv.clone()).unwrap().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(second_sources.is_empty(), "a disconnected window cannot see another window's connections");
|
||||
assert!(f.plugins.run_command(ID, "list-schemas", Some("user-source"), second_inv.clone()).is_err());
|
||||
assert!(
|
||||
f.plugins
|
||||
.run_command(ID, "list-tables", Some(r#"{"sourceId":"user-source","schema":"main"}"#), second_inv.clone())
|
||||
.is_err()
|
||||
);
|
||||
assert!(f.plugins.run_command(ID, "execute-query", Some(&q_req), second_inv).is_err());
|
||||
|
||||
// Schema discovery returns only non-secret identity + schemas/tables (never credentials or row data).
|
||||
let sources_json = f.run("connected-sources", None).unwrap().unwrap();
|
||||
let sources: Vec<serde_json::Value> = serde_json::from_str(&sources_json).unwrap();
|
||||
assert_eq!(sources.len(), 1);
|
||||
assert_eq!(sources[0]["sourceId"], "user-source");
|
||||
assert_eq!(sources[0]["driver"], "sqlite");
|
||||
assert!(!sources_json.contains("password") && !sources_json.contains("alice"));
|
||||
|
||||
let schemas: Vec<String> =
|
||||
serde_json::from_str(&f.run("list-schemas", Some("user-source")).unwrap().unwrap()).unwrap();
|
||||
assert!(schemas.iter().any(|s| s == "main"));
|
||||
|
||||
let tables: Vec<serde_json::Value> = serde_json::from_str(
|
||||
&f.run("list-tables", Some(r#"{"sourceId":"user-source","schema":"main"}"#)).unwrap().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(tables.iter().any(|t| t["name"] == "users" && t["kind"] == "table"));
|
||||
|
||||
// Query execution respects max_rows & has_more and returns rows.
|
||||
let q_res: serde_json::Value =
|
||||
serde_json::from_str(&f.run("execute-query", Some(&q_req)).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(q_res["rows"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(q_res["rows"][0][1], "alice");
|
||||
assert_eq!(q_res["hasMore"], true);
|
||||
|
||||
// Large cells are capped at 8192 UTF-16 code units.
|
||||
let wide_req = serde_json::json!({
|
||||
"sourceId": "user-source",
|
||||
"sql": "SELECT replace(hex(zeroblob(5000)), '0', 'a')",
|
||||
})
|
||||
.to_string();
|
||||
let wide_res: serde_json::Value =
|
||||
serde_json::from_str(&f.run("execute-query", Some(&wide_req)).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(wide_res["rows"][0][0].as_str().unwrap().encode_utf16().count(), 8192);
|
||||
|
||||
// Invalid inputs (empty SQL, NUL bytes) are rejected cleanly.
|
||||
for bad in [
|
||||
serde_json::json!({ "sourceId": "user-source", "sql": " " }),
|
||||
serde_json::json!({ "sourceId": "user-source", "sql": "SELECT 1\0" }),
|
||||
serde_json::json!({ "sourceId": "user\0source", "sql": "SELECT 1" }),
|
||||
] {
|
||||
assert!(f.run("execute-query", Some(&bad.to_string())).is_err(), "{bad}");
|
||||
}
|
||||
|
||||
// DDL/DML affected count works under database.query.
|
||||
let dml_req = serde_json::json!({
|
||||
"sourceId": "user-source",
|
||||
"sql": "UPDATE users SET name = 'charlie' WHERE id = 2",
|
||||
})
|
||||
.to_string();
|
||||
let dml_res: serde_json::Value =
|
||||
serde_json::from_str(&f.run("execute-query", Some(&dml_req)).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(dml_res["affected"], 1);
|
||||
|
||||
// Background calls (client: None) see sources connected in any window of the project.
|
||||
db.disconnect("user-source").await;
|
||||
let second_db = f.host.project("second").unwrap().db.clone();
|
||||
second_db.execute("user-source", "SELECT 1", 1, &cancel).await.unwrap();
|
||||
let bg_sources: Vec<serde_json::Value> = serde_json::from_str(
|
||||
&f.plugins
|
||||
.run_command(ID, "connected-sources", None, Invocation { client: None, ..f.invocation() })
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(bg_sources.len(), 1);
|
||||
assert_eq!(bg_sources[0]["sourceId"], "user-source");
|
||||
second_db.disconnect("user-source").await;
|
||||
|
||||
// Read-only sources allow SELECT but refuse writes even with database.query granted.
|
||||
db.save_sources(vec![ide_db::DataSource {
|
||||
id: "ro-source".into(),
|
||||
name: "Read-only SQLite".into(),
|
||||
driver: ide_db::DbDriver::Sqlite,
|
||||
file: Some(f.root.join("db.sqlite").into()),
|
||||
read_only: true,
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
db.execute("ro-source", "SELECT 1", 1, &cancel).await.unwrap();
|
||||
let ro_select = serde_json::json!({ "sourceId": "ro-source", "sql": "SELECT count(*) FROM users" }).to_string();
|
||||
let ro_update =
|
||||
serde_json::json!({ "sourceId": "ro-source", "sql": "UPDATE users SET name = 'blocked'" }).to_string();
|
||||
assert!(f.run("execute-query", Some(&ro_select)).is_ok());
|
||||
assert!(f.run("execute-query", Some(&ro_update)).is_err(), "read-only sources must reject writes");
|
||||
|
||||
// Revoking `database.query` blocks queries while leaving `database.schema` discovery intact.
|
||||
f.plugins.set_capability(ID, "database.query", false).unwrap();
|
||||
let err = f.run("execute-query", Some(&ro_select)).unwrap_err();
|
||||
assert!(err.message.contains("database.query"));
|
||||
assert!(f.run("connected-sources", None).is_ok());
|
||||
|
||||
// Revoking project trust blocks both.
|
||||
f.plugins.set_capability(ID, "database.query", true).unwrap();
|
||||
f.host.set_project_trust(&f.root, false, false).await.unwrap();
|
||||
assert!(f.run("connected-sources", None).is_err());
|
||||
assert!(f.run("execute-query", Some(&ro_select)).is_err());
|
||||
}
|
||||
@@ -387,3 +387,20 @@ fn cross_module_reference_and_definition_have_the_same_rename_anchors() {
|
||||
assert_eq!(symbol.files.iter().map(|f| f.ranges.len()).sum::<usize>(), 3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_plugin() {
|
||||
use ide_host::plugins::navigation::MAX_FILES;
|
||||
let f = Fixture::new();
|
||||
let source = f.index("source.idx", SOURCE, &[method()], Some(1), "");
|
||||
for i in 1..MAX_FILES {
|
||||
f.index(&format!("filler/{i}.idx"), "", &[], None, "");
|
||||
}
|
||||
let calls = f.host.info_of("test.indexer").unwrap().stats.calls;
|
||||
let mapping = f.index("mapping.idx", MAPPING, &[], Some(1), "");
|
||||
assert_eq!(f.host.info_of("test.indexer").unwrap().stats.calls, calls, "a file the graph can't take is skipped");
|
||||
assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_none());
|
||||
f.index("source.idx", SOURCE, &[method()], Some(2), "");
|
||||
assert_eq!(f.host.info_of("test.indexer").unwrap().stats.calls, calls + 1, "covered files still update");
|
||||
assert!(f.host.navigation_at(&f.root, &source, 2, Pos::new(1, 5), None, |_| None).is_none());
|
||||
}
|
||||
@@ -65,7 +65,7 @@ impl TestWorkspace {
|
||||
.iter()
|
||||
.map(|&(a, b, c, d)| ide_core::Range::new(ide_core::Pos::new(a, b), ide_core::Pos::new(c, d)))
|
||||
.collect();
|
||||
EditorContext { path, language: "text".into(), selections }
|
||||
EditorContext { path, language: "text".into(), selections, visible_lines: None }
|
||||
}
|
||||
|
||||
fn text(&self, rel: &str) -> String {
|
||||
@@ -2639,6 +2639,150 @@ fn linked_development_plugins() {
|
||||
assert!(again.info_of("language-toy").is_err());
|
||||
}
|
||||
|
||||
/// Drives the event flush the app runs every 250 ms until `f` holds.
|
||||
fn flushing(host: &PluginHost, mut f: impl FnMut() -> bool) -> bool {
|
||||
eventually(|| {
|
||||
host.flush_events();
|
||||
f()
|
||||
})
|
||||
}
|
||||
|
||||
/// Plugin changes announced since the last call (each reload announces one).
|
||||
fn announced_changes(f: &Fixture) -> usize {
|
||||
f.take_events().iter().filter(|(_, e)| matches!(e, PluginEvent::CommandsChanged)).count()
|
||||
}
|
||||
|
||||
/// Lets the watch of a just-linked folder go quiet: macOS reports the files written right
|
||||
/// before the watch started as a first change, which reloads the plugin once.
|
||||
fn settle(f: &Fixture) {
|
||||
changes_within(f, Duration::from_millis(600));
|
||||
f.host.event_wake().wait(Duration::ZERO);
|
||||
}
|
||||
|
||||
/// Runs the flush for `span` and counts the plugin changes announced meanwhile.
|
||||
fn changes_within(f: &Fixture, span: Duration) -> usize {
|
||||
let until = Instant::now() + span;
|
||||
while Instant::now() < until {
|
||||
f.host.flush_events();
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
}
|
||||
announced_changes(f)
|
||||
}
|
||||
|
||||
fn night_tokens(f: &Fixture) -> Option<String> {
|
||||
let active = f.host.active_theme()?;
|
||||
active.theme.tokens.get("--bg-frame").cloned()
|
||||
}
|
||||
|
||||
fn night_json(color: &str) -> String {
|
||||
format!(r##"{{"id":"night","name":"Night","kind":"dark","tokens":{{"--bg-frame":"{color}"}}}}"##)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_plugins_reload_when_their_files_change() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pkg = tmp.path().join("pair");
|
||||
write_theme_pair(&pkg);
|
||||
f.host.link(&pkg).unwrap();
|
||||
f.host.grant("theme-pair", &Consent::default()).unwrap();
|
||||
f.host.set_theme(Some(("theme-pair", "night"))).unwrap();
|
||||
assert_eq!(night_tokens(&f).as_deref(), Some("#111111"));
|
||||
settle(&f);
|
||||
|
||||
// A script regenerates the theme: temp file, rename, then touches it again.
|
||||
let theme = pkg.join("t/night.json");
|
||||
for color in ["#222222", "#333333", "#444444"] {
|
||||
let tmp_file = pkg.join("t/night.json.tmp");
|
||||
std::fs::write(&tmp_file, night_json(color)).unwrap();
|
||||
std::fs::rename(&tmp_file, &theme).unwrap();
|
||||
}
|
||||
let mut reloads = 0;
|
||||
let loaded = flushing(&f.host, || {
|
||||
reloads += announced_changes(&f);
|
||||
night_tokens(&f).as_deref() == Some("#444444")
|
||||
});
|
||||
assert!(loaded, "the final write is loaded");
|
||||
reloads += changes_within(&f, Duration::from_millis(600));
|
||||
assert_eq!(reloads, 1, "the whole burst is one batch and reloads once");
|
||||
|
||||
// A change that doesn't load shows its error; the next valid write recovers.
|
||||
std::fs::write(&theme, "{ not json").unwrap();
|
||||
assert!(flushing(&f.host, || f.status("theme-pair") == PluginStatus::Failed));
|
||||
assert!(f.host.info_of("theme-pair").unwrap().error.is_some());
|
||||
std::fs::write(&theme, night_json("#555555")).unwrap();
|
||||
assert!(flushing(&f.host, || f.status("theme-pair") == PluginStatus::Static));
|
||||
assert_eq!(night_tokens(&f).as_deref(), Some("#555555"), "the selected theme survives the failed reload");
|
||||
|
||||
// Build output and VCS metadata are not part of the package.
|
||||
f.take_events();
|
||||
std::fs::create_dir_all(pkg.join("target/debug")).unwrap();
|
||||
std::fs::create_dir_all(pkg.join(".git")).unwrap();
|
||||
std::fs::write(pkg.join("target/debug/out.bin"), "x").unwrap();
|
||||
std::fs::write(pkg.join(".git/index"), "x").unwrap();
|
||||
std::fs::write(pkg.join("t/night.json~"), "x").unwrap();
|
||||
assert_eq!(changes_within(&f, Duration::from_millis(600)), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_to_a_linked_plugin_wakes_the_event_pump() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pkg = tmp.path().join("pair");
|
||||
write_theme_pair(&pkg);
|
||||
f.host.link(&pkg).unwrap();
|
||||
settle(&f);
|
||||
let wake = f.host.event_wake();
|
||||
assert!(!wake.wait(Duration::from_millis(50)), "idle until something changes");
|
||||
|
||||
std::fs::write(pkg.join("t/night.json"), night_json("#666666")).unwrap();
|
||||
assert!(wake.wait(Duration::from_secs(5)), "the pump is woken without waiting for its period");
|
||||
f.host.flush_events();
|
||||
assert_eq!(announced_changes(&f), 1, "the woken flush reloads the plugin");
|
||||
|
||||
// Files that are not part of the package leave the pump asleep.
|
||||
std::fs::create_dir_all(pkg.join("target")).unwrap();
|
||||
std::fs::write(pkg.join("target/out.bin"), "x").unwrap();
|
||||
std::fs::write(pkg.join("t/night.json~"), "x").unwrap();
|
||||
assert!(!wake.wait(Duration::from_millis(600)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_linked_plugins_are_watched() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let linked = tmp.path().join("linked");
|
||||
write_theme_pair(&linked);
|
||||
f.host.link(&linked).unwrap();
|
||||
let copied = tmp.path().join("copied");
|
||||
write_theme_pair(&copied);
|
||||
std::fs::write(
|
||||
copied.join("plugin.toml"),
|
||||
std::fs::read_to_string(copied.join("plugin.toml")).unwrap().replace("theme-pair", "theme-copy"),
|
||||
)
|
||||
.unwrap();
|
||||
f.install(&copied);
|
||||
let installed = f.installed("theme-copy");
|
||||
settle(&f);
|
||||
|
||||
// The installed copy is not read in place again: editing it changes nothing.
|
||||
std::fs::write(installed.join("t/night.json"), night_json("#999999")).unwrap();
|
||||
assert_eq!(changes_within(&f, Duration::from_millis(600)), 0);
|
||||
|
||||
// Unlinking ends the watch (and the plugin): later edits don't bring it back.
|
||||
std::fs::write(linked.join("t/day.json"), r##"{"id":"day","name":"Day","kind":"light","tokens":{}}"##).unwrap();
|
||||
assert!(flushing(&f.host, || announced_changes(&f) > 0), "a linked plugin is watched");
|
||||
f.host.unlink("theme-pair").unwrap();
|
||||
f.take_events();
|
||||
std::fs::write(
|
||||
linked.join("t/day.json"),
|
||||
r##"{"id":"day","name":"Day","kind":"light","tokens":{"--bg-frame":"#fff"}}"##,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(changes_within(&f, Duration::from_millis(600)), 0);
|
||||
assert!(f.host.info_of("theme-pair").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_lists_sample_packages() {
|
||||
let f = fixture(Limits::default());
|
||||
@@ -7230,6 +7374,7 @@ fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
|
||||
path: path.clone(),
|
||||
language: "text".into(),
|
||||
selections: vec![ide_core::Range::default()],
|
||||
visible_lines: Some((10, 52)),
|
||||
}),
|
||||
);
|
||||
f.host.flush_events_at(Instant::now() + Duration::from_secs(2));
|
||||
@@ -7255,6 +7400,7 @@ fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
|
||||
assert_eq!(events[4]["editor"][0], path.as_str());
|
||||
assert_eq!(events[2]["editor"][0], path);
|
||||
assert_eq!(events[2]["editor"][1][0], serde_json::json!([0, 0, 0, 0]));
|
||||
assert_eq!(events[2]["editor"][2], serde_json::json!([10, 52]));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -8314,3 +8460,77 @@ title = "Prepare"
|
||||
f.host.set_enabled("jobs", false).unwrap();
|
||||
assert!(f.host.web_page("jobs", "jobs").is_err());
|
||||
}
|
||||
|
||||
/// A clone source is a page the Clone Repository dialog lists: its key carries
|
||||
/// the point's name, its page is served like a view's, and it needs a `web`
|
||||
/// entry plus API 1.21.
|
||||
#[test]
|
||||
fn clone_sources_are_web_pages_under_a_namespaced_key() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pkg = tmp.path().join("gitee-demo");
|
||||
std::fs::create_dir_all(pkg.join("clone")).unwrap();
|
||||
std::fs::write(pkg.join("clone/index.html"), "<!doctype html><html><body>repos</body></html>").unwrap();
|
||||
std::fs::write(
|
||||
pkg.join("plugin.toml"),
|
||||
r#"id = "gitee-demo"
|
||||
name = "Gitee Demo"
|
||||
version = "1.0.0"
|
||||
engines.openidea = "^1.21"
|
||||
|
||||
[[contributes.cloneSources]]
|
||||
id = "gitee"
|
||||
label = "Gitee"
|
||||
icon = "branch"
|
||||
web = "clone/index.html"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let info = f.install(&pkg);
|
||||
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
|
||||
|
||||
let item = f.host.ui_items("cloneSources").into_iter().find(|i| i.plugin_id == "gitee-demo").expect("the source");
|
||||
assert_eq!(item.key, "cloneSources/gitee");
|
||||
assert_eq!((item.decl["label"].as_str(), item.decl["icon"].as_str()), (Some("Gitee"), Some("branch")));
|
||||
// A source is not a tool window.
|
||||
assert!(f.host.ui_items("views").iter().all(|i| i.plugin_id != "gitee-demo"));
|
||||
|
||||
let page = f.host.web_page("gitee-demo", "cloneSources/gitee").unwrap();
|
||||
let (rev, entry) = page.path.strip_prefix("gitee-demo/").unwrap().split_once('/').unwrap();
|
||||
assert_eq!(entry, "clone/index.html");
|
||||
assert!(f.host.web_file("gitee-demo", &format!("{rev}/clone/index.html")).is_ok());
|
||||
assert!(f.host.web_page("gitee-demo", "cloneSources/nope").is_err());
|
||||
|
||||
// Refused: no page, a bad id, and an engine older than the point.
|
||||
for (name, body, message) in [
|
||||
("no-page", "id = \"gitee\"\nlabel = \"Gitee\"\nweb = \"clone/missing.html\"", "no such file"),
|
||||
("bad-id", "id = \"Gitee\"\nlabel = \"Gitee\"\nweb = \"clone/index.html\"", "invalid clone source id"),
|
||||
("no-web", "id = \"gitee\"\nlabel = \"Gitee\"", "missing field `web`"),
|
||||
] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let pkg = dir.path().join(name);
|
||||
std::fs::create_dir_all(pkg.join("clone")).unwrap();
|
||||
std::fs::write(pkg.join("clone/index.html"), "<p>repos</p>").unwrap();
|
||||
std::fs::write(
|
||||
pkg.join("plugin.toml"),
|
||||
format!(
|
||||
"id = \"gitee-{name}\"\nname = \"Gitee\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.21\"\n\n[[contributes.cloneSources]]\n{body}\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains(message), "{name}: {}", err.message);
|
||||
}
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
std::fs::create_dir_all(old.join("clone")).unwrap();
|
||||
std::fs::write(old.join("clone/index.html"), "<p>repos</p>").unwrap();
|
||||
std::fs::write(
|
||||
old.join("plugin.toml"),
|
||||
"id = \"gitee-old\"\nname = \"Gitee\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.20\"\n\n[[contributes.cloneSources]]\nid = \"gitee\"\nlabel = \"Gitee\"\nweb = \"clone/index.html\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let err = f.host.install_from_dir(&old, &Consent::all()).unwrap_err();
|
||||
assert!(err.message.contains("new in plugin API 1.21"), "{}", err.message);
|
||||
}
|
||||
@@ -1091,7 +1091,7 @@ async fn remote_focus_preserves_the_editor_for_following_plugin_events() {
|
||||
let events: Value = serde_json::from_str(received.as_str().unwrap()).unwrap();
|
||||
let event = events.as_array().unwrap().iter().rev().find(|e| e["kind"] == "input-mode-changed").unwrap();
|
||||
if focused {
|
||||
assert_eq!(event["editor"], json!([path, [[4, 2, 4, 5]]]));
|
||||
assert_eq!(event["editor"], json!([path, [[4, 2, 4, 5]], null]));
|
||||
} else {
|
||||
assert!(event["editor"].is_null(), "lost focus must clear the previous editor: {event}");
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ fn kinds(status: &[FileStatus]) -> Vec<(String, ChangeKind)> {
|
||||
/// Get from Version Control › Subversion, its progress lines dropped.
|
||||
async fn checkout(host: &Host, url: String, dest: PathBuf) -> ide_core::IdeResult<()> {
|
||||
let channel = ide_host::ops::Channel::new(|_: String| {});
|
||||
svn::svn_checkout(host, "main", ide_core::RequestId::next(), url, dest, channel).await
|
||||
svn::svn_checkout(host, "main", ide_core::RequestId::next(), url, dest, channel, None, None, None).await
|
||||
}
|
||||
|
||||
fn commit_options(paths: &[PathBuf]) -> CommitOptions {
|
||||
@@ -336,6 +336,78 @@ async fn svn_merge_eligible_revisions_and_revert_revision() {
|
||||
assert!(!root.join("feat.txt").exists());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn svn_wc_ops_ignore_property_diff_cleanup_update_options_and_url() {
|
||||
let Some(fx) = fixture() else { return };
|
||||
let root = fx.checkout("wc");
|
||||
std::fs::write(root.join("a.txt"), "one\n").unwrap();
|
||||
fx.svn(&root, &["add", "-q", "a.txt"]);
|
||||
fx.svn(&root, &["propset", "-q", "svn:eol-style", "native", "a.txt"]);
|
||||
fx.svn(&root, &["commit", "-q", "-m", "add a"]);
|
||||
|
||||
let (host, _project) = open(&fx.base, &root).await;
|
||||
let a = root.join("a.txt");
|
||||
|
||||
assert!(svn::svn_item_url(&host, "main", a.clone()).await.unwrap().ends_with("/repo/trunk/a.txt"));
|
||||
|
||||
svn::svn_set_property_options(&host, "main", a.clone(), "svn:eol-style".into(), Some("LF".into()), false)
|
||||
.await
|
||||
.unwrap();
|
||||
let diffs = svn::svn_properties_diff(&host, "main", a.clone()).await.unwrap();
|
||||
assert_eq!(diffs.len(), 1);
|
||||
assert_eq!(
|
||||
(diffs[0].name.as_str(), diffs[0].base_value.as_deref(), diffs[0].value.as_deref()),
|
||||
("svn:eol-style", Some("native"), Some("LF"))
|
||||
);
|
||||
|
||||
let ignored = root.join("build.log");
|
||||
std::fs::write(&ignored, "log\n").unwrap();
|
||||
svn::svn_ignore_pattern(&host, "main", ignored.clone(), "*.log".into()).await.unwrap();
|
||||
assert!(vcs::vcs_status(&host, "main").await.unwrap().iter().all(|f| f.rel_path != "build.log"));
|
||||
|
||||
// Ignoring a new unversioned directory sets svn:ignore on its versioned parent directory.
|
||||
let new_dir = root.join("unversioned-dir");
|
||||
std::fs::create_dir_all(&new_dir).unwrap();
|
||||
svn::svn_ignore_pattern(&host, "main", new_dir.clone(), "unversioned-dir".into()).await.unwrap();
|
||||
assert!(vcs::vcs_status(&host, "main").await.unwrap().iter().all(|f| f.rel_path != "unversioned-dir"));
|
||||
|
||||
let untracked = root.join("scratch.tmp");
|
||||
std::fs::write(&untracked, "tmp").unwrap();
|
||||
svn::svn_cleanup_options(
|
||||
&host,
|
||||
"main",
|
||||
None,
|
||||
svn::SvnCleanupOptions {
|
||||
remove_unversioned: true,
|
||||
remove_ignored: false,
|
||||
include_externals: false,
|
||||
vacuum_pristines: false,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!untracked.exists());
|
||||
|
||||
let channel = ide_host::ops::Channel::new(|_: String| {});
|
||||
let res = svn::svn_update_options(
|
||||
&host,
|
||||
"main",
|
||||
None,
|
||||
ide_core::RequestId::next(),
|
||||
vec![],
|
||||
svn::SvnUpdateOptions {
|
||||
revision: Some("HEAD".into()),
|
||||
depth: Some(svn::SvnDepth::Infinity),
|
||||
set_depth: false,
|
||||
ignore_externals: true,
|
||||
},
|
||||
channel,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(res.revision.is_some());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn svn_changelists_through_the_backend_changelist_commands() {
|
||||
let Some(fx) = fixture() else { return };
|
||||
@@ -868,9 +940,19 @@ async fn a_checkout_reports_progress_and_can_be_cancelled() {
|
||||
let seen = lines.clone();
|
||||
let channel = ide_host::ops::Channel::new(move |line: String| seen.lock().push(line));
|
||||
let dest = fx.base.join("fresh");
|
||||
svn::svn_checkout(&host, "main", ide_core::RequestId::next(), format!("{}/trunk", fx.url), dest.clone(), channel)
|
||||
.await
|
||||
.unwrap();
|
||||
svn::svn_checkout(
|
||||
&host,
|
||||
"main",
|
||||
ide_core::RequestId::next(),
|
||||
format!("{}/trunk", fx.url),
|
||||
dest.clone(),
|
||||
channel,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let lines = lines.lock().clone();
|
||||
assert!(lines.iter().any(|l| l.ends_with("a.txt")) && lines.iter().any(|l| l.ends_with("b.txt")), "{lines:?}");
|
||||
|
||||
@@ -907,7 +989,9 @@ async fn a_checkout_reports_progress_and_can_be_cancelled() {
|
||||
let channel = ide_host::ops::Channel::new(|_: String| {});
|
||||
let url = format!("svn://127.0.0.1:{port}/trunk");
|
||||
let dest = fx.base.join("stuck");
|
||||
tokio::spawn(async move { svn::svn_checkout(&host, "main", request, url, dest, channel).await })
|
||||
tokio::spawn(
|
||||
async move { svn::svn_checkout(&host, "main", request, url, dest, channel, None, None, None).await },
|
||||
)
|
||||
};
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
let started = std::time::Instant::now();
|
||||
@@ -1192,3 +1276,342 @@ async fn update_selected_paths_of_two_working_copies() {
|
||||
"only the selected file of antd"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn incoming_wc_info_branch_layout_compare_switch_and_restricted_mode() {
|
||||
let Some(fx) = fixture() else { return };
|
||||
let wc1 = fx.checkout("wc1");
|
||||
std::fs::write(wc1.join("a.txt"), "v1\n").unwrap();
|
||||
fx.svn(&wc1, &["add", "-q", "a.txt"]);
|
||||
fx.svn(&wc1, &["commit", "-q", "-m", "initial"]);
|
||||
|
||||
// Second WC commits an incoming change while wc1 stays behind.
|
||||
let wc2 = fx.checkout("wc2");
|
||||
std::fs::write(wc2.join("a.txt"), "v2\n").unwrap();
|
||||
fx.svn(&wc2, &["commit", "-q", "-m", "remote update"]);
|
||||
|
||||
// Create a branch & a custom branch container on the server.
|
||||
let trunk_url = format!("{}/trunk", fx.url);
|
||||
let feat_url = format!("{}/branches/feat", fx.url);
|
||||
fx.svn(&fx.base, &["copy", "-q", "-m", "create feat", &trunk_url, &feat_url]);
|
||||
let custom_exp_url = format!("{}/custom-branches/exp", fx.url);
|
||||
fx.svn(&fx.base, &["mkdir", "-q", "--parents", "-m", "custom exp", &custom_exp_url]);
|
||||
|
||||
let (host, _project) = open(&fx.base, &wc1).await;
|
||||
|
||||
// 1. svn_incoming sees remote change to a.txt with revision/author/timestamp metadata.
|
||||
let incoming = svn::svn_incoming(&host, "main", ide_core::RequestId::next(), None).await.unwrap();
|
||||
assert_eq!(incoming.iter().map(|c| c.rel_path.as_str()).collect::<Vec<_>>(), vec!["a.txt"]);
|
||||
assert!(incoming[0].revision.is_some());
|
||||
assert!(incoming[0].time_ms > 0.0);
|
||||
|
||||
// 2. svn_working_copy_info returns info for all SVN roots in the project.
|
||||
let infos = svn::svn_working_copy_info(&host, "main", None).await.unwrap();
|
||||
assert_eq!(infos.len(), 1);
|
||||
assert_eq!(infos[0].url, trunk_url);
|
||||
assert_eq!(infos[0].repository_root, fx.url);
|
||||
assert_eq!(infos[0].depth, "infinity");
|
||||
|
||||
// 3. svn_branch_layout picks up auto branches, and respects explicit per-root branch_configurations
|
||||
// (propagated to Backend::branches / VCS branches popup as well).
|
||||
let auto_layout = svn::svn_branch_layout(&host, "main", ide_core::RequestId::next(), None).await.unwrap();
|
||||
assert!(auto_layout.branches.iter().any(|b| b.name == "feat"));
|
||||
|
||||
let cfg_json = serde_json::json!({
|
||||
wc1.display().to_string(): {
|
||||
"trunkUrl": trunk_url.clone(),
|
||||
"branchLocations": [format!("{}/custom-branches", fx.url)]
|
||||
}
|
||||
});
|
||||
host.project("main")
|
||||
.unwrap()
|
||||
.settings
|
||||
.set(ide_workspace::settings::SettingsScope::Project, "vcs.svn.branchConfigurations", cfg_json)
|
||||
.unwrap();
|
||||
let cfg_layout = svn::svn_branch_layout(&host, "main", ide_core::RequestId::next(), None).await.unwrap();
|
||||
assert_eq!(cfg_layout.branches.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), vec!["exp"]);
|
||||
let backend_branches = vcs::vcs_branches(&host, "main", None).await.unwrap();
|
||||
assert!(backend_branches.iter().any(|b| b.name == "custom-branches/exp"));
|
||||
|
||||
// 4. svn_switch_url switches wc1 to branches/feat, commits a file, and svn_compare_with_url detects it.
|
||||
let reached = svn::svn_switch_url(
|
||||
&host,
|
||||
"main",
|
||||
ide_core::RequestId::next(),
|
||||
None,
|
||||
feat_url.clone(),
|
||||
None,
|
||||
Some(svn::SvnDepth::Infinity),
|
||||
Some(true),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(reached.is_some());
|
||||
assert_eq!(svn::svn_working_copy_info(&host, "main", None).await.unwrap()[0].url, feat_url);
|
||||
|
||||
std::fs::write(wc1.join("branch.txt"), "branch\n").unwrap();
|
||||
fx.svn(&wc1, &["add", "-q", "branch.txt"]);
|
||||
fx.svn(&wc1, &["commit", "-q", "-m", "branch file"]);
|
||||
let diff = svn::svn_compare_with_url(&host, "main", ide_core::RequestId::next(), None, trunk_url.clone(), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(diff.iter().any(|e| e.path == "branch.txt"));
|
||||
|
||||
// Comparing a single locally-modified file against an equal branch URL reports it.
|
||||
std::fs::write(wc1.join("branch.txt"), "branch local edit\n").unwrap();
|
||||
let file_diff = svn::svn_compare_with_url(
|
||||
&host,
|
||||
"main",
|
||||
ide_core::RequestId::next(),
|
||||
None,
|
||||
feat_url.clone(),
|
||||
Some(wc1.join("branch.txt")),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(file_diff.iter().any(|e| e.path == "branch.txt" && e.item == "modified"), "{file_diff:?}");
|
||||
fx.svn(&wc1, &["revert", "-q", "branch.txt"]);
|
||||
|
||||
// Switched descendant sharing parent `.svn` appears in svn_working_copy_info(None).
|
||||
fx.svn(&fx.base, &["mkdir", "-q", "-m", "sub", &format!("{trunk_url}/sub")]);
|
||||
fx.svn(&wc1, &["switch", "-q", "--ignore-ancestry", &feat_url]);
|
||||
fx.svn(&fx.base, &["mkdir", "-q", "-m", "feat sub", &format!("{feat_url}/sub")]);
|
||||
fx.svn(&wc1, &["update", "-q"]);
|
||||
let sub_dir = wc1.join("sub");
|
||||
svn::svn_switch_url(
|
||||
&host,
|
||||
"main",
|
||||
ide_core::RequestId::next(),
|
||||
Some(sub_dir.clone()),
|
||||
format!("{trunk_url}/sub"),
|
||||
None,
|
||||
None,
|
||||
Some(true),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let all_infos = svn::svn_working_copy_info(&host, "main", None).await.unwrap();
|
||||
assert!(
|
||||
all_infos.iter().any(|i| i.root == sub_dir.display().to_string() && i.is_switched),
|
||||
"expected switched descendant in wc info: {all_infos:?}"
|
||||
);
|
||||
|
||||
// 5. Restricted Mode rejects all 5 commands with ErrorKind::Unavailable.
|
||||
let untrusted_wc = fx.checkout("wc-untrusted");
|
||||
let untrusted_host = Host::new(common::host_config(&fx.base)).with_subversion(false);
|
||||
untrusted_host.open_project("restricted", &untrusted_wc).unwrap();
|
||||
for err in [
|
||||
svn::svn_incoming(&untrusted_host, "restricted", ide_core::RequestId::next(), None).await.unwrap_err(),
|
||||
svn::svn_working_copy_info(&untrusted_host, "restricted", None).await.unwrap_err(),
|
||||
svn::svn_branch_layout(&untrusted_host, "restricted", ide_core::RequestId::next(), None).await.unwrap_err(),
|
||||
svn::svn_compare_with_url(&untrusted_host, "restricted", ide_core::RequestId::next(), None, trunk_url, None)
|
||||
.await
|
||||
.unwrap_err(),
|
||||
svn::svn_switch_url(
|
||||
&untrusted_host,
|
||||
"restricted",
|
||||
ide_core::RequestId::next(),
|
||||
None,
|
||||
feat_url,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap_err(),
|
||||
] {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable, "{err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remote_browser_export_checkout_options_and_restricted_mode() {
|
||||
let Some(fx) = fixture() else { return };
|
||||
let wc = fx.checkout("wc");
|
||||
std::fs::write(wc.join("readme.txt"), "rev2\n").unwrap();
|
||||
fx.svn(&wc, &["add", "-q", "readme.txt"]);
|
||||
fx.svn(&wc, &["commit", "-q", "-m", "add readme"]);
|
||||
std::fs::write(wc.join("readme.txt"), "rev3\n").unwrap();
|
||||
std::fs::create_dir_all(wc.join("sub")).unwrap();
|
||||
std::fs::write(wc.join("sub/nested.txt"), "nested\n").unwrap();
|
||||
fx.svn(&wc, &["add", "-q", "sub"]);
|
||||
fx.svn(&wc, &["commit", "-q", "-m", "update readme and add sub"]);
|
||||
|
||||
let (host, _project) = open(&fx.base, &wc).await;
|
||||
let trunk = format!("{}/trunk", fx.url);
|
||||
|
||||
// 1. Browse list, remote log, cat at revision 2 and HEAD.
|
||||
let entries = svn::svn_list_url(&host, "main", ide_core::RequestId::next(), trunk.clone(), None).await.unwrap();
|
||||
assert_eq!(
|
||||
entries.iter().map(|e| (e.name.as_str(), e.kind.as_str())).collect::<Vec<_>>(),
|
||||
vec![("sub", "dir"), ("readme.txt", "file")]
|
||||
);
|
||||
let log =
|
||||
svn::svn_remote_log(&host, "main", ide_core::RequestId::next(), trunk.clone(), None, Some(10)).await.unwrap();
|
||||
assert_eq!(log[0].summary, "update readme and add sub");
|
||||
let text_head = svn::svn_cat_url(&host, "main", ide_core::RequestId::next(), format!("{trunk}/readme.txt"), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(text_head, "rev3\n");
|
||||
let text_r2 =
|
||||
svn::svn_cat_url(&host, "main", ide_core::RequestId::next(), format!("{trunk}/readme.txt"), Some("2".into()))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(text_r2, "rev2\n");
|
||||
|
||||
// 2. Export with depth=files into a clean folder.
|
||||
let exp_dir = fx.base.join("exported");
|
||||
let lines = Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
|
||||
let seen = lines.clone();
|
||||
svn::svn_export(
|
||||
&host,
|
||||
"main",
|
||||
ide_core::RequestId::next(),
|
||||
trunk.clone(),
|
||||
exp_dir.clone(),
|
||||
Some("2".into()),
|
||||
Some(svn::SvnDepth::Files),
|
||||
Some(true),
|
||||
Some(false),
|
||||
ide_host::ops::Channel::new(move |line: String| seen.lock().push(line)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!exp_dir.join(".svn").exists());
|
||||
assert_eq!(std::fs::read_to_string(exp_dir.join("readme.txt")).unwrap(), "rev2\n");
|
||||
assert!(!exp_dir.join("sub").exists());
|
||||
assert!(!lines.lock().is_empty());
|
||||
|
||||
// 3. Checkout with explicit revision and depth=files.
|
||||
let co_dir = fx.base.join("co-r2-files");
|
||||
svn::svn_checkout(
|
||||
&host,
|
||||
"main",
|
||||
ide_core::RequestId::next(),
|
||||
trunk.clone(),
|
||||
co_dir.clone(),
|
||||
ide_host::ops::Channel::new(|_: String| {}),
|
||||
Some("2".into()),
|
||||
Some(svn::SvnDepth::Files),
|
||||
Some(true),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(co_dir.join(".svn").exists());
|
||||
assert_eq!(std::fs::read_to_string(co_dir.join("readme.txt")).unwrap(), "rev2\n");
|
||||
assert!(!co_dir.join("sub").exists());
|
||||
|
||||
// 4. Remote mutations succeed in trusted project.
|
||||
let tags_url = format!("{}/tags", fx.url);
|
||||
assert!(
|
||||
svn::svn_remote_mkdir(&host, "main", ide_core::RequestId::next(), tags_url.clone(), "mkdir tags".into())
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
let tag_v1 = format!("{tags_url}/v1");
|
||||
assert!(
|
||||
svn::svn_remote_copy(
|
||||
&host,
|
||||
"main",
|
||||
ide_core::RequestId::next(),
|
||||
trunk.clone(),
|
||||
tag_v1.clone(),
|
||||
Some("3".into()),
|
||||
"tag v1".into(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
svn::svn_remote_delete(&host, "main", ide_core::RequestId::next(), tag_v1.clone(), "delete v1".into())
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
|
||||
// 5. Restricted Mode rejects remote mutations (`mkdir`/`copy`/`delete`) in untrusted window.
|
||||
let untrusted_dir = fx.base.join("untrusted");
|
||||
std::fs::create_dir_all(&untrusted_dir).unwrap();
|
||||
let untrusted_host = Host::new(common::host_config(&fx.base)).with_subversion(false);
|
||||
untrusted_host.open_project("restricted", &untrusted_dir).unwrap();
|
||||
let mkdir_err = svn::svn_remote_mkdir(
|
||||
&untrusted_host,
|
||||
"restricted",
|
||||
ide_core::RequestId::next(),
|
||||
format!("{}/blocked", fx.url),
|
||||
"blocked".into(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(mkdir_err.kind, ide_core::error::ErrorKind::Unavailable, "{mkdir_err:?}");
|
||||
assert!(mkdir_err.message.contains("Restricted Mode"), "{mkdir_err:?}");
|
||||
let copy_err = svn::svn_remote_copy(
|
||||
&untrusted_host,
|
||||
"restricted",
|
||||
ide_core::RequestId::next(),
|
||||
trunk,
|
||||
tag_v1.clone(),
|
||||
None,
|
||||
"blocked".into(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(copy_err.kind, ide_core::error::ErrorKind::Unavailable, "{copy_err:?}");
|
||||
let del_err =
|
||||
svn::svn_remote_delete(&untrusted_host, "restricted", ide_core::RequestId::next(), tags_url, "blocked".into())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(del_err.kind, ide_core::error::ErrorKind::Unavailable, "{del_err:?}");
|
||||
}
|
||||
|
||||
/// Update Project in two working copies (issue #7433): the console gets svn's own output for
|
||||
/// each, the files it changed and the revision reached, not only a summary line.
|
||||
#[tokio::test]
|
||||
async fn update_output_of_two_working_copies() {
|
||||
let Some(fx) = fixture() else { return };
|
||||
let seed = fx.checkout("seed");
|
||||
for name in ["a.txt", "gone.txt"] {
|
||||
std::fs::write(seed.join(name), "one\n").unwrap();
|
||||
}
|
||||
fx.svn(&seed, &["add", "-q", "a.txt", "gone.txt"]);
|
||||
fx.svn(&seed, &["commit", "-q", "-m", "seed"]);
|
||||
let project_root = fx.base.join("project");
|
||||
std::fs::create_dir(&project_root).unwrap();
|
||||
let trunk = format!("{}/trunk", fx.url);
|
||||
for name in ["boot", "antd"] {
|
||||
fx.svn(&fx.base, &["checkout", "-q", &trunk, project_root.join(name).to_str().unwrap()]);
|
||||
}
|
||||
std::fs::write(seed.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(seed.join("new.txt"), "new\n").unwrap();
|
||||
fx.svn(&seed, &["add", "-q", "new.txt"]);
|
||||
fx.svn(&seed, &["rm", "-q", "gone.txt"]);
|
||||
fx.svn(&seed, &["commit", "-q", "-m", "two"]);
|
||||
|
||||
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
until("both working copies", || project.backends().len() == 2).await;
|
||||
for name in ["boot", "antd"] {
|
||||
let lines = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||
let sink = lines.clone();
|
||||
let channel = ide_host::ops::Channel::new(move |line: String| sink.lock().unwrap().push(line));
|
||||
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
|
||||
let repo = Some(project_root.join(name));
|
||||
vcs::vcs_remote(&host, "main", repo, ide_core::RequestId::next(), op, channel, None).await.unwrap();
|
||||
let lines = lines.lock().unwrap().clone();
|
||||
let changed: Vec<&str> = lines
|
||||
.iter()
|
||||
.filter_map(|l| {
|
||||
l.split_once(char::is_whitespace).filter(|(code, _)| code.len() == 1).map(|(_, p)| p.trim())
|
||||
})
|
||||
.map(|p| p.rsplit(['/', '\\']).next().unwrap())
|
||||
.collect();
|
||||
assert!(lines.iter().any(|l| l.starts_with("Updating ")), "{name}: {lines:?}");
|
||||
for file in ["a.txt", "new.txt", "gone.txt"] {
|
||||
assert!(changed.contains(&file), "{name}: {file} in {lines:?}");
|
||||
}
|
||||
assert!(lines.last().is_some_and(|l| l.starts_with("Updated to revision ")), "{name}: {lines:?}");
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,14 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
|
||||
let host = &host;
|
||||
let w = "main";
|
||||
let file = project.root.join("src/a.txt");
|
||||
#[cfg(unix)]
|
||||
let history_path = {
|
||||
let link = project.root.join("linked.txt");
|
||||
std::os::unix::fs::symlink(external.root.join("src/a.txt"), &link).unwrap();
|
||||
link
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let history_path = file.clone();
|
||||
let root = || Some(project.root.clone());
|
||||
let log = || Some(external.root.clone());
|
||||
|
||||
@@ -169,6 +177,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
|
||||
call!("vcs_detected_roots", "", vcs::vcs_detected_roots(host, w)),
|
||||
call!("vcs_branch_info", "", vcs::vcs_branch_info(host, w, root())),
|
||||
call!("vcs_line_hunks", "", vcs::vcs_line_hunks(host, w, file.clone())),
|
||||
call!("vcs_linked_file_has_history", "", vcs::vcs_linked_file_has_history(host, w, history_path)),
|
||||
call!("vcs_staging_line_hunks", "", vcs::vcs_staging_line_hunks(host, w, file.clone(), None)),
|
||||
call!("vcs_file_at", "", vcs::vcs_file_at(host, w, file.clone(), None)),
|
||||
call!("vcs_image_at", "", vcs::vcs_image_at(host, w, project.root.join("asset.jpg"), ":0".into())),
|
||||
|
||||
@@ -74,6 +74,110 @@ impl Drop for Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn linked_editor_files_use_target_history_and_unsaved_text() {
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let target = base.join("target");
|
||||
let root = base.join("workspace");
|
||||
std::fs::create_dir(&target).unwrap();
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let target_file = target.join("notes.txt");
|
||||
let original = "first\nsecond\n";
|
||||
std::fs::write(&target_file, original).unwrap();
|
||||
git(&target, &["init", "-b", "main"]);
|
||||
git(&target, &["add", "notes.txt"]);
|
||||
git(
|
||||
&target,
|
||||
&[
|
||||
"-c",
|
||||
"user.name=Target",
|
||||
"-c",
|
||||
"[email protected]",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"-m",
|
||||
"Add notes",
|
||||
],
|
||||
);
|
||||
symlink("../target", root.join("linked")).unwrap();
|
||||
let directory_link_file = root.join("linked/notes.txt");
|
||||
let file_link = root.join("notes.txt");
|
||||
symlink("../target/notes.txt", &file_link).unwrap();
|
||||
let new_file = target.join("new.txt");
|
||||
std::fs::write(&new_file, "not committed\n").unwrap();
|
||||
git(&target, &["add", "new.txt"]);
|
||||
symlink("../target/new.txt", root.join("new.txt")).unwrap();
|
||||
std::fs::write(root.join("plain.txt"), "not a link\n").unwrap();
|
||||
|
||||
let host = Host::new(common::host_config(&base));
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
for path in [root.join("plain.txt"), root.join("new.txt"), new_file] {
|
||||
assert!(!vcs::vcs_linked_file_has_history(&host, "main", path).await.unwrap());
|
||||
}
|
||||
for path in [&directory_link_file, &file_link] {
|
||||
assert!(vcs::vcs_linked_file_has_history(&host, "main", path.clone()).await.unwrap());
|
||||
let blame = vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap();
|
||||
assert_eq!(blame.len(), 2);
|
||||
assert!(blame.iter().all(|line| line.author == "Target"));
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap().is_empty());
|
||||
let doc = project.documents.open(path).unwrap().id;
|
||||
project.documents.replace_all(doc, "first\nupdated\n").unwrap();
|
||||
let hunks = vcs::vcs_line_hunks(&host, "main", path.clone()).await.unwrap();
|
||||
assert_eq!(hunks.len(), 1);
|
||||
assert_eq!((hunks[0].start, hunks[0].lines, hunks[0].old_text.as_str()), (1, 1, "second\n"));
|
||||
let blame = vcs::vcs_blame(&host, "main", path.clone(), None, None).await.unwrap();
|
||||
assert_eq!(blame[0].author, "Target");
|
||||
assert!(blame[1].commit.chars().all(|character| character == '0'));
|
||||
assert!(vcs::vcs_staging_line_hunks(&host, "main", path.clone(), None).await.unwrap().is_none());
|
||||
project.documents.close(doc);
|
||||
}
|
||||
assert_eq!(std::fs::read_to_string(&target_file).unwrap(), original);
|
||||
assert!(project.repos().is_empty());
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", target_file).await.is_err());
|
||||
|
||||
// The workspace's Git history can contain the link itself, but the editor reads its target.
|
||||
git(&root, &["init", "-b", "main"]);
|
||||
git(&root, &["add", "linked", "notes.txt"]);
|
||||
git(
|
||||
&root,
|
||||
&[
|
||||
"-c",
|
||||
"user.name=Workspace",
|
||||
"-c",
|
||||
"[email protected]",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"commit",
|
||||
"-m",
|
||||
"Add links",
|
||||
],
|
||||
);
|
||||
project.refresh_repositories();
|
||||
assert_eq!(project.repos().roots(), vec![root.clone()]);
|
||||
let blame = vcs::vcs_blame(&host, "main", file_link.clone(), None, None).await.unwrap();
|
||||
assert_eq!(blame[0].author, "Target");
|
||||
assert!(vcs::vcs_staging_line_hunks(&host, "main", file_link, None).await.unwrap().is_none());
|
||||
|
||||
for excluded in ["linked".to_owned(), target.to_string_lossy().into_owned()] {
|
||||
project.settings.set(SettingsScope::Project, "vcs.mappings.excluded", serde_json::json!([excluded])).unwrap();
|
||||
assert!(vcs::vcs_linked_file_has_history(&host, "main", directory_link_file.clone()).await.is_err());
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", directory_link_file.clone()).await.is_err());
|
||||
assert!(vcs::vcs_blame(&host, "main", directory_link_file.clone(), None, None).await.is_err());
|
||||
}
|
||||
project.settings.set(SettingsScope::Project, "vcs.mappings.excluded", serde_json::json!([])).unwrap();
|
||||
project.settings.set(SettingsScope::Project, "vcs.git.enabled", serde_json::json!(false)).unwrap();
|
||||
assert!(!vcs::vcs_linked_file_has_history(&host, "main", directory_link_file.clone()).await.unwrap());
|
||||
assert!(vcs::vcs_line_hunks(&host, "main", directory_link_file.clone()).await.is_err());
|
||||
assert!(vcs::vcs_blame(&host, "main", directory_link_file, None, None).await.is_err());
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn checkout_reloads_clean_open_documents_before_returning() {
|
||||
let f = Fixture::new().await;
|
||||
|
||||
@@ -432,3 +432,168 @@ async fn tmp_alias_is_protected() {
|
||||
let alias = std::path::Path::new("/").join(linked.strip_prefix("/private").unwrap());
|
||||
f.assert_protected(&alias).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn linked_worktree_below_project_repo_is_excluded_until_unmarked_or_attached() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let workspace = base.join("workspace");
|
||||
let repo = workspace.join("app");
|
||||
std::fs::create_dir_all(repo.join("src")).unwrap();
|
||||
std::fs::write(repo.join("Cargo.toml"), "[package]\nname = \"app\"\nversion = \"0.1.0\"\n").unwrap();
|
||||
std::fs::write(
|
||||
repo.join("src/lib.rs"),
|
||||
"pub fn unique_worktree_symbol() -> &'static str { \"unique_worktree_needle\" }\n",
|
||||
)
|
||||
.unwrap();
|
||||
git(&repo, &["init", "-b", "main"]);
|
||||
git(&repo, &["config", "user.name", "Test"]);
|
||||
git(&repo, &["config", "user.email", "[email protected]"]);
|
||||
git(&repo, &["config", "commit.gpgsign", "false"]);
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-m", "initial"]);
|
||||
|
||||
// Linked worktree of `repo` placed below `repo` at a custom path (not `.worktrees`).
|
||||
let nested = repo.join("topics/feature");
|
||||
git(&repo, &["worktree", "add", "-b", "feature", nested.to_str().unwrap()]);
|
||||
// Sibling linked worktree outside `repo`, inside the non-repo parent folder `workspace`.
|
||||
let sibling = workspace.join("app-sibling");
|
||||
git(&repo, &["worktree", "add", "-b", "sibling", sibling.to_str().unwrap()]);
|
||||
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&repo, true, false).unwrap();
|
||||
let project = host.open_project("main", &repo).unwrap();
|
||||
wait_for_repos(&project, 2).await;
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
|
||||
let search = |include_excluded: bool| {
|
||||
let host = &host;
|
||||
async move {
|
||||
let hits = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let out = hits.clone();
|
||||
let query = serde_json::from_value(serde_json::json!({
|
||||
"pattern": "unique_worktree_needle",
|
||||
"isRegex": false,
|
||||
"caseSensitive": true,
|
||||
"wholeWord": false,
|
||||
"include": [],
|
||||
"exclude": [],
|
||||
"scope": { "kind": "project" },
|
||||
"maxMatches": 100,
|
||||
"includeExcluded": include_excluded
|
||||
}))
|
||||
.unwrap();
|
||||
ide_host::ops::search::search_start(
|
||||
host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query,
|
||||
ide_host::ops::Channel::new(move |event| {
|
||||
if let ide_host::ops::search::SearchEvent::File { file } = event {
|
||||
out.lock().unwrap().push(file.rel_path);
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut found = hits.lock().unwrap().clone();
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
};
|
||||
|
||||
// Detected as excluded root; skipped in file index, symbol index, and Find in Files.
|
||||
assert!(project.roots().excluded_globs().contains(&"/topics/feature".to_owned()));
|
||||
let indexed_files: Vec<String> = project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect();
|
||||
assert_eq!(indexed_files, vec!["src/lib.rs"]);
|
||||
let indexed_syms: Vec<String> = project
|
||||
.index
|
||||
.find_symbols("unique_worktree_symbol", ide_index::SymbolFilter::All, 20)
|
||||
.into_iter()
|
||||
.map(|m| m.rel_path)
|
||||
.collect();
|
||||
assert_eq!(indexed_syms, vec!["src/lib.rs"]);
|
||||
assert_eq!(search(false).await, vec!["src/lib.rs"]);
|
||||
assert_eq!(search(true).await, vec!["src/lib.rs", "topics/feature/src/lib.rs"]);
|
||||
|
||||
// Adding a worktree below `repo` via VCS command excludes it immediately; removing drops it.
|
||||
let live_wt = repo.join("live-worktree");
|
||||
vcs::vcs_add_worktree(&host, "main", None, live_wt.clone(), "main".into(), Some("live".into()), None, None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(project.roots().excluded_globs().contains(&"/live-worktree".to_owned()));
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
assert_eq!(search(false).await, vec!["src/lib.rs"]);
|
||||
vcs::vcs_remove_worktree(&host, "main", None, live_wt, false).await.unwrap();
|
||||
assert!(!project.roots().excluded_globs().contains(&"/live-worktree".to_owned()));
|
||||
|
||||
// Unmarking the detected exclusion (Cancel Exclusion) opts the worktree back in.
|
||||
ide_host::ops::project::set_settings(
|
||||
&host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"projectStructure.unmarked",
|
||||
r#"["topics/feature"]"#,
|
||||
)
|
||||
.unwrap();
|
||||
let expected_both = vec!["src/lib.rs".to_owned(), "topics/feature/src/lib.rs".to_owned()];
|
||||
let mut after_unmark = Vec::new();
|
||||
for _ in 0..100 {
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
after_unmark = project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect();
|
||||
after_unmark.sort();
|
||||
if after_unmark == expected_both {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
assert_eq!(after_unmark, expected_both);
|
||||
assert_eq!(search(false).await, expected_both);
|
||||
|
||||
// Clear the unmark so the worktree is excluded again, then verify `attach_workspace` opts it back in.
|
||||
ide_host::ops::project::set_settings(
|
||||
&host,
|
||||
"main",
|
||||
ide_workspace::settings::SettingsScope::Project,
|
||||
"projectStructure.unmarked",
|
||||
"[]",
|
||||
)
|
||||
.unwrap();
|
||||
for _ in 0..100 {
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
if project.index.find_files("lib.rs", 20).len() == 1 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
assert_eq!(search(false).await, vec!["src/lib.rs"]);
|
||||
host.trust.decide(&nested, true, false).unwrap();
|
||||
ide_host::ops::project::attach_workspace(&host, "main", &nested).unwrap();
|
||||
assert!(project.index.wait_idle(Duration::from_secs(10)));
|
||||
let mut after_attach: Vec<String> =
|
||||
project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect();
|
||||
after_attach.sort();
|
||||
assert_eq!(after_attach, expected_both);
|
||||
assert_eq!(search(false).await, expected_both);
|
||||
|
||||
// Opening the linked worktree directly as the project root indexes and searches it normally.
|
||||
host.close_project("main");
|
||||
host.trust.decide(&nested, true, false).unwrap();
|
||||
let wt_project = host.open_project("main", &nested).unwrap();
|
||||
assert!(wt_project.index.wait_idle(Duration::from_secs(10)));
|
||||
assert!(wt_project.roots().excluded_globs().is_empty());
|
||||
let wt_files: Vec<String> = wt_project.index.find_files("lib.rs", 20).into_iter().map(|m| m.rel_path).collect();
|
||||
assert_eq!(wt_files, vec!["src/lib.rs"]);
|
||||
assert_eq!(search(false).await, vec!["src/lib.rs"]);
|
||||
|
||||
// Opening a non-repository parent folder holding `app` and sibling `app-sibling` keeps both indexed.
|
||||
host.close_project("main");
|
||||
host.trust.decide(&workspace, true, false).unwrap();
|
||||
let parent_project = host.open_project("main", &workspace).unwrap();
|
||||
assert!(parent_project.index.wait_idle(Duration::from_secs(10)));
|
||||
assert!(!parent_project.roots().excluded_globs().contains(&"/app-sibling".to_owned()));
|
||||
let parent_found = search(false).await;
|
||||
assert!(parent_found.contains(&"app/src/lib.rs".to_owned()), "{parent_found:?}");
|
||||
assert!(parent_found.contains(&"app-sibling/src/lib.rs".to_owned()), "{parent_found:?}");
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! The body of a prepared request: text and the bytes of included files, in order.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum BodyChunk {
|
||||
Text(String),
|
||||
/// Bytes that are not text, included as `< path` (as written, relative to the request file).
|
||||
Binary {
|
||||
path: String,
|
||||
bytes: Arc<[u8]>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Serialized as [`RequestBody::display`]: the UI and the history never hold a binary file's bytes,
|
||||
/// so a body read back from either is for display only.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(from = "String", into = "String")]
|
||||
pub struct RequestBody {
|
||||
chunks: Vec<BodyChunk>,
|
||||
}
|
||||
|
||||
impl RequestBody {
|
||||
pub(crate) fn push_text(&mut self, text: &str) {
|
||||
if let Some(BodyChunk::Text(last)) = self.chunks.last_mut() {
|
||||
last.push_str(text);
|
||||
} else if !text.is_empty() {
|
||||
self.chunks.push(BodyChunk::Text(text.to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the content of the file included as `< path`.
|
||||
pub(crate) fn push_file(&mut self, path: &str, bytes: Vec<u8>) {
|
||||
match std::str::from_utf8(&bytes) {
|
||||
Ok(text) if !text.contains('\0') => self.push_text(text),
|
||||
_ => self.chunks.push(BodyChunk::Binary { path: path.to_owned(), bytes: bytes.into() }),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn chunks(&self) -> &[BodyChunk] {
|
||||
&self.chunks
|
||||
}
|
||||
|
||||
/// The bytes to send.
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for chunk in &self.chunks {
|
||||
match chunk {
|
||||
BodyChunk::Text(text) => out.extend_from_slice(text.as_bytes()),
|
||||
BodyChunk::Binary { bytes, .. } => out.extend_from_slice(bytes),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The body as text, with the `< path` line of each binary file in place of its bytes.
|
||||
pub fn display(&self) -> String {
|
||||
let mut out = String::new();
|
||||
for chunk in &self.chunks {
|
||||
match chunk {
|
||||
BodyChunk::Text(text) => out.push_str(text),
|
||||
BodyChunk::Binary { path, .. } => {
|
||||
out.push_str("< ");
|
||||
out.push_str(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for RequestBody {
|
||||
fn from(text: String) -> Self {
|
||||
Self { chunks: vec![BodyChunk::Text(text)] }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for RequestBody {
|
||||
fn from(text: &str) -> Self {
|
||||
text.to_owned().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RequestBody> for String {
|
||||
fn from(body: RequestBody) -> Self {
|
||||
body.display()
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,49 @@
|
||||
//! cURL ⇄ `.http` request: Convert to cURL and Copy, and the conversion of a pasted
|
||||
//! `curl …` command into a request.
|
||||
|
||||
use crate::PreparedRequest;
|
||||
mod form;
|
||||
mod import;
|
||||
mod options;
|
||||
mod words;
|
||||
|
||||
/// `req` as a cURL command line, one option per line (POSIX shell quoting).
|
||||
pub use import::from_curl;
|
||||
|
||||
use crate::PreparedRequest;
|
||||
use crate::body::BodyChunk;
|
||||
|
||||
/// `req` as a cURL command line, one option per line (POSIX shell quoting). Binary files of the
|
||||
/// body are read by their path, relative to the request file.
|
||||
pub fn to_curl(req: &PreparedRequest) -> String {
|
||||
let mut parts = vec![format!("curl -X {} {}", req.method, quote(&req.url))];
|
||||
for (k, v) in &req.headers {
|
||||
parts.push(format!("-H {}", quote(&format!("{k}: {v}"))));
|
||||
}
|
||||
if let Some(body) = &req.body {
|
||||
parts.push(format!("--data-raw {}", quote(body)));
|
||||
let mut input = None;
|
||||
match req.body.as_ref().map(|b| (b.chunks(), b)) {
|
||||
None => {}
|
||||
Some(([BodyChunk::Binary { path, .. }], _)) => {
|
||||
parts.push(format!("--data-binary {}", quote(&format!("@{path}"))));
|
||||
}
|
||||
Some(([] | [BodyChunk::Text(_)], body)) => parts.push(format!("--data-raw {}", quote(&body.display()))),
|
||||
// cURL joins several data options with `&`, so a mixed body is piped in.
|
||||
Some((chunks, _)) => {
|
||||
input = Some(chunks.iter().map(piped).collect::<String>());
|
||||
parts.push("--data-binary @-".to_owned());
|
||||
}
|
||||
}
|
||||
let curl = parts.join(" \\\n ");
|
||||
match input {
|
||||
Some(input) => format!("{{ {input}}} | {curl}"),
|
||||
None => curl,
|
||||
}
|
||||
}
|
||||
|
||||
/// The shell command writing `chunk` to stdout, with its `;`.
|
||||
fn piped(chunk: &BodyChunk) -> String {
|
||||
match chunk {
|
||||
BodyChunk::Text(text) => format!("printf %s {}; ", quote(text)),
|
||||
BodyChunk::Binary { path, .. } => format!("cat {}; ", quote(path)),
|
||||
}
|
||||
parts.join(" \\\n ")
|
||||
}
|
||||
|
||||
/// `s` in single quotes, as POSIX shells read it.
|
||||
@@ -20,215 +51,6 @@ fn quote(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', r"'\''"))
|
||||
}
|
||||
|
||||
/// The request a `curl …` command sends, as `.http` text; `None` when `cmd` is not a cURL
|
||||
/// command or names no URL.
|
||||
pub fn from_curl(cmd: &str) -> Option<String> {
|
||||
let words = split_words(cmd)?;
|
||||
let mut args = words.iter().map(String::as_str);
|
||||
if args.next() != Some("curl") {
|
||||
return None;
|
||||
}
|
||||
let mut method: Option<String> = None;
|
||||
let mut url: Option<String> = None;
|
||||
let mut headers: Vec<(String, String)> = Vec::new();
|
||||
let mut data: Vec<String> = Vec::new();
|
||||
let mut form: Vec<(String, String)> = Vec::new();
|
||||
let mut get = false;
|
||||
let header = |headers: &mut Vec<(String, String)>, line: &str| {
|
||||
if let Some((k, v)) = line.split_once(':') {
|
||||
headers.push((k.trim().to_owned(), v.trim().to_owned()));
|
||||
}
|
||||
};
|
||||
while let Some(arg) = args.next() {
|
||||
// `--opt=value` and `-Xvalue` forms.
|
||||
let (flag, inline) = match arg.split_once('=') {
|
||||
Some((f, v)) if arg.starts_with("--") => (f, Some(v.to_owned())),
|
||||
_ if arg.len() > 2 && arg.starts_with('-') && !arg.starts_with("--") && takes_value(&arg[..2]) => {
|
||||
(&arg[..2], Some(arg[2..].to_owned()))
|
||||
}
|
||||
_ => (arg, None),
|
||||
};
|
||||
let mut value = || inline.clone().or_else(|| args.next().map(str::to_owned));
|
||||
match flag {
|
||||
"-X" | "--request" => method = value(),
|
||||
"-H" | "--header" => header(&mut headers, &value()?),
|
||||
"-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" | "--data-urlencode" => {
|
||||
data.push(value()?)
|
||||
}
|
||||
"--json" => {
|
||||
data.push(value()?);
|
||||
headers.push(("Content-Type".into(), "application/json".into()));
|
||||
headers.push(("Accept".into(), "application/json".into()));
|
||||
}
|
||||
"-F" | "--form" | "--form-string" => {
|
||||
let v = value()?;
|
||||
let (k, v) = v.split_once('=')?;
|
||||
form.push((k.to_owned(), v.to_owned()));
|
||||
}
|
||||
"-u" | "--user" => {
|
||||
let v = value()?;
|
||||
let (user, pass) = v.split_once(':').unwrap_or((&v, ""));
|
||||
headers.push(("Authorization".into(), format!("Basic {user} {pass}").trim_end().to_owned()));
|
||||
}
|
||||
"-b" | "--cookie" => headers.push(("Cookie".into(), value()?)),
|
||||
"-A" | "--user-agent" => headers.push(("User-Agent".into(), value()?)),
|
||||
"-e" | "--referer" => headers.push(("Referer".into(), value()?)),
|
||||
"--url" => url = value(),
|
||||
"-G" | "--get" => get = true,
|
||||
f if f.starts_with('-') => {
|
||||
// Options with a value the request doesn't need (timeouts, output, proxy…).
|
||||
if takes_value(f) {
|
||||
value();
|
||||
}
|
||||
}
|
||||
u => {
|
||||
if url.is_none() {
|
||||
url = Some(u.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut url = url?;
|
||||
if get && !data.is_empty() {
|
||||
url.push(if url.contains('?') { '&' } else { '?' });
|
||||
url.push_str(&data.join("&"));
|
||||
data.clear();
|
||||
}
|
||||
let method = method.unwrap_or_else(|| if data.is_empty() && form.is_empty() { "GET" } else { "POST" }.into());
|
||||
let mut body = None;
|
||||
if !form.is_empty() {
|
||||
const BOUNDARY: &str = "WebAppBoundary";
|
||||
headers.retain(|(k, _)| !k.eq_ignore_ascii_case("content-type"));
|
||||
headers.push(("Content-Type".into(), format!("multipart/form-data; boundary={BOUNDARY}")));
|
||||
let mut text = String::new();
|
||||
for (name, value) in &form {
|
||||
text.push_str(&format!("--{BOUNDARY}\n"));
|
||||
match value.strip_prefix('@') {
|
||||
Some(file) => {
|
||||
let file = file.split(';').next().unwrap_or(file);
|
||||
let base = file.rsplit(['/', '\\']).next().unwrap_or(file);
|
||||
text.push_str(&format!(
|
||||
"Content-Disposition: form-data; name=\"{name}\"; filename=\"{base}\"\n\n< {file}\n"
|
||||
));
|
||||
}
|
||||
None => text.push_str(&format!("Content-Disposition: form-data; name=\"{name}\"\n\n{value}\n")),
|
||||
}
|
||||
}
|
||||
text.push_str(&format!("--{BOUNDARY}--"));
|
||||
body = Some(text);
|
||||
} else if !data.is_empty() {
|
||||
if !headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-type")) {
|
||||
headers.push(("Content-Type".into(), "application/x-www-form-urlencoded".into()));
|
||||
}
|
||||
body = Some(data.join("&"));
|
||||
}
|
||||
let mut out = format!("{method} {url}\n");
|
||||
for (k, v) in &headers {
|
||||
out.push_str(&format!("{k}: {v}\n"));
|
||||
}
|
||||
if let Some(body) = body {
|
||||
out.push('\n');
|
||||
out.push_str(&body);
|
||||
out.push('\n');
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Options that take a value, so it isn't read as the URL.
|
||||
fn takes_value(flag: &str) -> bool {
|
||||
matches!(
|
||||
flag,
|
||||
"-X" | "-H"
|
||||
| "-d"
|
||||
| "-F"
|
||||
| "-u"
|
||||
| "-b"
|
||||
| "-A"
|
||||
| "-e"
|
||||
| "-o"
|
||||
| "-x"
|
||||
| "-m"
|
||||
| "-c"
|
||||
| "-E"
|
||||
| "-T"
|
||||
| "-w"
|
||||
| "-r"
|
||||
| "-K"
|
||||
| "--output"
|
||||
| "--proxy"
|
||||
| "--max-time"
|
||||
| "--connect-timeout"
|
||||
| "--cookie-jar"
|
||||
| "--cert"
|
||||
| "--key"
|
||||
| "--cacert"
|
||||
| "--upload-file"
|
||||
| "--write-out"
|
||||
| "--range"
|
||||
| "--config"
|
||||
| "--retry"
|
||||
| "--resolve"
|
||||
| "--interface"
|
||||
)
|
||||
}
|
||||
|
||||
/// Shell words of `cmd`: single and double quotes, backslash escapes and line continuations
|
||||
/// (also `^` / backtick continuations from Windows shells). `None` for an unclosed quote.
|
||||
fn split_words(cmd: &str) -> Option<Vec<String>> {
|
||||
let mut words = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut in_word = false;
|
||||
let mut chars = cmd.trim().chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
'\'' => {
|
||||
in_word = true;
|
||||
loop {
|
||||
match chars.next()? {
|
||||
'\'' => break,
|
||||
c => cur.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
'"' => {
|
||||
in_word = true;
|
||||
loop {
|
||||
match chars.next()? {
|
||||
'"' => break,
|
||||
'\\' if matches!(chars.peek(), Some('"' | '\\' | '$' | '`')) => cur.push(chars.next()?),
|
||||
c => cur.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
'\\' | '^' | '`' if matches!(chars.peek(), Some('\n' | '\r')) => {
|
||||
while matches!(chars.peek(), Some('\n' | '\r')) {
|
||||
chars.next();
|
||||
}
|
||||
}
|
||||
'\\' => {
|
||||
in_word = true;
|
||||
if let Some(n) = chars.next() {
|
||||
cur.push(n);
|
||||
}
|
||||
}
|
||||
c if c.is_whitespace() => {
|
||||
if in_word {
|
||||
words.push(std::mem::take(&mut cur));
|
||||
in_word = false;
|
||||
}
|
||||
}
|
||||
c => {
|
||||
in_word = true;
|
||||
cur.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
if in_word {
|
||||
words.push(cur);
|
||||
}
|
||||
Some(words)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Multipart fields (`-F name=content`).
|
||||
|
||||
/// Also the boundary written in the request.
|
||||
pub(super) const BOUNDARY: &str = "WebAppBoundary";
|
||||
|
||||
enum Content {
|
||||
Text(String),
|
||||
File(String),
|
||||
}
|
||||
|
||||
pub(super) struct Field {
|
||||
name: String,
|
||||
content: Content,
|
||||
filename: Option<String>,
|
||||
content_type: Option<String>,
|
||||
headers: Vec<String>,
|
||||
}
|
||||
|
||||
const ATTRIBUTES: [&str; 4] = ["type=", "filename=", "headers=", "encoder="];
|
||||
|
||||
impl Field {
|
||||
/// `--form-string name=text`: nothing in the text is special.
|
||||
pub(super) fn literal(value: &str) -> Option<Self> {
|
||||
let (name, text) = value.split_once('=')?;
|
||||
Some(Self::new(name, Content::Text(text.to_owned())))
|
||||
}
|
||||
|
||||
/// `-F name=content;attribute=…`. `None` for what one part of a request file can't express:
|
||||
/// nested parts, several files, standard input, encoders and header files.
|
||||
pub(super) fn parse(value: &str) -> Option<Self> {
|
||||
let (name, content) = value.split_once('=')?;
|
||||
let content = content.trim_start();
|
||||
if content.starts_with('(') || (name.is_empty() && content.starts_with(')')) {
|
||||
return None;
|
||||
}
|
||||
let (mut field, mut rest) = if let Some(file) = content.strip_prefix(['@', '<']) {
|
||||
let (path, quoted, rest) = word(file);
|
||||
if path.is_empty() || path == "-" || (!quoted && path.contains(',')) {
|
||||
return None;
|
||||
}
|
||||
let base = path.rsplit(['/', '\\']).next().unwrap_or(&path).to_owned();
|
||||
let filename = content.starts_with('@').then_some(base);
|
||||
(Self { filename, ..Self::new(name, Content::File(path)) }, rest)
|
||||
} else {
|
||||
let (text, _, rest) = word(content);
|
||||
(Self::new(name, Content::Text(text)), rest)
|
||||
};
|
||||
while !rest.is_empty() {
|
||||
let attribute = attribute(rest);
|
||||
let value = attribute.map_or(rest, |a| &rest[a.len()..]);
|
||||
let (text, _, next) = word(value);
|
||||
rest = next;
|
||||
match attribute {
|
||||
Some("type=") => {
|
||||
let mut mime = text;
|
||||
// Its own parameters (`; charset=utf-8`) are not attributes of the field.
|
||||
while !rest.is_empty() && self::attribute(rest).is_none() {
|
||||
let (parameter, _, next) = word(rest);
|
||||
mime.push_str("; ");
|
||||
mime.push_str(¶meter);
|
||||
rest = next;
|
||||
}
|
||||
field.content_type = Some(mime);
|
||||
}
|
||||
Some("filename=") => field.filename = Some(text),
|
||||
Some("headers=") if !text.starts_with(['@', '<']) => field.headers.push(text),
|
||||
Some(_) => return None,
|
||||
// cURL skips what it doesn't know, with a warning.
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Some(field)
|
||||
}
|
||||
|
||||
fn new(name: &str, content: Content) -> Self {
|
||||
Self { name: name.to_owned(), content, filename: None, content_type: None, headers: Vec::new() }
|
||||
}
|
||||
|
||||
pub(super) fn write(&self, out: &mut String) {
|
||||
out.push_str(&format!("--{BOUNDARY}\nContent-Disposition: form-data; name=\"{}\"", escape(&self.name)));
|
||||
if let Some(filename) = &self.filename {
|
||||
out.push_str(&format!("; filename=\"{}\"", escape(filename)));
|
||||
}
|
||||
out.push('\n');
|
||||
if let Some(content_type) = &self.content_type {
|
||||
out.push_str(&format!("Content-Type: {content_type}\n"));
|
||||
}
|
||||
for header in &self.headers {
|
||||
out.push_str(&format!("{header}\n"));
|
||||
}
|
||||
match &self.content {
|
||||
Content::Text(text) => out.push_str(&format!("\n{text}\n")),
|
||||
Content::File(path) => out.push_str(&format!("\n< {path}\n")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The attribute name `s` starts with.
|
||||
fn attribute(s: &str) -> Option<&'static str> {
|
||||
ATTRIBUTES.into_iter().find(|a| s.get(..a.len()).is_some_and(|start| start.eq_ignore_ascii_case(a)))
|
||||
}
|
||||
|
||||
/// A value up to the next `;` or in double quotes: the value, whether it was quoted, and what
|
||||
/// follows the `;`.
|
||||
fn word(s: &str) -> (String, bool, &str) {
|
||||
let s = s.trim_start();
|
||||
if let Some(inner) = s.strip_prefix('"') {
|
||||
let mut value = String::new();
|
||||
let mut chars = inner.char_indices();
|
||||
while let Some((i, c)) = chars.next() {
|
||||
match c {
|
||||
'"' => {
|
||||
let rest = inner[i + 1..].split_once(';').map_or("", |(_, rest)| rest);
|
||||
return (value, true, rest.trim_start());
|
||||
}
|
||||
'\\' if inner[i + 1..].starts_with(['\\', '"']) => value.extend(chars.next().map(|(_, c)| c)),
|
||||
c => value.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
let (value, rest) = s.split_once(';').unwrap_or((s, ""));
|
||||
(value.trim_end().to_owned(), false, rest.trim_start())
|
||||
}
|
||||
|
||||
fn escape(s: &str) -> String {
|
||||
s.replace('"', "%22").replace('\r', "%0D").replace('\n', "%0A")
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
//! A pasted `curl …` command as a request.
|
||||
|
||||
use super::form::{BOUNDARY, Field};
|
||||
use super::{options, words};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
|
||||
/// The request a `curl …` command sends, as `.http` text; `None` when `cmd` is not a cURL
|
||||
/// command, names no URL, or sends something a request file can't express (standard input, several
|
||||
/// files joined into one body).
|
||||
pub fn from_curl(cmd: &str) -> Option<String> {
|
||||
let words = words::split(cmd)?;
|
||||
let (command, args) = words.split_first()?;
|
||||
if command != "curl" {
|
||||
return None;
|
||||
}
|
||||
let mut request = Request::default();
|
||||
for (name, value) in options::parse(args)? {
|
||||
if name == "next" {
|
||||
break;
|
||||
}
|
||||
request.apply(name, value)?;
|
||||
}
|
||||
request.into_http()
|
||||
}
|
||||
|
||||
enum Data {
|
||||
Text(String),
|
||||
File(String),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Request {
|
||||
method: Option<String>,
|
||||
url: Option<String>,
|
||||
globoff: bool,
|
||||
headers: Vec<Header>,
|
||||
/// Headers cURL is told not to send (`-H 'Name:'`), in lower case.
|
||||
removed: Vec<String>,
|
||||
data: Vec<Data>,
|
||||
query: Vec<String>,
|
||||
form: Vec<Field>,
|
||||
upload: Option<String>,
|
||||
json: bool,
|
||||
get: bool,
|
||||
head: bool,
|
||||
}
|
||||
|
||||
struct Header {
|
||||
name: String,
|
||||
value: String,
|
||||
/// Set with `-H`, which wins over the options that set the same header.
|
||||
explicit: bool,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
fn apply(&mut self, name: &str, value: &str) -> Option<()> {
|
||||
match name {
|
||||
"request" => self.method = Some(value.to_owned()),
|
||||
"url" if self.url.is_none() => self.url = Some(value.to_owned()),
|
||||
"globoff" => self.globoff = true,
|
||||
"header" => self.header(value),
|
||||
"data" | "data-ascii" | "data-binary" => self.data.push(data(value)?),
|
||||
"data-raw" => self.data.push(Data::Text(value.to_owned())),
|
||||
"data-urlencode" => self.data.push(Data::Text(urlencode(value)?)),
|
||||
"json" => {
|
||||
// Unlike other data, several `--json` are joined without a `&`.
|
||||
match (self.data.last_mut(), data(value)?) {
|
||||
(Some(Data::Text(last)), Data::Text(more)) => last.push_str(&more),
|
||||
(_, more) => self.data.push(more),
|
||||
}
|
||||
self.json = true;
|
||||
}
|
||||
"url-query" => self.query.push(match value.strip_prefix('+') {
|
||||
Some(raw) => raw.to_owned(),
|
||||
None => urlencode(value)?,
|
||||
}),
|
||||
"form" => self.form.push(Field::parse(value)?),
|
||||
"form-string" => self.form.push(Field::literal(value)?),
|
||||
"upload-file" if matches!(value, "" | "-" | ".") => return None,
|
||||
"upload-file" => self.upload = Some(value.to_owned()),
|
||||
"user" => self.derive("Authorization", basic(value)),
|
||||
"oauth2-bearer" => self.derive("Authorization", format!("Bearer {value}")),
|
||||
// Without a `=` it names a file to read cookies from.
|
||||
"cookie" if value.contains('=') => {
|
||||
match self.headers.iter_mut().find(|h| !h.explicit && h.name == "Cookie") {
|
||||
Some(cookie) => cookie.value = format!("{}; {value}", cookie.value),
|
||||
None => self.derive("Cookie", value.to_owned()),
|
||||
}
|
||||
}
|
||||
"user-agent" => self.derive("User-Agent", value.to_owned()),
|
||||
"referer" => self.derive("Referer", value.strip_suffix(";auto").unwrap_or(value).to_owned()),
|
||||
"get" => self.get = true,
|
||||
"head" => self.head = true,
|
||||
_ => {}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn header(&mut self, line: &str) {
|
||||
let (name, value) = match (line.split_once(':'), line.strip_suffix(';')) {
|
||||
(Some((name, value)), _) if value.trim().is_empty() => {
|
||||
self.removed.push(name.trim().to_ascii_lowercase());
|
||||
return;
|
||||
}
|
||||
(Some((name, value)), _) => (name, value),
|
||||
(None, Some(name)) => (name, ""),
|
||||
// A file of headers.
|
||||
(None, None) => return,
|
||||
};
|
||||
self.headers.push(Header { name: name.trim().to_owned(), value: value.trim().to_owned(), explicit: true });
|
||||
}
|
||||
|
||||
/// The header an option sets; the last such option wins.
|
||||
fn derive(&mut self, name: &str, value: String) {
|
||||
self.headers.retain(|h| h.explicit || h.name != name);
|
||||
if !value.is_empty() {
|
||||
self.headers.push(Header { name: name.to_owned(), value, explicit: false });
|
||||
}
|
||||
}
|
||||
|
||||
fn into_http(mut self) -> Option<String> {
|
||||
let mut url = self.url.take()?;
|
||||
if !self.globoff {
|
||||
for bracket in ['[', ']', '{', '}'] {
|
||||
url = url.replace(&format!("\\{bracket}"), &bracket.to_string());
|
||||
}
|
||||
}
|
||||
let has_body = !self.form.is_empty() || (!self.data.is_empty() && !self.get);
|
||||
let default_method = match (self.head, &self.upload) {
|
||||
(true, _) => "HEAD",
|
||||
(_, Some(_)) => "PUT",
|
||||
_ if has_body => "POST",
|
||||
_ => "GET",
|
||||
};
|
||||
let method = self.method.take().unwrap_or_else(|| default_method.to_owned());
|
||||
if let Some(path) = &self.upload {
|
||||
url = upload_url(url, path);
|
||||
}
|
||||
let mut query = Vec::new();
|
||||
if self.get {
|
||||
for data in std::mem::take(&mut self.data) {
|
||||
match data {
|
||||
Data::Text(text) => query.push(text),
|
||||
Data::File(_) => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
query.append(&mut self.query);
|
||||
if !query.is_empty() {
|
||||
url = with_query(&url, &query.join("&"));
|
||||
}
|
||||
let body = self.body()?;
|
||||
let headers: Vec<&Header> = self
|
||||
.headers
|
||||
.iter()
|
||||
.filter(|h| h.explicit || !(self.sets(&h.name) || self.removed.contains(&h.name.to_ascii_lowercase())))
|
||||
.collect();
|
||||
let mut out = format!("{method} {url}\n");
|
||||
for header in headers {
|
||||
out.push_str(format!("{}: {}", header.name, header.value).trim_end());
|
||||
out.push('\n');
|
||||
}
|
||||
if let Some(body) = body {
|
||||
out.push('\n');
|
||||
out.push_str(&body);
|
||||
out.push('\n');
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Whether a `-H` option sets header `name`.
|
||||
fn sets(&self, name: &str) -> bool {
|
||||
self.headers.iter().any(|h| h.explicit && h.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// The body text, with the headers it implies added.
|
||||
fn body(&mut self) -> Option<Option<String>> {
|
||||
if !self.form.is_empty() {
|
||||
self.headers.retain(|h| !h.name.eq_ignore_ascii_case("content-type"));
|
||||
self.derive("Content-Type", format!("multipart/form-data; boundary={BOUNDARY}"));
|
||||
let mut text = String::new();
|
||||
for field in &self.form {
|
||||
field.write(&mut text);
|
||||
}
|
||||
text.push_str(&format!("--{BOUNDARY}--"));
|
||||
return Some(Some(text));
|
||||
}
|
||||
if let Some(path) = &self.upload {
|
||||
return Some(Some(format!("< {path}")));
|
||||
}
|
||||
if self.data.is_empty() {
|
||||
return Some(None);
|
||||
}
|
||||
if self.json {
|
||||
self.derive("Content-Type", "application/json".to_owned());
|
||||
self.derive("Accept", "application/json".to_owned());
|
||||
} else {
|
||||
self.derive("Content-Type", "application/x-www-form-urlencoded".to_owned());
|
||||
}
|
||||
if let [Data::File(path)] = self.data.as_slice() {
|
||||
return Some(Some(format!("< {path}")));
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
for data in &self.data {
|
||||
match data {
|
||||
Data::Text(text) => parts.push(text.as_str()),
|
||||
// A file is a line of its own in a request file, so it can't be joined with `&`.
|
||||
Data::File(_) => return None,
|
||||
}
|
||||
}
|
||||
Some(Some(parts.join("&")))
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of `-d`: text, or `@file`. `None` for standard input.
|
||||
fn data(value: &str) -> Option<Data> {
|
||||
match value.strip_prefix('@') {
|
||||
Some("" | "-") => None,
|
||||
Some(path) => Some(Data::File(path.to_owned())),
|
||||
None => Some(Data::Text(value.to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `content`, `=content` or `name=content`, with the content encoded; `None` for `@file` and
|
||||
/// `name@file`.
|
||||
fn urlencode(value: &str) -> Option<String> {
|
||||
let (name, content) = match value.split_once('=') {
|
||||
Some((name, content)) => (name, content),
|
||||
None if value.contains('@') => return None,
|
||||
None => ("", value),
|
||||
};
|
||||
let mut out = String::new();
|
||||
if !name.is_empty() {
|
||||
out.push_str(name);
|
||||
out.push('=');
|
||||
}
|
||||
for byte in content.bytes() {
|
||||
match byte {
|
||||
b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => out.push(byte as char),
|
||||
b' ' => out.push('+'),
|
||||
_ => out.push_str(&format!("%{byte:02X}")),
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// `Basic user password`, which is encoded when the request is sent; encoded here when it can't be
|
||||
/// written as two words.
|
||||
fn basic(user: &str) -> String {
|
||||
let (name, password) = user.split_once(':').unwrap_or((user, ""));
|
||||
let is_word = |s: &str| !s.is_empty() && !s.contains(char::is_whitespace);
|
||||
if is_word(name) && is_word(password) {
|
||||
format!("Basic {name} {password}")
|
||||
} else {
|
||||
format!("Basic {}", STANDARD.encode(format!("{name}:{password}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// An upload to a folder goes to the file of the same name in it.
|
||||
fn upload_url(url: String, path: &str) -> String {
|
||||
let end = url.find(['?', '#']).unwrap_or(url.len());
|
||||
let (target, rest) = url.split_at(end);
|
||||
let after_scheme = target.split_once("://").map_or(target, |(_, after)| after);
|
||||
let slash = match after_scheme.rsplit_once('/') {
|
||||
None => "/",
|
||||
Some((_, "")) => "",
|
||||
Some(_) => return url,
|
||||
};
|
||||
let base = path.rsplit(['/', '\\']).next().unwrap_or(path);
|
||||
format!("{target}{slash}{base}{rest}")
|
||||
}
|
||||
|
||||
fn with_query(url: &str, query: &str) -> String {
|
||||
let (target, fragment) = url.split_at(url.find('#').unwrap_or(url.len()));
|
||||
let separator = match target.split_once('?') {
|
||||
None => "?",
|
||||
Some((_, "")) => "",
|
||||
Some(_) => "&",
|
||||
};
|
||||
format!("{target}{separator}{query}{fragment}")
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! cURL's command-line options: which ones take a value, and clusters of short ones (`-sXPOST`).
|
||||
|
||||
/// The options of `args` in order as `(long name, value)`, flags with an empty value and URLs as
|
||||
/// `url`. `None` when an option lacks its value.
|
||||
pub(super) fn parse(args: &[String]) -> Option<Vec<(&str, &str)>> {
|
||||
let mut out = Vec::new();
|
||||
let mut args = args.iter().map(String::as_str);
|
||||
while let Some(arg) = args.next() {
|
||||
if arg == "--" {
|
||||
out.extend(args.by_ref().map(|url| ("url", url)));
|
||||
} else if let Some(long) = arg.strip_prefix("--") {
|
||||
// cURL itself has no `--opt=value`, but it is often written.
|
||||
let (name, inline) = match long.split_once('=') {
|
||||
Some((name, value)) if LONG_WITH_VALUE.contains(&name) => (name, Some(value)),
|
||||
_ => (long, None),
|
||||
};
|
||||
let value = match inline {
|
||||
Some(value) => value,
|
||||
None if LONG_WITH_VALUE.contains(&name) => args.next()?,
|
||||
None => "",
|
||||
};
|
||||
out.push((name, value));
|
||||
} else if let Some(cluster) = arg.strip_prefix('-').filter(|c| !c.is_empty()) {
|
||||
for (i, flag) in cluster.char_indices() {
|
||||
if !SHORT_WITH_VALUE.contains(flag) {
|
||||
out.push((long_name(flag), ""));
|
||||
continue;
|
||||
}
|
||||
let rest = &cluster[i + flag.len_utf8()..];
|
||||
out.push((long_name(flag), if rest.is_empty() { args.next()? } else { rest }));
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
out.push(("url", arg));
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The long name of a short option that says something about the request; empty for the others.
|
||||
fn long_name(flag: char) -> &'static str {
|
||||
match flag {
|
||||
'A' => "user-agent",
|
||||
'b' => "cookie",
|
||||
'd' => "data",
|
||||
'e' => "referer",
|
||||
'F' => "form",
|
||||
'G' => "get",
|
||||
'H' => "header",
|
||||
'I' => "head",
|
||||
'T' => "upload-file",
|
||||
'u' => "user",
|
||||
'X' => "request",
|
||||
':' => "next",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
const SHORT_WITH_VALUE: &str = "ACDEFHKPQTUXYbcdemortuwxyz";
|
||||
|
||||
/// From `curl --help all`, including options newer than the cURL most systems ship.
|
||||
#[rustfmt::skip]
|
||||
const LONG_WITH_VALUE: &[&str] = &[
|
||||
"abstract-unix-socket", "alt-svc", "aws-sigv4", "cacert", "capath", "cert", "cert-type", "ciphers", "config",
|
||||
"connect-timeout", "connect-to", "continue-at", "cookie", "cookie-jar", "create-file-mode", "crlfile", "curves",
|
||||
"data", "data-ascii", "data-binary", "data-raw", "data-urlencode", "delegation", "dns-interface",
|
||||
"dns-ipv4-addr", "dns-ipv6-addr", "dns-servers", "doh-url", "dump-header", "ech", "egd-file", "engine",
|
||||
"etag-compare", "etag-save", "expect100-timeout", "form", "form-string", "ftp-account",
|
||||
"ftp-alternative-to-user", "ftp-method", "ftp-port", "ftp-ssl-ccc-mode", "happy-eyeballs-timeout-ms",
|
||||
"haproxy-clientip", "header", "hostpubmd5", "hostpubsha256", "hsts", "interface", "ip-tos", "ipfs-gateway",
|
||||
"json", "keepalive-cnt", "keepalive-time", "key", "key-type", "knownhosts", "krb", "libcurl", "limit-rate",
|
||||
"local-port", "login-options", "mail-auth", "mail-from", "mail-rcpt", "max-filesize", "max-redirs", "max-time",
|
||||
"netrc-file", "noproxy", "oauth2-bearer", "output", "output-dir", "parallel-max", "parallel-max-host", "pass",
|
||||
"pinnedpubkey", "preproxy", "proto", "proto-default", "proto-redir", "proxy", "proxy-cacert", "proxy-capath",
|
||||
"proxy-cert", "proxy-cert-type", "proxy-ciphers", "proxy-crlfile", "proxy-header", "proxy-key",
|
||||
"proxy-key-type", "proxy-pass", "proxy-pinnedpubkey", "proxy-service-name", "proxy-tls13-ciphers",
|
||||
"proxy-tlsauthtype", "proxy-tlspassword", "proxy-tlsuser", "proxy-user", "proxy1.0", "pubkey", "quote",
|
||||
"random-file", "range", "rate", "referer", "request", "request-target", "resolve", "retry", "retry-delay",
|
||||
"retry-max-time", "sasl-authzid", "service-name", "sigalgs", "socks4", "socks4a", "socks5",
|
||||
"socks5-gssapi-service", "socks5-hostname", "speed-limit", "speed-time", "stderr", "telnet-option",
|
||||
"tftp-blksize", "time-cond", "tls-max", "tls13-ciphers", "tlsauthtype", "tlspassword", "tlsuser", "trace",
|
||||
"trace-ascii", "trace-config", "unix-socket", "upload-file", "upload-flags", "url", "url-query", "user",
|
||||
"user-agent", "variable", "vlan-priority", "write-out",
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse;
|
||||
|
||||
#[test]
|
||||
fn clusters_and_values() {
|
||||
let cases: &[(&str, &[(&str, &str)])] = &[
|
||||
("-sX POST u", &[("", ""), ("request", "POST"), ("url", "u")]),
|
||||
("-sXPUT u", &[("", ""), ("request", "PUT"), ("url", "u")]),
|
||||
("-kd@f -I u", &[("", ""), ("data", "@f"), ("head", ""), ("url", "u")]),
|
||||
("-D h.txt --dump-header h u", &[("", "h.txt"), ("dump-header", "h"), ("url", "u")]),
|
||||
("-X=A u", &[("request", "=A"), ("url", "u")]),
|
||||
("--url=u --compressed=x", &[("url", "u"), ("compressed=x", "")]),
|
||||
("-d x -- -u", &[("data", "x"), ("url", "-u")]),
|
||||
];
|
||||
for (args, options) in cases {
|
||||
let args: Vec<String> = args.split(' ').map(str::to_owned).collect();
|
||||
assert_eq!(parse(&args).as_deref(), Some(*options), "{args:?}");
|
||||
}
|
||||
assert_eq!(parse(&["-X".to_owned()]), None);
|
||||
assert_eq!(parse(&["--max-time".to_owned()]), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
//! Splits a pasted command into words, as the shell it was written for does.
|
||||
|
||||
/// The words of the command: POSIX quoting (with bash's `$'…'`), or `cmd.exe` quoting when a caret
|
||||
/// escapes a quote or continues a line. Output redirections and pipes end the command. `None` for an
|
||||
/// unclosed quote, or when another command follows.
|
||||
pub(super) fn split(cmd: &str) -> Option<Vec<String>> {
|
||||
let cmd = cmd.trim().replace("\r\n", "\n");
|
||||
let chars: Vec<char> = cmd.chars().collect();
|
||||
let mut words = Words::default();
|
||||
let mut i = 0;
|
||||
while let Some(&c) = chars.get(i) {
|
||||
i += 1;
|
||||
let next = chars.get(i).copied();
|
||||
match c {
|
||||
'^' if matches!(next, Some('"' | '\n')) => return split_cmd(&chars),
|
||||
'\\' | '`' if next == Some('\n') => i += 1,
|
||||
'\'' => {
|
||||
let len = chars[i..].iter().position(|&c| c == '\'')?;
|
||||
words.push_str(&chars[i..i + len]);
|
||||
i += len + 1;
|
||||
}
|
||||
'$' if next == Some('\'') => i = ansi_c(&chars, i + 1, &mut words)?,
|
||||
'$' if next == Some('"') => {}
|
||||
'"' => {
|
||||
words.in_word = true;
|
||||
loop {
|
||||
let c = *chars.get(i)?;
|
||||
let next = chars.get(i + 1).copied();
|
||||
i += 1;
|
||||
match (c, next) {
|
||||
('"', _) => break,
|
||||
('\\', Some('\n')) => i += 1,
|
||||
('\\', Some(escaped @ ('"' | '\\' | '$' | '`'))) => {
|
||||
words.push(escaped);
|
||||
i += 1;
|
||||
}
|
||||
_ => words.push(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
'\\' => {
|
||||
words.in_word = true;
|
||||
words.current.extend(next);
|
||||
i += 1;
|
||||
}
|
||||
c if c.is_whitespace() => words.end(),
|
||||
c => match operator(c, next, words.in_word) {
|
||||
Operator::None => words.push(c),
|
||||
Operator::Output => break,
|
||||
Operator::Separator => return chars[i..].iter().all(|c| c.is_whitespace()).then(|| words.finish()),
|
||||
},
|
||||
}
|
||||
}
|
||||
Some(words.finish())
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Words {
|
||||
words: Vec<String>,
|
||||
current: String,
|
||||
in_word: bool,
|
||||
}
|
||||
|
||||
impl Words {
|
||||
fn push(&mut self, c: char) {
|
||||
self.in_word = true;
|
||||
self.current.push(c);
|
||||
}
|
||||
|
||||
fn push_str(&mut self, chars: &[char]) {
|
||||
self.in_word = true;
|
||||
self.current.extend(chars);
|
||||
}
|
||||
|
||||
fn end(&mut self) {
|
||||
if std::mem::take(&mut self.in_word) {
|
||||
self.words.push(std::mem::take(&mut self.current));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Vec<String> {
|
||||
self.end();
|
||||
self.words
|
||||
}
|
||||
}
|
||||
|
||||
enum Operator {
|
||||
None,
|
||||
/// A pipe or a redirection of the output.
|
||||
Output,
|
||||
/// `;`, `&` or `&&`.
|
||||
Separator,
|
||||
}
|
||||
|
||||
/// The unquoted `c` as a shell operator. Inside a word `;`, `&`, `<` and `>` are kept: URLs and
|
||||
/// placeholders are often pasted unquoted.
|
||||
fn operator(c: char, next: Option<char>, in_word: bool) -> Operator {
|
||||
let ends_word = next.is_none_or(char::is_whitespace);
|
||||
match c {
|
||||
'|' => Operator::Output,
|
||||
'>' | '<' if !in_word => Operator::Output,
|
||||
';' if ends_word => Operator::Separator,
|
||||
'&' if ends_word || !in_word => Operator::Separator,
|
||||
_ => Operator::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads bash's `$'…'` from `i` (after its opening quote); the index after the closing one.
|
||||
fn ansi_c(chars: &[char], mut i: usize, words: &mut Words) -> Option<usize> {
|
||||
// `\xHH` and octal escapes are bytes; several may make up one character.
|
||||
let mut bytes: Vec<u8> = Vec::new();
|
||||
loop {
|
||||
let c = *chars.get(i)?;
|
||||
i += 1;
|
||||
if c == '\'' {
|
||||
break;
|
||||
}
|
||||
if c != '\\' {
|
||||
push_char(&mut bytes, c);
|
||||
continue;
|
||||
}
|
||||
let escape = *chars.get(i)?;
|
||||
i += 1;
|
||||
let (radix, max_digits) = match escape {
|
||||
'x' => (16, 2),
|
||||
'u' => (16, 4),
|
||||
'U' => (16, 8),
|
||||
'0'..='7' => {
|
||||
i -= 1;
|
||||
(8, 3)
|
||||
}
|
||||
_ => {
|
||||
let c = match escape {
|
||||
'a' => '\x07',
|
||||
'b' => '\x08',
|
||||
'e' | 'E' => '\x1b',
|
||||
'f' => '\x0c',
|
||||
'n' => '\n',
|
||||
'r' => '\r',
|
||||
't' => '\t',
|
||||
'v' => '\x0b',
|
||||
'c' => {
|
||||
let control = *chars.get(i)?;
|
||||
i += 1;
|
||||
(control.to_ascii_uppercase() as u8 & 0x1f) as char
|
||||
}
|
||||
'\\' | '\'' | '"' | '?' => escape,
|
||||
_ => {
|
||||
bytes.push(b'\\');
|
||||
escape
|
||||
}
|
||||
};
|
||||
push_char(&mut bytes, c);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let digits: String = chars[i..].iter().take(max_digits).take_while(|c| c.is_digit(radix)).collect();
|
||||
i += digits.len();
|
||||
match u32::from_str_radix(&digits, radix) {
|
||||
Err(_) => bytes.extend([b'\\', escape as u8]),
|
||||
Ok(code) if matches!(escape, 'u' | 'U') => push_char(&mut bytes, char::from_u32(code)?),
|
||||
Ok(byte) => bytes.push(byte as u8),
|
||||
}
|
||||
}
|
||||
words.in_word = true;
|
||||
words.current.push_str(&String::from_utf8_lossy(&bytes));
|
||||
Some(i)
|
||||
}
|
||||
|
||||
fn push_char(bytes: &mut Vec<u8>, c: char) {
|
||||
bytes.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
|
||||
}
|
||||
|
||||
/// `cmd.exe` removes the carets that escape a character outside quotes, then the program splits
|
||||
/// what is left by the rules of the Microsoft C runtime.
|
||||
fn split_cmd(chars: &[char]) -> Option<Vec<String>> {
|
||||
let mut line = Vec::new();
|
||||
let mut quoted = false;
|
||||
let mut i = 0;
|
||||
while let Some(&c) = chars.get(i) {
|
||||
i += 1;
|
||||
match c {
|
||||
'"' => quoted = !quoted,
|
||||
'^' if !quoted => {
|
||||
// After a continued line the first character is taken as it is, carets included.
|
||||
if chars.get(i) == Some(&'\n') {
|
||||
i += 1;
|
||||
}
|
||||
line.extend(chars.get(i));
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
_ if !quoted => {
|
||||
let in_word = line.last().is_some_and(|c: &char| !c.is_whitespace());
|
||||
match operator(c, chars.get(i).copied(), in_word) {
|
||||
Operator::None => {}
|
||||
Operator::Output => break,
|
||||
Operator::Separator if chars[i..].iter().all(|c| c.is_whitespace()) => break,
|
||||
Operator::Separator => return None,
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
line.push(c);
|
||||
}
|
||||
split_crt(&line)
|
||||
}
|
||||
|
||||
fn split_crt(chars: &[char]) -> Option<Vec<String>> {
|
||||
let mut words = Words::default();
|
||||
let mut quoted = false;
|
||||
let mut i = 0;
|
||||
while let Some(&c) = chars.get(i) {
|
||||
i += 1;
|
||||
match c {
|
||||
'\\' => {
|
||||
let run = 1 + chars[i..].iter().take_while(|&&c| c == '\\').count();
|
||||
i += run - 1;
|
||||
let before_quote = chars.get(i) == Some(&'"');
|
||||
words.push_str(&vec!['\\'; if before_quote { run / 2 } else { run }]);
|
||||
if before_quote && run % 2 == 1 {
|
||||
words.push('"');
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
'"' if quoted && chars.get(i) == Some(&'"') => {
|
||||
words.push('"');
|
||||
i += 1;
|
||||
}
|
||||
'"' => {
|
||||
words.in_word = true;
|
||||
quoted = !quoted;
|
||||
}
|
||||
c if c.is_whitespace() && !quoted => words.end(),
|
||||
c => words.push(c),
|
||||
}
|
||||
}
|
||||
(!quoted).then(|| words.finish())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::split;
|
||||
|
||||
#[test]
|
||||
fn posix_words() {
|
||||
let cases: &[(&str, &[&str])] = &[
|
||||
(r#"a 'b c'"d\"e\$f"\ g"#, &["a", "b cd\"e$f g"]),
|
||||
("a \\\n b \\\r\n c `\n d", &["a", "b", "c", "d"]),
|
||||
("a \"b\\\nc\"", &["a", "bc"]),
|
||||
("a '' \"\"", &["a", "", ""]),
|
||||
(r"a $'it\'s\n\t\\ \u0021\x41\101\U1f600 \q'", &["a", "it's\n\t\\ !AA\u{1f600} \\q"]),
|
||||
(r"a $'\xc3\xa9' $'\cA'x", &["a", "é", "\u{1}x"]),
|
||||
(r#"a $"b" $c d$"#, &["a", "b", "$c", "d$"]),
|
||||
("a http://h/?x=1&y=2;z=<id> b", &["a", "http://h/?x=1&y=2;z=<id>", "b"]),
|
||||
("a b | jq .x", &["a", "b"]),
|
||||
("a b > out.json", &["a", "b"]),
|
||||
("a b;", &["a", "b"]),
|
||||
];
|
||||
for (cmd, words) in cases {
|
||||
assert_eq!(split(cmd).as_deref().unwrap_or_default(), *words, "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmd_words() {
|
||||
let cases: &[(&str, &[&str])] = &[
|
||||
// What Chrome and Firefox escape a JSON body to.
|
||||
(r#"a ^"^{^"^"b^"^":^"^"c d^"^"^}^""#, &["a", r#"{"b":"c d"}"#]),
|
||||
(r#"a ^"^{^\^"b^\^":1^}^""#, &["a", r#"{"b":1}"#]),
|
||||
("a ^\n ^\"b^\" ^\r\n -c", &["a", "b", "-c"]),
|
||||
("a ^\"one^\n\ntwo^\"", &["a", "one\ntwo"]),
|
||||
(r#"a ^"x^%^41^&y^|z^" "q^r" 'b c'"#, &["a", "x%41&y|z", "q^r", "'b", "c'"]),
|
||||
(r#"a ^"c:\dir\\^" ^"\\x^""#, &["a", r"c:\dir\", r"\\x"]),
|
||||
("a ^\"b^\" | jq", &["a", "b"]),
|
||||
];
|
||||
for (cmd, words) in cases {
|
||||
assert_eq!(split(cmd).as_deref().unwrap_or_default(), *words, "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unclosed_quotes_and_several_commands_are_rejected() {
|
||||
for cmd in ["a 'b", "a \"b", "a $'b", "a ^\"b", "a b ;\na c", "a b && a c", "a ^\"b^\" &\r\na c"] {
|
||||
assert_eq!(split(cmd), None, "{cmd}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
//! Preparing (substitution, body includes) and executing requests.
|
||||
|
||||
use crate::body::RequestBody;
|
||||
use crate::client::{describe, with_scheme};
|
||||
use crate::env::{Environments, Resolver};
|
||||
use crate::parse::{BodyPart, RawRequest};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -34,7 +37,8 @@ pub struct PreparedRequest {
|
||||
pub method: String,
|
||||
pub url: String,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: Option<String>,
|
||||
#[specta(type = Option<String>)]
|
||||
pub body: Option<RequestBody>,
|
||||
}
|
||||
|
||||
/// One followed redirect: the response and the `Location` it pointed to.
|
||||
@@ -80,12 +84,29 @@ pub fn prepare(
|
||||
let resolver = Resolver { file_vars, env: envs.variables(env), env_first: env.is_some() };
|
||||
let mut missing = BTreeSet::new();
|
||||
let url = resolver.substitute(&raw.block.url, &mut missing);
|
||||
let headers: Vec<(String, String)> =
|
||||
raw.headers.iter().map(|(k, v)| (k.clone(), resolver.substitute(v, &mut missing))).collect();
|
||||
let mut body_lines: Vec<String> = Vec::new();
|
||||
for part in &raw.body {
|
||||
let mut substitute = |text: &str| resolver.substitute(text, &mut missing);
|
||||
let headers: Vec<(String, String)> = raw
|
||||
.headers
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
let basic = k.eq_ignore_ascii_case("authorization").then(|| basic_credentials(v, &mut substitute));
|
||||
(k.clone(), basic.flatten().unwrap_or_else(|| substitute(v)))
|
||||
})
|
||||
.collect();
|
||||
// Multipart bodies delimit parts with CRLF per RFC 2046 §5.1; joining
|
||||
// with bare LF leaves servers (e.g. Tomcat) unable to find the boundary.
|
||||
let is_multipart = headers
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
|
||||
.is_some_and(|(_, v)| v.to_ascii_lowercase().starts_with("multipart/"));
|
||||
let eol = if is_multipart { "\r\n" } else { "\n" };
|
||||
let mut body = RequestBody::default();
|
||||
for (i, part) in raw.body.iter().enumerate() {
|
||||
if i > 0 {
|
||||
body.push_text(eol);
|
||||
}
|
||||
match part {
|
||||
BodyPart::Text(t) => body_lines.push(resolver.substitute(t, &mut missing)),
|
||||
BodyPart::Text(t) => body.push_text(&resolver.substitute(t, &mut missing)),
|
||||
BodyPart::File(p) => {
|
||||
let p = resolver.substitute(p, &mut missing);
|
||||
let path = match base_dir {
|
||||
@@ -94,7 +115,7 @@ pub fn prepare(
|
||||
};
|
||||
let bytes = std::fs::read(&path)
|
||||
.map_err(|e| IdeError::not_found(format!("cannot read body file {}: {e}", path.display())))?;
|
||||
body_lines.push(String::from_utf8_lossy(&bytes).trim_end_matches(['\r', '\n']).to_owned());
|
||||
body.push_file(&p, bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,22 +133,37 @@ pub fn prepare(
|
||||
} else {
|
||||
with_scheme(&url)
|
||||
};
|
||||
// Multipart bodies delimit parts with CRLF per RFC 2046 §5.1; joining
|
||||
// with bare LF leaves servers (e.g. Tomcat) unable to find the boundary.
|
||||
let is_multipart = headers
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
|
||||
.is_some_and(|(_, v)| v.to_ascii_lowercase().starts_with("multipart/"));
|
||||
let eol = if is_multipart { "\r\n" } else { "\n" };
|
||||
Ok(PreparedRequest {
|
||||
name: raw.block.name.clone(),
|
||||
method: raw.block.method.clone(),
|
||||
url,
|
||||
headers,
|
||||
body: (!body_lines.is_empty()).then(|| body_lines.join(eol)),
|
||||
body: (!raw.body.is_empty()).then_some(body),
|
||||
})
|
||||
}
|
||||
|
||||
/// `Basic user password` encoded for the wire, as IntelliJ's HTTP Client does. Split before
|
||||
/// substitution: the value of a variable may contain spaces.
|
||||
fn basic_credentials(value: &str, mut substitute: impl FnMut(&str) -> String) -> Option<String> {
|
||||
let mut words = vec![String::new()];
|
||||
let mut rest = value;
|
||||
while let Some(c) = rest.chars().next() {
|
||||
let variable = rest.starts_with("{{").then(|| rest.find("}}")).flatten().map(|end| end + 2);
|
||||
let (text, after) = rest.split_at(variable.unwrap_or(c.len_utf8()));
|
||||
rest = after;
|
||||
match words.last_mut() {
|
||||
Some(word) if !c.is_whitespace() => word.push_str(text),
|
||||
Some(word) if word.is_empty() => {}
|
||||
_ => words.push(String::new()),
|
||||
}
|
||||
}
|
||||
let [scheme, user, password] = words.as_slice() else { return None };
|
||||
if !substitute(scheme).eq_ignore_ascii_case("basic") {
|
||||
return None;
|
||||
}
|
||||
Some(format!("Basic {}", STANDARD.encode(format!("{}:{}", substitute(user), substitute(password)))))
|
||||
}
|
||||
|
||||
fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool {
|
||||
if let Some(ct) = content_type {
|
||||
let ct = ct.to_ascii_lowercase();
|
||||
@@ -159,7 +195,7 @@ fn request_to(
|
||||
client: &reqwest::Client,
|
||||
method: &reqwest::Method,
|
||||
req: &PreparedRequest,
|
||||
body: Option<&str>,
|
||||
body: Option<&RequestBody>,
|
||||
original: &reqwest::Url,
|
||||
url: &reqwest::Url,
|
||||
) -> IdeResult<reqwest::Request> {
|
||||
@@ -171,7 +207,7 @@ fn request_to(
|
||||
}
|
||||
}
|
||||
if let Some(body) = body {
|
||||
builder = builder.body(body.to_owned());
|
||||
builder = builder.body(body.to_bytes());
|
||||
}
|
||||
builder.build().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))
|
||||
}
|
||||
@@ -203,12 +239,12 @@ pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeRe
|
||||
let original = req.url.parse::<reqwest::Url>().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))?;
|
||||
let mut url = original.clone();
|
||||
let mut method = method;
|
||||
let mut body = req.body.clone();
|
||||
let mut body = req.body.as_ref();
|
||||
let mut redirects = Vec::new();
|
||||
let started = Instant::now();
|
||||
let mut response;
|
||||
loop {
|
||||
let request = request_to(&client, &method, req, body.as_deref(), &original, &url)?;
|
||||
let request = request_to(&client, &method, req, body, &original, &url)?;
|
||||
response = send(&client, request, cancel).await?;
|
||||
let status = response.status();
|
||||
if redirects.len() >= MAX_REDIRECTS || !REDIRECT_STATUSES.contains(&status.as_u16()) {
|
||||
@@ -287,7 +323,7 @@ mod tests {
|
||||
assert_eq!(p.url, "https://api.test/items");
|
||||
assert_eq!(p.headers, vec![("Authorization".into(), "Bearer abc".into())]);
|
||||
// Included files are inserted verbatim (no substitution inside them).
|
||||
assert_eq!(p.body.as_deref(), Some("{\"id\": \"{{id}}\"}"));
|
||||
assert_eq!(p.body, Some("{\"id\": \"{{id}}\"}\n".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -302,6 +338,28 @@ mod tests {
|
||||
assert_eq!(url(None), "http://localhost:8080/v1/x?env=none");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic_authorization_is_encoded() {
|
||||
let envs =
|
||||
Environments::from_json(r#"{"dev":{"user":"bob","password":"se cret","encoded":"Ym9iOng="}}"#, "").unwrap();
|
||||
for (header, sent) in [
|
||||
("Authorization: Basic bob secret", "Basic Ym9iOnNlY3JldA=="),
|
||||
("authorization: basic bob secret", "Basic Ym9iOnNlY3JldA=="),
|
||||
("Authorization: Basic {{user}} {{ password }}", "Basic Ym9iOnNlIGNyZXQ="),
|
||||
("Authorization: Basic {{encoded}}", "Basic Ym9iOng="),
|
||||
("Authorization: Basic Ym9iOng=", "Basic Ym9iOng="),
|
||||
("Authorization: Bearer a b", "Bearer a b"),
|
||||
("X-Other: Basic bob secret", "Basic bob secret"),
|
||||
] {
|
||||
let f = parse(&format!("GET https://api.test/\n{header}\n"));
|
||||
let p = prepare(&f.requests[0], &f.variables, &envs, Some("dev"), None).unwrap();
|
||||
assert_eq!(p.headers[0].1, sent, "{header}");
|
||||
}
|
||||
let f = parse("GET https://api.test/\nAuthorization: Basic {{user}} {{nope}}\n");
|
||||
let err = prepare(&f.requests[0], &f.variables, &envs, Some("dev"), None).unwrap_err();
|
||||
assert!(err.message.contains("nope"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_unresolved_variables() {
|
||||
let f = parse("GET https://{{host}}/x\n");
|
||||
@@ -315,14 +373,14 @@ mod tests {
|
||||
"POST https://api.test/upload\nContent-Type: multipart/form-data; boundary=xyz\n\n--xyz\nfield\n--xyz--\n",
|
||||
);
|
||||
let p = prepare(&f.requests[0], &f.variables, &Environments::default(), None, None).unwrap();
|
||||
assert_eq!(p.body.as_deref(), Some("--xyz\r\nfield\r\n--xyz--"));
|
||||
assert_eq!(p.body, Some("--xyz\r\nfield\r\n--xyz--".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_multipart_bodies_join_lines_with_lf() {
|
||||
let f = parse("POST https://api.test/x\nContent-Type: application/json\n\n{\n\"a\": 1\n}\n");
|
||||
let p = prepare(&f.requests[0], &f.variables, &Environments::default(), None, None).unwrap();
|
||||
assert_eq!(p.body.as_deref(), Some("{\n\"a\": 1\n}"));
|
||||
assert_eq!(p.body, Some("{\n\"a\": 1\n}".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -445,7 +503,7 @@ mod tests {
|
||||
assert_eq!(headers.lines().next().unwrap(), "POST /echo?id=123456789012345678901234567890 HTTP/1.1");
|
||||
assert!(headers.lines().any(|line| line.eq_ignore_ascii_case("x-exact-amount: 1.0000000000000000002")));
|
||||
assert_eq!(body, expected);
|
||||
assert_eq!(exchange.request.body.as_deref(), Some(expected));
|
||||
assert_eq!(exchange.request.body, Some(expected.into()));
|
||||
assert_eq!(exchange.response.unwrap().body.as_deref(), Some(expected));
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! timed) and [`history`] keeps the responses. [`client`] builds every HTTP client
|
||||
//! of the backend, with the proxy of System Settings › HTTP Proxy.
|
||||
|
||||
mod body;
|
||||
pub mod client;
|
||||
pub mod curl;
|
||||
pub mod env;
|
||||
@@ -17,6 +18,7 @@ pub use pac::system_pac_route;
|
||||
pub mod parse;
|
||||
pub mod tunnel;
|
||||
|
||||
pub use body::RequestBody;
|
||||
pub use env::Environments;
|
||||
pub use exec::{HttpResponse, PreparedRequest};
|
||||
pub use history::{History, HistoryEntry, HttpExchange};
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
//! A pasted cURL command, converted and run by the HTTP Client, sends what the real cURL sends.
|
||||
#![cfg(unix)]
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_http::RunInput;
|
||||
use ide_http::curl::from_curl;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Received {
|
||||
request_line: String,
|
||||
headers: Vec<String>,
|
||||
body: String,
|
||||
}
|
||||
|
||||
async fn receive(listener: &TcpListener) -> Received {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = Vec::new();
|
||||
let mut buffer = [0u8; 4096];
|
||||
loop {
|
||||
let read = socket.read(&mut buffer).await.unwrap();
|
||||
assert!(read > 0, "request ended before its body");
|
||||
request.extend_from_slice(&buffer[..read]);
|
||||
let text = String::from_utf8(request.clone()).unwrap();
|
||||
let Some((head, body)) = text.split_once("\r\n\r\n") else { continue };
|
||||
let (request_line, lines) = head.split_once("\r\n").unwrap();
|
||||
let mut headers: Vec<String> = lines.lines().map(str::to_owned).collect();
|
||||
let header = |name: &str| {
|
||||
headers.iter().find_map(|h| {
|
||||
let (n, v) = h.split_once(':')?;
|
||||
n.eq_ignore_ascii_case(name).then(|| v.trim().to_owned())
|
||||
})
|
||||
};
|
||||
if body.len() < header("content-length").map_or(0, |l| l.parse().unwrap()) {
|
||||
continue;
|
||||
}
|
||||
socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await.unwrap();
|
||||
// The boundary is up to the sender, and so is the line break after the last one.
|
||||
let boundary = header("content-type").and_then(|v| Some(v.split_once("boundary=")?.1.to_owned()));
|
||||
let unify = |s: &str| boundary.as_ref().map_or(s.to_owned(), |b| s.replace(b, "B").trim_end().to_owned());
|
||||
headers = headers
|
||||
.iter()
|
||||
.map(|h| {
|
||||
let (name, value) = h.split_once(':').unwrap();
|
||||
let name = name.to_ascii_lowercase();
|
||||
let mut value = unify(value.trim());
|
||||
// curl releases join several -b with `;` or `; `.
|
||||
if name == "cookie" {
|
||||
value = value.split(';').map(str::trim).collect::<Vec<_>>().join("; ");
|
||||
}
|
||||
format!("{name}: {value}").trim_end().to_owned()
|
||||
})
|
||||
// What each client sends on its own.
|
||||
.filter(|h| {
|
||||
!["host:", "content-length:", "accept: */*", "user-agent: curl/"].iter().any(|p| h.starts_with(p))
|
||||
})
|
||||
.filter(|h| !h.starts_with("accept-encoding:") && !h.starts_with("user-agent: OpenIDEA"))
|
||||
.collect();
|
||||
headers.sort();
|
||||
return Received { request_line: request_line.to_owned(), headers, body: unify(body) };
|
||||
}
|
||||
}
|
||||
|
||||
/// `None` when the installed cURL is too old for an option.
|
||||
async fn sent_by_curl(dir: &Path, command: &str, listener: &TcpListener) -> Option<Received> {
|
||||
let command = command.replacen("curl ", "curl --noproxy '*' --max-time 5 -sS -o /dev/null ", 1);
|
||||
let mut child = tokio::process::Command::new("bash").args(["-c", &command]).current_dir(dir).spawn().unwrap();
|
||||
tokio::select! {
|
||||
received = receive(listener) => {
|
||||
assert!(child.wait().await.unwrap().success(), "{command}");
|
||||
Some(received)
|
||||
}
|
||||
status = child.wait() => {
|
||||
assert_eq!(status.unwrap().code(), Some(2), "{command}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `None` when the request doesn't reach the server.
|
||||
async fn sent_by_the_client(dir: &Path, text: &str, listener: &TcpListener) -> Option<Received> {
|
||||
let file = dir.join("requests.http");
|
||||
let cancel = CancellationToken::new();
|
||||
let input = RunInput { text, index: 0, file: Some(&file), root: Some(dir), env: None };
|
||||
let both = async { tokio::join!(ide_http::run(input, &cancel), receive(listener)).1 };
|
||||
tokio::time::timeout(Duration::from_secs(5), both).await.ok()
|
||||
}
|
||||
|
||||
fn missing(tool: &str) -> bool {
|
||||
!Command::new(tool).arg("--version").output().is_ok_and(|o| o.status.success())
|
||||
}
|
||||
|
||||
const COMMANDS: &[&str] = &[
|
||||
// Clusters, and options whose value is not the URL.
|
||||
"curl -sX POST {url}/a",
|
||||
"curl -sXPUT -dfoo {url}/a",
|
||||
"curl -D /dev/null -C 0 -y 5 -Y 1 {url}/a",
|
||||
"curl --dump-header /dev/null --max-redirs 3 --retry-delay 1 --retry-max-time 5 {url}/a",
|
||||
// Methods.
|
||||
"curl -I {url}/a",
|
||||
"curl -I -G -d q=1 {url}/a",
|
||||
"curl -T f.json {url}/dir/",
|
||||
"curl -T f.json {url}",
|
||||
"curl -T f.json -X POST {url}/up?x=1",
|
||||
// Data.
|
||||
"curl -d @f.json -H 'Content-Type: application/json' {url}/a",
|
||||
"curl --data-binary @f.json {url}/a",
|
||||
"curl --data-raw @f.json {url}/a",
|
||||
"curl -d a=1 --data-urlencode 'b=x y&é/~' --data-urlencode '=p=q' --data-urlencode 'x y' {url}/a",
|
||||
"curl -G -d a=1 --data-urlencode 'b=c d' '{url}/a?z'",
|
||||
"curl -G -d a=1 '{url}/a?'",
|
||||
"curl --json '{\"a\":' --json '1}' -H 'Content-Type: x/y' {url}/a",
|
||||
"curl --url-query 'q=a b' --url-query '+r=1' -d body '{url}/a?z=1'",
|
||||
// Forms.
|
||||
"curl -F 'note=hi;type=text/plain' -F 'n2= x y ; type=text/html; charset=utf-8;filename=\"q\\\"r.txt\"' {url}/a",
|
||||
"curl -F '[email protected];type=application/json;filename=z.json' -F 'g=<f.json' -F 'q=\"a;b\"' {url}/a",
|
||||
"curl --form-string 'a=@x;type=b' {url}/a",
|
||||
// Headers.
|
||||
"curl -H 'X-Empty;' -H 'X-None:' -H 'X-Trim: v ' {url}/a",
|
||||
"curl -H 'Content-Type:' -d x {url}/a",
|
||||
"curl -b a=1 -b 'b=2; c=3' -b cookies.txt -A agent -e 'http://r;auto' {url}/a",
|
||||
"curl -u bob:secret {url}/a",
|
||||
"curl -u bob: {url}/a",
|
||||
"curl -u 'bob:se cret:x' {url}/a",
|
||||
"curl -u bob:secret -H 'Authorization: mine' {url}/a",
|
||||
"curl --oauth2-bearer abc {url}/a",
|
||||
// Quoting, as Chrome copies it, and the rest of a command line.
|
||||
r#"curl --url '{url}/a' -X $'PUT' -H $'x-title: it\'s!' --data-raw $'{"a":"b\\né"}'"#,
|
||||
"curl '{url}/\\[a\\]'",
|
||||
"curl -s {url}/a | cat",
|
||||
];
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_converted_command_sends_what_curl_sends() {
|
||||
if missing("curl") || missing("bash") {
|
||||
eprintln!("skipped: no curl or bash on PATH");
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("f.json"), "{\"from\": \"file\"}").unwrap();
|
||||
let mut failures = Vec::new();
|
||||
for command in COMMANDS {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let command = command.replace("{url}", &format!("http://{}", listener.local_addr().unwrap()));
|
||||
let expected =
|
||||
tokio::time::timeout(Duration::from_secs(20), sent_by_curl(dir.path(), &command, &listener)).await.unwrap();
|
||||
if expected.is_none() {
|
||||
eprintln!("skipped, not known to this curl: {command}");
|
||||
continue;
|
||||
}
|
||||
let Some(text) = from_curl(&command) else {
|
||||
failures.push(format!("{command}\n not converted"));
|
||||
continue;
|
||||
};
|
||||
let sent = sent_by_the_client(dir.path(), &text, &listener).await;
|
||||
if sent != expected {
|
||||
failures.push(format!("{command}\n curl {expected:?}\n client {sent:?}\n from {text:?}"));
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{} of {} differ\n{}", failures.len(), COMMANDS.len(), failures.join("\n"));
|
||||
}
|
||||
|
||||
/// What a request file can't express stays as pasted.
|
||||
#[test]
|
||||
fn commands_that_cannot_be_expressed_are_not_converted() {
|
||||
for command in [
|
||||
"curl -d @- http://h",
|
||||
"curl -T - http://h",
|
||||
"curl -d a=1 -d @f.json http://h",
|
||||
"curl -G -d @f.json http://h",
|
||||
"curl --data-urlencode [email protected] http://h",
|
||||
"curl -F 'f=@a,b' http://h",
|
||||
"curl -F '=(;type=multipart/mixed' http://h",
|
||||
"curl 'http://h/1' ;\ncurl 'http://h/2'",
|
||||
"curl -X",
|
||||
] {
|
||||
assert_eq!(from_curl(command), None, "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Chrome's "Copy as cURL (cmd)".
|
||||
#[test]
|
||||
fn a_windows_command_is_converted() {
|
||||
let command = "curl --url ^\"https://example.com/api?q=1^&r=^%^20^\" ^\r\n -X ^\"PUT^\" ^\r\n \
|
||||
-H ^\"accept: */*^\" ^\r\n -H ^\"sec-ch-ua: ^\"^\"Chromium^\"^\";v=^\"^\"140^\"^\"^\" ^\r\n \
|
||||
-H ^\"content-type: application/json^\" ^\r\n --data-raw ^\"^{^\"^\"a^\"^\":^\"^\"b c^\"^\"^}^\"";
|
||||
assert_eq!(
|
||||
from_curl(command).unwrap(),
|
||||
"PUT https://example.com/api?q=1&r=%20\naccept: */*\nsec-ch-ua: \"Chromium\";v=\"140\"\n\
|
||||
content-type: application/json\n\n{\"a\":\"b c\"}\n"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Files included in a request body (`< ./file`), as a server receives them.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_http::{History, HttpExchange, RunInput};
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
/// A PNG signature, every byte value, and the line endings a text include could lose.
|
||||
fn png() -> Vec<u8> {
|
||||
let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
bytes.extend(0..=255u8);
|
||||
bytes.extend(b"\xff\x00\r\n\n");
|
||||
bytes
|
||||
}
|
||||
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
haystack.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
/// Answers one connection per response with the next of `responses`, returning each request's
|
||||
/// head and body.
|
||||
async fn serve(listener: TcpListener, responses: Vec<&'static str>) -> Vec<(String, Vec<u8>)> {
|
||||
let mut seen = Vec::new();
|
||||
for response in responses {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = Vec::new();
|
||||
let mut buffer = [0u8; 4096];
|
||||
let (head, body) = loop {
|
||||
let read = socket.read(&mut buffer).await.unwrap();
|
||||
assert!(read > 0, "request ended before its body");
|
||||
request.extend_from_slice(&buffer[..read]);
|
||||
let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") else { continue };
|
||||
let head = String::from_utf8_lossy(&request[..end]).into_owned();
|
||||
let length = content_length(&head).expect("a Content-Length");
|
||||
if request.len() >= end + 4 + length {
|
||||
break (head, request[end + 4..].to_vec());
|
||||
}
|
||||
};
|
||||
seen.push((head, body));
|
||||
socket.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
fn content_length(head: &str) -> Option<usize> {
|
||||
head.lines().find_map(|line| {
|
||||
let (name, value) = line.split_once(':')?;
|
||||
name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse().unwrap())
|
||||
})
|
||||
}
|
||||
|
||||
const OK: &str = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok";
|
||||
|
||||
/// Runs the only request of `text` (`{{url}}` is the server) from a file in `dir`.
|
||||
async fn run(dir: &Path, text: &str, responses: Vec<&'static str>) -> (HttpExchange, Vec<(String, Vec<u8>)>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let text = format!("@url = http://{}\n{text}", listener.local_addr().unwrap());
|
||||
let server = tokio::spawn(serve(listener, responses));
|
||||
let file = dir.join("requests.http");
|
||||
let input = RunInput { text: &text, index: 0, file: Some(&file), root: Some(dir), env: None };
|
||||
let cancel = CancellationToken::new();
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
let exchange = ide_http::run(input, &cancel).await.unwrap();
|
||||
(exchange, server.await.unwrap())
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_file_body_is_sent_byte_for_byte() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for bytes in [png(), b"{\"id\": \"{{id}}\"}\r\n\n".to_vec(), b"caf\xe9\n".to_vec()] {
|
||||
std::fs::write(dir.path().join("a.bin"), &bytes).unwrap();
|
||||
let (_, seen) =
|
||||
run(dir.path(), "POST {{url}}/\nContent-Type: application/octet-stream\n\n< ./a.bin\n", vec![OK]).await;
|
||||
assert_eq!(content_length(&seen[0].0), Some(bytes.len()));
|
||||
assert_eq!(seen[0].1, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
const MULTIPART: &str = "POST {{url}}/\nContent-Type: multipart/form-data; boundary=xyz\n\n\
|
||||
--xyz\nContent-Disposition: form-data; name=\"note\"\n\nhi {{name}}\n\
|
||||
--xyz\nContent-Disposition: form-data; name=\"log\"; filename=\"a.log\"\n\n< ./a.log\n\
|
||||
--xyz\nContent-Disposition: form-data; name=\"pic\"; filename=\"a.png\"\nContent-Type: image/png\n\n< ./a.png\n\
|
||||
--xyz--\n";
|
||||
|
||||
fn multipart_dir() -> (tempfile::TempDir, Vec<u8>) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("a.log"), "one\ntwo\n").unwrap();
|
||||
std::fs::write(dir.path().join("a.png"), png()).unwrap();
|
||||
let mut expected = b"--xyz\r\nContent-Disposition: form-data; name=\"note\"\r\n\r\nhi Ada\r\n\
|
||||
--xyz\r\nContent-Disposition: form-data; name=\"log\"; filename=\"a.log\"\r\n\r\none\ntwo\n\r\n\
|
||||
--xyz\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"a.png\"\r\nContent-Type: image/png\r\n\r\n"
|
||||
.to_vec();
|
||||
expected.extend(png());
|
||||
expected.extend(b"\r\n--xyz--");
|
||||
(dir, expected)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multipart_parts_mix_text_and_files() {
|
||||
let (dir, expected) = multipart_dir();
|
||||
let (_, seen) = run(dir.path(), &format!("@name = Ada\n{MULTIPART}"), vec![OK]).await;
|
||||
assert_eq!(content_length(&seen[0].0), Some(expected.len()));
|
||||
assert_eq!(seen[0].1, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_redirect_resends_the_same_bytes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("a.png"), png()).unwrap();
|
||||
let redirect = "HTTP/1.1 307 Temporary Redirect\r\nLocation: /b\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
|
||||
let (_, seen) = run(dir.path(), "PUT {{url}}/a\n\n< ./a.png\n", vec![redirect, OK]).await;
|
||||
assert_eq!(seen[0].1, png());
|
||||
assert_eq!(seen[1].1, png());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_shown_and_saved_request_names_a_binary_file_instead_of_its_bytes() {
|
||||
let (dir, _) = multipart_dir();
|
||||
let (exchange, _) = run(dir.path(), &format!("@name = Ada\n{MULTIPART}"), vec![OK]).await;
|
||||
let shown = serde_json::to_value(&exchange).unwrap()["request"]["body"].as_str().unwrap().to_owned();
|
||||
assert!(shown.contains("hi Ada\r\n") && shown.contains("\r\n\r\none\ntwo\n\r\n"), "{shown}");
|
||||
assert!(shown.ends_with("Content-Type: image/png\r\n\r\n< ./a.png\r\n--xyz--"), "{shown}");
|
||||
|
||||
let history = History::new(dir.path().join("history"));
|
||||
history.add(&exchange).unwrap();
|
||||
let saved = std::fs::read(dir.path().join("history").join(format!("{}.json", exchange.entry.id))).unwrap();
|
||||
assert!(!contains(&saved, b"PNG") && !contains(&saved, "\u{fffd}".as_bytes()));
|
||||
let loaded = history.get(&exchange.entry.id).unwrap();
|
||||
assert_eq!(serde_json::to_value(&loaded).unwrap()["request"]["body"], shown.as_str());
|
||||
}
|
||||
|
||||
/// A history entry written before the body had parts.
|
||||
#[test]
|
||||
fn a_saved_text_body_still_loads() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let json = r#"{"entry":{"id":"e1","timeMs":1.0,"name":null,"method":"POST","url":"http://x","status":200,"totalMs":3.0,"file":null,"error":null},"request":{"name":null,"method":"POST","url":"http://x","headers":[],"body":"{\"a\": 1}"},"response":null}"#;
|
||||
std::fs::write(dir.path().join("e1.json"), json).unwrap();
|
||||
let exchange = History::new(dir.path().to_path_buf()).get("e1").unwrap();
|
||||
assert_eq!(serde_json::to_string(&exchange).unwrap(), json);
|
||||
}
|
||||
|
||||
fn to_curl(dir: &Path, text: &str) -> String {
|
||||
let file = dir.join("requests.http");
|
||||
ide_http::curl(&RunInput { text, index: 0, file: Some(&file), root: Some(dir), env: None }).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curl_reads_a_binary_file_by_its_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("a b.png"), png()).unwrap();
|
||||
std::fs::write(dir.path().join("a.json"), "{}\n").unwrap();
|
||||
assert_eq!(
|
||||
to_curl(dir.path(), "POST http://h/\nContent-Type: image/png\n\n< ./a b.png\n"),
|
||||
"curl -X POST 'http://h/' \\\n -H 'Content-Type: image/png' \\\n --data-binary '@./a b.png'"
|
||||
);
|
||||
// Text stays inline, so the command works without the file.
|
||||
assert_eq!(
|
||||
to_curl(dir.path(), "POST http://h/\n\n< ./a.json\n"),
|
||||
"curl -X POST 'http://h/' \\\n --data-raw '{}\n'"
|
||||
);
|
||||
}
|
||||
|
||||
/// The copied command sends what the HTTP Client sends, run by a real shell and cURL.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn the_copied_curl_command_sends_the_same_bytes() {
|
||||
let has_curl = std::process::Command::new("curl").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !has_curl {
|
||||
eprintln!("skipped: no curl on PATH");
|
||||
return;
|
||||
}
|
||||
let (dir, expected) = multipart_dir();
|
||||
for (request, expected) in [
|
||||
(MULTIPART.to_owned(), expected),
|
||||
("POST {{url}}/\nContent-Type: image/png\n\n< ./a.png\n".to_owned(), png()),
|
||||
("POST {{url}}/\nContent-Type: text/plain\n\n< ./a.log\n".to_owned(), b"one\ntwo\n".to_vec()),
|
||||
] {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let text = format!("@name = Ada\n@url = http://{}\n{request}", listener.local_addr().unwrap());
|
||||
let command = to_curl(dir.path(), &text).replace("curl -X", "curl --noproxy '*' -sS -X");
|
||||
let server = tokio::spawn(serve(listener, vec![OK]));
|
||||
let output =
|
||||
tokio::process::Command::new("sh").args(["-c", &command]).current_dir(dir.path()).output().await.unwrap();
|
||||
assert!(output.status.success(), "{command}\n{}", String::from_utf8_lossy(&output.stderr));
|
||||
let seen = tokio::time::timeout(Duration::from_secs(10), server).await.unwrap().unwrap();
|
||||
assert_eq!(seen[0].1, expected, "{command}");
|
||||
}
|
||||
}
|
||||
@@ -428,6 +428,26 @@ fn script_class_change(body: Node, text: &str) -> Option<Change> {
|
||||
return None;
|
||||
}
|
||||
let ranges: Vec<Range<usize>> = blocks.into_iter().map(|b| b.3).collect();
|
||||
// A method moved to the top would continue a field left open above it when it starts with an
|
||||
// operator: `x = 1` then `*gen() {}` reads as `1 * gen()`.
|
||||
let children: Vec<Node> = body.children(&mut body.walk()).filter(|n| n.kind() != "comment").collect();
|
||||
let top = children.iter().find(|n| n.start_byte() >= ranges[order[0]].start);
|
||||
let above = children.iter().rev().find(|n| n.end_byte() <= ranges[0].start);
|
||||
if order[0] != 0
|
||||
&& top.is_some_and(|n| n.child(0).is_some_and(|c| matches!(&text[c.byte_range()], "*" | "in" | "instanceof")))
|
||||
&& !above.is_some_and(|n| n.kind() == "class_static_block" || text[n.byte_range()].ends_with(['{', ';']))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Whole lines move: what shares the last method's last line (the closing brace, a comment
|
||||
// running on below it) stays at the end, so the last method must too.
|
||||
let end = ranges.last()?.end;
|
||||
if order.last() != Some(&(ranges.len() - 1))
|
||||
&& (end >= body.end_byte()
|
||||
|| body.children(&mut body.walk()).any(|n| n.start_byte() < end && n.end_byte() > end))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut gaps = Vec::new();
|
||||
for pair in ranges.windows(2) {
|
||||
// Only blank lines between methods; anything else stays with the class.
|
||||
@@ -650,10 +670,23 @@ mod tests {
|
||||
"class A {\n // #region helpers\n b() {}\n // #endregion\n constructor() {}\n}\n",
|
||||
// Two members on one line.
|
||||
"class A {\n b() {} constructor() {}\n}\n",
|
||||
// The closing brace on the last method's line would move with it.
|
||||
"class A {\n b() {}\n constructor() {} }\n",
|
||||
"const A = class {\n b() {}\n constructor() {} };",
|
||||
// So would the first line of a comment running on below it.
|
||||
"class A {\n b() {}\n constructor() {}; /* note\n */\n}\n",
|
||||
// A generator moved below a field without a semicolon would continue its initializer,
|
||||
// and so would one moved above the semicolon ending it.
|
||||
"class A {\n x = 1\n #p() {}\n *gen() {}\n}\n",
|
||||
"class A {\n x = {}\n #p() {}\n *gen() {}\n}\n",
|
||||
"class A {\n x = 1\n #p() {}\n in(a) {}\n}\n",
|
||||
"class A {\n x = 1\n #p() {}\n instanceof(a) {}\n}\n",
|
||||
"class A {\n x = 1\n /* c */ ;\n #p() {}\n *gen() {}\n}\n",
|
||||
// A syntax error anywhere in the file.
|
||||
"class A {\n b() {}\n constructor() {}\n}\nlet = ;\n",
|
||||
] {
|
||||
assert_eq!(script("typescript", text), None, "{text}");
|
||||
assert_eq!(script("javascript", text), None, "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -665,6 +698,38 @@ mod tests {
|
||||
assert_eq!(script("javascript", text).as_deref(), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_last_method_sharing_its_line_stays_last() {
|
||||
let text = "class A {\n b() {}\n static of() {}\n c() {} }";
|
||||
assert_eq!(script("typescript", text).as_deref(), Some("class A {\n static of() {}\n b() {}\n c() {} }"));
|
||||
let text = "class A {\n b() {}\n static of() {}\n c() {} /* note\n */\n}\n";
|
||||
let expected = "class A {\n static of() {}\n b() {}\n c() {} /* note\n */\n}\n";
|
||||
assert_eq!(script("javascript", text).as_deref(), Some(expected));
|
||||
// Below the last method's line: an empty class element, or a space only JavaScript knows.
|
||||
let text = "class A {\n b() {}\n constructor() {}\n ;\n}\n";
|
||||
assert_eq!(script("typescript", text).as_deref(), Some("class A {\n constructor() {}\n b() {}\n ;\n}\n"));
|
||||
let text = "class A {\n b() {}\n constructor() {}\n \u{feff}}\n";
|
||||
assert_eq!(
|
||||
script("javascript", text).as_deref(),
|
||||
Some("class A {\n constructor() {}\n b() {}\n \u{feff}}\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generator_moves_to_the_top_only_below_a_closed_member() {
|
||||
let text = "class A {\n x = 1;\n #p() {}\n *gen() {}\n}\n";
|
||||
let expected = "class A {\n x = 1;\n *gen() {}\n #p() {}\n}\n";
|
||||
assert_eq!(script("javascript", text).as_deref(), Some(expected));
|
||||
let text = "class A {\n static {}\n #p() {}\n *gen() {}\n}\n";
|
||||
let expected = "class A {\n static {}\n *gen() {}\n #p() {}\n}\n";
|
||||
assert_eq!(script("javascript", text).as_deref(), Some(expected));
|
||||
// The first method stays first, so the field's line ending is untouched.
|
||||
let text = "class A {\n x = 1\n /* c */ ;\n constructor() {}\n #p() {}\n *gen() {}\n}\n";
|
||||
let expected = "class A {\n x = 1\n /* c */ ;\n constructor() {}\n *gen() {}\n #p() {}\n}\n";
|
||||
assert_eq!(script("typescript", text).as_deref(), Some(expected));
|
||||
assert_eq!(script("javascript", text).as_deref(), Some(expected));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_and_instance_methods_with_one_name_stay_separate() {
|
||||
let text = "class A {\n of() {}\n static of() {}\n}\n";
|
||||
|
||||
@@ -513,6 +513,10 @@ impl ClientHandler {
|
||||
|
||||
fn show_message(&self, mgr: &LspManager, params: &Value) {
|
||||
let text = params.get("message").and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||
// "Renew or activate a license" doesn't apply to a free preview build: its status offers the update.
|
||||
if self.expired_license(mgr, &text) {
|
||||
return;
|
||||
}
|
||||
// rust-analyzer built from source reports its own slow main-loop turns as errors, meant for
|
||||
// its developers (`poke_rust_analyzer_developer`); nothing for the user to act on.
|
||||
if text.starts_with("overly long loop turn") {
|
||||
@@ -534,6 +538,16 @@ impl ClientHandler {
|
||||
mgr.sink().emit(IdeEvent::Notify { level, title: self.server.name.clone(), body: Some(text) });
|
||||
}
|
||||
|
||||
/// Whether `text` says the running build's license ran out; if so, its status says so.
|
||||
fn expired_license(&self, mgr: &LspManager, text: &str) -> bool {
|
||||
if !crate::server::reports_expired_license(text) {
|
||||
return false;
|
||||
}
|
||||
tracing::warn!(server = ?self.server.id, generation = self.generation, "[{}] {text}", self.server.name);
|
||||
self.server.report_expired_while_running(self.generation, mgr.sink());
|
||||
true
|
||||
}
|
||||
|
||||
/// `window/showMessageRequest` expects `MessageActionItem | null`. Showing
|
||||
/// the question as a plain notification and replying null made Dart cancel
|
||||
/// renames with a warning (`Renamed field will be invisible in …`).
|
||||
@@ -770,6 +784,7 @@ impl Handler for ClientHandler {
|
||||
"window/showMessage" => self.show_message(&mgr, ¶ms),
|
||||
"window/logMessage" => {
|
||||
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
|
||||
self.expired_license(&mgr, text);
|
||||
if self.server.config.tsserver_project && tsserver_ran_out_of_memory(text) {
|
||||
tracing::warn!(server = ?self.server.id, generation = self.generation, "[{}] {text}", self.server.name);
|
||||
// The tasks of the dead tsserver never see their `end`: end them now
|
||||
|
||||
@@ -175,6 +175,9 @@ pub struct Server {
|
||||
/// Why the current instance's `initialize` failed, for the crash report.
|
||||
start_error: Mutex<Option<(u64, String)>>,
|
||||
stderr: Mutex<VecDeque<String>>,
|
||||
/// The instance whose JetBrains preview build reported, while running, that its license
|
||||
/// ran out: it stops serving after a short grace period, and only an update helps.
|
||||
expired_while_running: Mutex<Option<u64>>,
|
||||
pub progress: Mutex<HashMap<String, Progress>>,
|
||||
/// What the editor shows per path: the pushed and the pulled diagnostics together.
|
||||
diagnostics: Mutex<HashMap<PathBuf, Vec<lsp::Diagnostic>>>,
|
||||
@@ -240,6 +243,7 @@ impl Server {
|
||||
started: Mutex::new(None),
|
||||
start_error: Mutex::new(None),
|
||||
stderr: Mutex::new(VecDeque::new()),
|
||||
expired_while_running: Mutex::new(None),
|
||||
progress: Mutex::new(HashMap::new()),
|
||||
diagnostics: Mutex::new(HashMap::new()),
|
||||
pushed: Mutex::new(HashMap::new()),
|
||||
@@ -750,11 +754,35 @@ impl Server {
|
||||
return;
|
||||
}
|
||||
let busy = self.is_busy();
|
||||
self.queue_status(&mut st, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, None);
|
||||
let message = self.expired_message(st.generation);
|
||||
self.queue_status(&mut st, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, message);
|
||||
drop(st);
|
||||
self.publish(sink);
|
||||
}
|
||||
|
||||
/// A running JetBrains preview build (kotlin-lsp) said its license ran out: it keeps the
|
||||
/// process alive but stops serving once a short grace period ends, without crashing. Its
|
||||
/// status then says the build expired, which offers the update a crashed one gets.
|
||||
pub fn report_expired_while_running(&self, generation: u64, sink: &SharedSink) {
|
||||
let mut st = self.state.lock();
|
||||
if st.generation != generation || !matches!(st.conn, Conn::Ready(_)) {
|
||||
return;
|
||||
}
|
||||
if self.expired_while_running.lock().replace(generation) == Some(generation) {
|
||||
return;
|
||||
}
|
||||
let busy = self.is_busy();
|
||||
let message = self.expired_message(generation);
|
||||
self.queue_status(&mut st, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, message);
|
||||
drop(st);
|
||||
self.publish(sink);
|
||||
}
|
||||
|
||||
fn expired_message(&self, generation: u64) -> Option<String> {
|
||||
(*self.expired_while_running.lock() == Some(generation))
|
||||
.then(|| format!("This build of {} has expired and stops working soon; update it.", self.name))
|
||||
}
|
||||
|
||||
/// Whether the server reports work in progress (indexing, analysis). A task marked
|
||||
/// stuck stays visible but no longer holds the server busy.
|
||||
pub fn is_busy(&self) -> bool {
|
||||
@@ -1167,6 +1195,14 @@ fn is_expired_build_line(line: &str) -> bool {
|
||||
line.contains("This build of ") && line.contains(" has expired")
|
||||
}
|
||||
|
||||
/// What a running JetBrains preview build says once its date passes: "Your JetBrains license has
|
||||
/// expired or is no longer valid. The language server keeps working for a short grace period…",
|
||||
/// then a parked license gate.
|
||||
pub(crate) fn reports_expired_license(text: &str) -> bool {
|
||||
let text = text.to_ascii_lowercase();
|
||||
text.contains("jetbrains license has expired") || text.contains("license gate: parked")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -2094,6 +2094,28 @@ async fn apply_edit_hook_and_server_requests() {
|
||||
"showMessageRequest is now a question with actions, not a notification; info and developer notices are not surfaced"
|
||||
);
|
||||
|
||||
// A JetBrains preview build past its date keeps running but stops serving after a grace
|
||||
// period: its status says the build expired (the UI offers the update), once per instance.
|
||||
let expired = |e: &IdeEvent| matches!(e, IdeEvent::LanguageServer { status: ide_core::event::ServerStatus::Ready | ide_core::event::ServerStatus::Busy, message: Some(m), .. } if m.contains("has expired"));
|
||||
peer.notify(
|
||||
"window/showMessage",
|
||||
json!({ "type": 2, "message": "Your JetBrains license has expired or is no longer valid. The language server keeps working for a short grace period; renew or activate a license to avoid interruption." }),
|
||||
)
|
||||
.unwrap();
|
||||
peer.notify(
|
||||
"window/logMessage",
|
||||
json!({ "type": 3, "message": "#LicenseManager - License gate: Parked(reason=GraceExpired)" }),
|
||||
)
|
||||
.unwrap();
|
||||
peer.notify("window/showMessage", json!({ "type": 2, "message": "after" })).unwrap();
|
||||
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b == "after")))
|
||||
.await;
|
||||
assert_eq!(h.events.lock().iter().filter(|e| expired(e)).count(), 1);
|
||||
assert!(
|
||||
!h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b.contains("license"))),
|
||||
"the license notice is not shown as is"
|
||||
);
|
||||
|
||||
// Dynamically registered capability is now usable.
|
||||
s.respond(
|
||||
"textDocument/documentHighlight",
|
||||
|
||||
@@ -100,6 +100,51 @@ pub trait HostApi: Send + Sync {
|
||||
) -> Result<crate::PluginDatabaseTableSchema, HostError> {
|
||||
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
|
||||
}
|
||||
/// Lists already-connected project sources; database.schema was checked (API 1.21).
|
||||
fn database_connected_sources(
|
||||
&self,
|
||||
_root: &Path,
|
||||
_client: Option<&str>,
|
||||
) -> Result<Vec<crate::PluginConnectedDataSource>, HostError> {
|
||||
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
|
||||
}
|
||||
/// Lists schemas of an already-connected project source; database.schema was checked (API 1.21).
|
||||
fn database_list_schemas(
|
||||
&self,
|
||||
_root: &Path,
|
||||
_client: Option<&str>,
|
||||
_source_id: &str,
|
||||
_cancel: &CancellationToken,
|
||||
_timeout: Duration,
|
||||
) -> Result<Vec<String>, HostError> {
|
||||
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
|
||||
}
|
||||
/// Lists tables and views in a schema of a connected project source; database.schema was checked (API 1.21).
|
||||
fn database_list_tables(
|
||||
&self,
|
||||
_root: &Path,
|
||||
_client: Option<&str>,
|
||||
_source_id: &str,
|
||||
_schema: &str,
|
||||
_cancel: &CancellationToken,
|
||||
_timeout: Duration,
|
||||
) -> Result<Vec<crate::PluginDatabaseTableSummary>, HostError> {
|
||||
Err(HostError::Invalid("Database schema access is unavailable on this host".into()))
|
||||
}
|
||||
/// Executes SQL against an already-connected project source; database.query was checked (API 1.21).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn database_execute_query(
|
||||
&self,
|
||||
_root: &Path,
|
||||
_client: Option<&str>,
|
||||
_source_id: &str,
|
||||
_sql: &str,
|
||||
_max_rows: Option<u32>,
|
||||
_cancel: &CancellationToken,
|
||||
_timeout: Duration,
|
||||
) -> Result<crate::PluginDatabaseQueryResult, HostError> {
|
||||
Err(HostError::Invalid("Database query execution is unavailable on this host".into()))
|
||||
}
|
||||
/// Creates/replaces this plugin's non-secret project connection settings.
|
||||
fn database_upsert(&self, root: &Path, source: crate::PluginDataSource) -> Result<(), HostError>;
|
||||
/// Removes only an owned data source and its credentials.
|
||||
@@ -135,6 +180,10 @@ pub trait HostApi: Send + Sync {
|
||||
/// (of the module `module` only, when given), as the IDE last resolved it; never runs
|
||||
/// a build tool.
|
||||
fn build_dependencies(&self, root: &Path, module: Option<&str>) -> Result<Vec<crate::DependencyNode>, HostError>;
|
||||
/// Installed SDKs / toolchains relevant to `root`, optionally narrowed by `kind` (API 1.21).
|
||||
fn build_sdks(&self, root: &Path, kind: Option<&str>) -> Result<Vec<crate::SdkInfo>, HostError>;
|
||||
/// Project Structure › Artifacts definitions of `root` (API 1.21).
|
||||
fn build_artifacts(&self, root: &Path) -> Result<Vec<crate::ArtifactInfo>, HostError>;
|
||||
/// Stdio argv only; no URL or bearer token.
|
||||
fn mcp_stdio_command(&self, client: &str) -> Option<Vec<String>>;
|
||||
/// What other plugins contributed to `point`, as (plugin id, JSON). Only the
|
||||
|
||||
@@ -20,6 +20,8 @@ pub struct EditorContext {
|
||||
pub language: String,
|
||||
/// Selections when the command was invoked (cursors are empty ranges).
|
||||
pub selections: Vec<ide_core::Range>,
|
||||
/// First and last document line on screen when the command was invoked.
|
||||
pub visible_lines: Option<(u32, u32)>,
|
||||
}
|
||||
|
||||
/// Where a command or event batch comes from: the window and its project.
|
||||
@@ -1178,6 +1180,47 @@ pub struct DependencyNode {
|
||||
pub parent: Option<u32>,
|
||||
}
|
||||
|
||||
/// One installed interpreter, JDK, or toolchain returned by `build.sdks` (API 1.21).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SdkInfo {
|
||||
pub kind: String,
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub version: Option<String>,
|
||||
pub source: String,
|
||||
pub home: Option<String>,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
/// Origin of an artifact returned by `build.artifacts` (API 1.21).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArtifactOrigin {
|
||||
BuildModel,
|
||||
ProjectStructure,
|
||||
}
|
||||
|
||||
/// Packaging kind of an artifact (API 1.21).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ArtifactKind {
|
||||
Jar,
|
||||
War,
|
||||
WarExploded,
|
||||
}
|
||||
|
||||
/// One deployable WAR module or Project Structure › Artifacts definition returned by `build.artifacts` (API 1.21).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ArtifactInfo {
|
||||
pub id: String,
|
||||
pub origin: ArtifactOrigin,
|
||||
pub tool: String,
|
||||
pub name: String,
|
||||
pub kind: ArtifactKind,
|
||||
pub module: String,
|
||||
pub output_directory: String,
|
||||
pub main_class: String,
|
||||
pub include_libraries: Vec<String>,
|
||||
}
|
||||
|
||||
/// Non-secret settings of a plugin-owned project database source (API 1.4).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -1264,3 +1307,37 @@ pub struct PluginDatabaseTableSchema {
|
||||
pub indexes: Vec<PluginDatabaseIndex>,
|
||||
pub foreign_keys: Vec<PluginDatabaseForeignKey>,
|
||||
}
|
||||
/// Non-secret identity of an already-connected project data source (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginConnectedDataSource {
|
||||
pub source_id: String,
|
||||
pub name: String,
|
||||
pub driver: String,
|
||||
pub database: Option<String>,
|
||||
}
|
||||
/// Summary of a table or view in a connected schema (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginDatabaseTableSummary {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
/// Column metadata of a query result (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginDatabaseQueryColumn {
|
||||
pub name: String,
|
||||
pub type_name: String,
|
||||
}
|
||||
/// Bounded result of executing a SQL statement on a connected source (API 1.21).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginDatabaseQueryResult {
|
||||
pub columns: Vec<PluginDatabaseQueryColumn>,
|
||||
pub rows: Vec<Vec<Option<String>>>,
|
||||
pub affected: Option<u64>,
|
||||
pub has_more: bool,
|
||||
pub elapsed_ms: u64,
|
||||
}
|
||||
@@ -1337,6 +1337,13 @@ impl editor::HostTextEditor for StoreData {
|
||||
Ok(Ok(self.table.get(&this)?.ctx.selections.iter().map(range_to_wit).collect()))
|
||||
}
|
||||
|
||||
fn visible_lines(&mut self, this: Resource<EditorRes>) -> Fallible<Option<(u32, u32)>> {
|
||||
if let Err(e) = self.require(Capability::EditorRead) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
Ok(Ok(self.table.get(&this)?.ctx.visible_lines))
|
||||
}
|
||||
|
||||
fn apply_edits(&mut self, this: Resource<EditorRes>, version: u64, edits: Vec<wit::TextEdit>) -> Fallible<u64> {
|
||||
if let Err(e) = self.require(Capability::EditorWrite) {
|
||||
return Ok(Err(e));
|
||||
@@ -1566,6 +1573,64 @@ impl build::Host for StoreData {
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
|
||||
fn sdks(&mut self, project: Resource<ProjectRes>, kind: Option<String>) -> Fallible<Vec<build::SdkInfo>> {
|
||||
if let Err(e) = self.require(Capability::BuildRead) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
Ok(self
|
||||
.host
|
||||
.build_sdks(&root, kind.as_deref())
|
||||
.map(|sdks| {
|
||||
sdks.into_iter()
|
||||
.map(|s| build::SdkInfo {
|
||||
kind: s.kind,
|
||||
name: s.name,
|
||||
path: s.path,
|
||||
version: s.version,
|
||||
source: s.source,
|
||||
home: s.home,
|
||||
active: s.active,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
|
||||
fn artifacts(&mut self, project: Resource<ProjectRes>) -> Fallible<Vec<build::ArtifactInfo>> {
|
||||
if let Err(e) = self.require(Capability::BuildRead) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
Ok(self
|
||||
.host
|
||||
.build_artifacts(&root)
|
||||
.map(|artifacts| {
|
||||
artifacts
|
||||
.into_iter()
|
||||
.map(|a| build::ArtifactInfo {
|
||||
id: a.id,
|
||||
origin: match a.origin {
|
||||
crate::ArtifactOrigin::BuildModel => build::ArtifactOrigin::BuildModel,
|
||||
crate::ArtifactOrigin::ProjectStructure => build::ArtifactOrigin::ProjectStructure,
|
||||
},
|
||||
tool: a.tool,
|
||||
name: a.name,
|
||||
kind: match a.kind {
|
||||
crate::ArtifactKind::Jar => build::ArtifactKind::Jar,
|
||||
crate::ArtifactKind::War => build::ArtifactKind::War,
|
||||
crate::ArtifactKind::WarExploded => build::ArtifactKind::WarExploded,
|
||||
},
|
||||
module: a.module,
|
||||
output_directory: a.output_directory,
|
||||
main_class: a.main_class,
|
||||
include_libraries: a.include_libraries,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
}
|
||||
|
||||
impl commit::Host for StoreData {
|
||||
@@ -3426,6 +3491,114 @@ impl bindings::openidea::plugin::database::Host for StoreData {
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn connected_sources(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
) -> Fallible<Vec<bindings::openidea::plugin::database::ConnectedSource>> {
|
||||
if let Err(e) = self.require(Capability::DatabaseSchema) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result = self.host.database_connected_sources(&root, self.client());
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
use bindings::openidea::plugin::database as db;
|
||||
Ok(result
|
||||
.map(|sources| {
|
||||
sources
|
||||
.into_iter()
|
||||
.map(|s| db::ConnectedSource {
|
||||
source_id: s.source_id,
|
||||
name: s.name,
|
||||
driver: s.driver,
|
||||
database: s.database,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn list_schemas(&mut self, project: Resource<ProjectRes>, source_id: String) -> Fallible<Vec<String>> {
|
||||
if let Err(e) = self.require(Capability::DatabaseSchema) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result =
|
||||
self.host.database_list_schemas(&root, self.client(), &source_id, &self.cancel.token(), self.io_timeout());
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
Ok(result.map_err(to_wit))
|
||||
}
|
||||
fn list_tables(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
source_id: String,
|
||||
schema: String,
|
||||
) -> Fallible<Vec<bindings::openidea::plugin::database::TableSummary>> {
|
||||
if let Err(e) = self.require(Capability::DatabaseSchema) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result = self.host.database_list_tables(
|
||||
&root,
|
||||
self.client(),
|
||||
&source_id,
|
||||
&schema,
|
||||
&self.cancel.token(),
|
||||
self.io_timeout(),
|
||||
);
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
use bindings::openidea::plugin::database as db;
|
||||
Ok(result
|
||||
.map(|tables| {
|
||||
tables
|
||||
.into_iter()
|
||||
.map(|t| db::TableSummary { name: t.name, kind: t.kind, comment: t.comment })
|
||||
.collect()
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn execute_query(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
source_id: String,
|
||||
sql: String,
|
||||
max_rows: Option<u32>,
|
||||
) -> Fallible<bindings::openidea::plugin::database::QueryResult> {
|
||||
if let Err(e) = self.require(Capability::DatabaseQuery) {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let root = self.table.get(&project)?.root.clone();
|
||||
let result = self.host.database_execute_query(
|
||||
&root,
|
||||
self.client(),
|
||||
&source_id,
|
||||
&sql,
|
||||
max_rows,
|
||||
&self.cancel.token(),
|
||||
self.io_timeout(),
|
||||
);
|
||||
if result.is_err() {
|
||||
self.grant_io_error_grace();
|
||||
}
|
||||
use bindings::openidea::plugin::database as db;
|
||||
Ok(result
|
||||
.map(|r| db::QueryResult {
|
||||
columns: r
|
||||
.columns
|
||||
.into_iter()
|
||||
.map(|c| db::QueryColumn { name: c.name, type_name: c.type_name })
|
||||
.collect(),
|
||||
rows: r.rows,
|
||||
affected: r.affected,
|
||||
has_more: r.has_more,
|
||||
elapsed_ms: r.elapsed_ms,
|
||||
})
|
||||
.map_err(to_wit))
|
||||
}
|
||||
fn upsert_source(
|
||||
&mut self,
|
||||
project: Resource<ProjectRes>,
|
||||
|
||||
@@ -96,6 +96,24 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `MockHost::install()` grants every capability that takes no value, so plugin tests see what
|
||||
/// a fully granted plugin sees.
|
||||
#[test]
|
||||
fn the_sdk_mock_grants_every_capability_without_a_value() {
|
||||
let mock = std::fs::read_to_string(repo().join("sdk/rust/openidea-plugin/src/mock.rs")).unwrap();
|
||||
let list = mock.split_once("const ALL: &[&str] = &[").unwrap().1.split_once("];").unwrap().0;
|
||||
let granted: Vec<&str> = list.split('"').skip(1).step_by(2).collect();
|
||||
let parser = std::fs::read_to_string(repo().join("crates/ide-extension/src/capability.rs")).unwrap();
|
||||
let fixed = parser.split_once("Ok(match s {").unwrap().1.split_once("_ => return Err").unwrap().0;
|
||||
let names: Vec<&str> =
|
||||
fixed.lines().filter_map(|line| line.trim().strip_prefix('"')?.split_once('"').map(|(n, _)| n)).collect();
|
||||
assert!(names.len() > 10, "{names:?}");
|
||||
for name in names {
|
||||
assert!(granted.contains(&name), "MockHost::install() in the SDK does not grant {name:?}");
|
||||
assert!(name.parse::<ide_extension::Capability>().is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.21.0");
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
5e1b98e6beb51fdacc358ac9a16eece3d696bc5f3cb17f8278b060c8d186d425
|
||||
fbd767ccf69c37807aa8f535197ab9fac47f809ef887ab9fd99c0b2886201ae1
|
||||
@@ -174,6 +174,7 @@ impl Plugin for Api14 {
|
||||
.into_iter()
|
||||
.map(|r| [r.start.line, r.start.character, r.end.line, r.end.character])
|
||||
.collect::<Vec<_>>(),
|
||||
e.visible_lines().unwrap(),
|
||||
)
|
||||
});
|
||||
received.push(serde_json::json!({ "kind": kind, "data": data, "editor": editor }));
|
||||
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
27cd36ae025d3b93a179c9957f770a5a00746239e34964fd95cacd9fa12796e0
|
||||
583b5ee3f495851ca14c378a3a4fe4cfd92be772e5f33a383d4f3b9f935f4b7e
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
ba8adc3daa979ef7d7cae161537ebc9726ee640d5a0c4fb3201a472c6804e00d
|
||||
a29fb8d12bc4bb7fdba146706ce941ecfce1e4ddecdbbe1672aac88b1adfb4da
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
cdca6f0307b4c29829979ccfaafdcd818e5230e3435bc46a43a05790975f4c06
|
||||
f99c40e69fba8d835f578dc6d1dc2a078ad774d881ae454e3703d5d150cf2c8d
|
||||
Бінарний файл не відображається.
Loaded 100 of 852 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача