дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 22:02:59 +02:00
Порівняти коміти
28
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
0c9450f5b0 | ||
|
|
b8289a40f4 | ||
|
|
fd1702f6dd | ||
|
|
b9a25462ea | ||
|
|
04e68f6a12 | ||
|
|
4cfc794f60 | ||
|
|
8105dfd41a | ||
|
|
fca497d246 | ||
|
|
5cb73c5fd1 | ||
|
|
2b435c8440 | ||
|
|
db266643aa | ||
|
|
4812d28614 | ||
|
|
7c9f343ca4 | ||
|
|
d815a8ef44 | ||
|
|
d22c42e471 | ||
|
|
a111b32e11 | ||
|
|
f7141f6515 | ||
|
|
2d14368d2c | ||
|
|
5cbc4134a1 | ||
|
|
5a92145ad9 | ||
|
|
4354839584 | ||
|
|
e1a1becadd | ||
|
|
ad685ea19e | ||
|
|
5fb8f21c60 | ||
|
|
68abe345cc | ||
|
|
32381cc740 | ||
|
|
d897236bd7 | ||
|
|
68e3adde99 |
No files matched your search
Створено
@@ -4198,6 +4198,7 @@ version = "0.1.55"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"which",
|
||||
|
||||
@@ -112,6 +112,8 @@ pub type WorkspaceRootsHook = Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>;
|
||||
|
||||
/// Returns the project's git executable (`None`: the default), which the tasks' git runs.
|
||||
pub type GitExecutableHook = Arc<dyn Fn() -> Option<PathBuf> + Send + Sync>;
|
||||
/// Whether the project's Git integration is on (Settings › Version Control › Git).
|
||||
pub type GitEnabledHook = Arc<dyn Fn() -> bool + Send + Sync>;
|
||||
|
||||
/// Returns the user's transient network retry window and cold-reopen recovery policy.
|
||||
pub type RecoverySettingsHook = Arc<
|
||||
@@ -260,6 +262,7 @@ struct Shared {
|
||||
reconciled: AtomicBool,
|
||||
workspace_roots: RwLock<Option<WorkspaceRootsHook>>,
|
||||
git_executable: RwLock<Option<GitExecutableHook>>,
|
||||
git_enabled: RwLock<Option<GitEnabledHook>>,
|
||||
change_reads: Arc<tokio::sync::Semaphore>,
|
||||
known: Arc<Mutex<HashMap<String, Known>>>,
|
||||
providers: RwLock<Vec<provider::ProviderSpec>>,
|
||||
@@ -1011,6 +1014,7 @@ impl AgentManager {
|
||||
reconciled: AtomicBool::new(false),
|
||||
workspace_roots: RwLock::new(None),
|
||||
git_executable: RwLock::new(None),
|
||||
git_enabled: RwLock::new(None),
|
||||
change_reads: Arc::new(tokio::sync::Semaphore::new(MAX_CHANGE_READS)),
|
||||
known,
|
||||
providers,
|
||||
@@ -1118,6 +1122,11 @@ impl AgentManager {
|
||||
*self.shared.git_executable.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// Sets the callback that tells whether Git integration is on; off, tasks run no git.
|
||||
pub fn set_git_enabled_hook(&self, hook: GitEnabledHook) {
|
||||
*self.shared.git_enabled.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// Directory holding linked Git worktrees created for agent tasks of this project.
|
||||
pub fn worktrees_dir(&self) -> &Path {
|
||||
&self.shared.paths.worktrees_dir
|
||||
@@ -1585,6 +1594,11 @@ impl AgentManager {
|
||||
let project_root = Some(IpcPath(root.clone()));
|
||||
let (cwd, branch, base, base_commit, before) = match req.isolation {
|
||||
Isolation::Worktree => {
|
||||
if !git_enabled(&self.shared) {
|
||||
return Err(IdeError::invalid(
|
||||
"worktrees need Git, which is disabled: run the task in the local checkout",
|
||||
));
|
||||
}
|
||||
// The UI offers worktrees for git projects only; state it when it isn't one.
|
||||
if Repo::discover(&root)?.is_none() {
|
||||
return Err(IdeError::invalid(
|
||||
@@ -1598,10 +1612,14 @@ impl AgentManager {
|
||||
}
|
||||
Isolation::Local => {
|
||||
let r = root.clone();
|
||||
let (head, before) = vcs(&self.shared, move || {
|
||||
Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default()))
|
||||
})
|
||||
.await?;
|
||||
let (head, before) = if git_enabled(&self.shared) {
|
||||
vcs(&self.shared, move || {
|
||||
Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default()))
|
||||
})
|
||||
.await?
|
||||
} else {
|
||||
(None, BTreeMap::new())
|
||||
};
|
||||
let (base, commit) = head.unzip();
|
||||
(root, None, base, commit, before)
|
||||
}
|
||||
@@ -6291,8 +6309,16 @@ async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + '
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
fn git_enabled(shared: &Shared) -> bool {
|
||||
shared.git_enabled.read().as_ref().is_none_or(|hook| hook())
|
||||
}
|
||||
|
||||
/// [`blocking`] for work that runs git: the repositories it opens run the project's git.
|
||||
/// Fails without running it while Git integration is off.
|
||||
async fn vcs<T: Send + 'static>(shared: &Shared, f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
if !git_enabled(shared) {
|
||||
return Err(IdeError::unavailable("Git integration is disabled"));
|
||||
}
|
||||
let git = shared.git_executable.read().as_ref().and_then(|hook| hook());
|
||||
blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await
|
||||
}
|
||||
|
||||
@@ -653,7 +653,7 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.shutdown();
|
||||
shut_down(&mgr, &agent).await;
|
||||
let restored_agent = Arc::new(FakeAgent::default());
|
||||
let restored = manager(tmp.path(), restored_agent.clone());
|
||||
// Listing the tasks leaves the conversation on disk until something asks for it.
|
||||
@@ -672,7 +672,8 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -693,7 +694,7 @@ async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
|
||||
mgr.archive(&task.id).unwrap();
|
||||
assert!(snapshot(&mgr).commands.is_empty());
|
||||
assert!(names(mgr.commands("claude", Some(&task.id)).await.unwrap()).contains(&"review".to_owned()));
|
||||
mgr.shutdown();
|
||||
shut_down(&mgr, &agent).await;
|
||||
|
||||
// A list saved with an archived task (by an earlier version) isn't read back.
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
@@ -787,7 +788,7 @@ async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.shutdown();
|
||||
shut_down(&mgr, &agent).await;
|
||||
// In a store of its own: a late save of the first manager can't touch it.
|
||||
let name = format!("{}.json", task.id);
|
||||
let mut file: Value =
|
||||
@@ -826,7 +827,7 @@ async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
|
||||
mgr.shutdown();
|
||||
shut_down(&mgr, &agent).await;
|
||||
// The caller never deleted it (its window closed): only a saved task comes back.
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
|
||||
@@ -1388,6 +1389,19 @@ async fn wait_for(mgr: &AgentManager, id: &str, status: AgentStatus) {
|
||||
panic!("task never reached {status:?} (is {s:?})");
|
||||
}
|
||||
|
||||
/// Shuts `mgr` down and waits until `agent` has seen each of its connections end. A fake still
|
||||
/// waiting for an answer holds a blocking thread until its side reads that end; a test that
|
||||
/// returned first would drop the runtime, and the drop waits for that thread forever.
|
||||
async fn shut_down(mgr: &AgentManager, agent: &FakeAgent) {
|
||||
mgr.shutdown();
|
||||
let servers = agent.servers.lock().clone();
|
||||
for server in servers {
|
||||
tokio::time::timeout(Duration::from_secs(5), server.closed())
|
||||
.await
|
||||
.expect("the agent's side of the connection closes");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1968,7 +1982,8 @@ async fn shutdown_during_session_open_kills_connecting_peer_without_failing() {
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn shutdown_during_permission_request_settles_without_failing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("decide"),
|
||||
@@ -1980,7 +1995,7 @@ async fn shutdown_during_permission_request_settles_without_failing() {
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
|
||||
mgr.shutdown();
|
||||
shut_down(&mgr, &agent).await;
|
||||
tokio::time::sleep(TURN_GRACE * 3).await;
|
||||
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-android"
|
||||
description = "Android devices and logcat for the Logcat tool window, driven through the adb CLI"
|
||||
description = "Android devices and iOS Simulators and their logs for the Logcat tool window, driven through adb and simctl"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -8,6 +8,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
which = "8"
|
||||
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
//! iOS Simulators and their unified log, driven through `xcrun simctl` (macOS only).
|
||||
//!
|
||||
//! A simulator's log is followed with `simctl spawn <udid> log stream --style ndjson`
|
||||
//! and parsed into the same [`LogcatLine`] the Android log uses, so the Logcat tool
|
||||
//! window shows both with one level filter and one filter language.
|
||||
|
||||
use crate::model::{LogcatLevel, LogcatLine};
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const LIST: Duration = Duration::from_secs(20);
|
||||
const BATCH_IDLE: Duration = Duration::from_millis(60);
|
||||
const BATCH_MAX: usize = 300;
|
||||
|
||||
/// A booted simulator, as `simctl list devices booted -j` reports it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BootedSimulator {
|
||||
pub udid: String,
|
||||
pub name: String,
|
||||
/// e.g. `iOS 27.0`.
|
||||
pub runtime: String,
|
||||
}
|
||||
|
||||
/// Booted simulators; empty off macOS or without Xcode, so nothing iOS-related shows there.
|
||||
pub fn booted_simulators() -> IdeResult<Vec<BootedSimulator>> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut cmd = Command::new("xcrun");
|
||||
cmd.args(["simctl", "list", "devices", "booted", "-j"]);
|
||||
match process::run(cmd, LIST, None) {
|
||||
Ok(out) if out.success => Ok(parse_simulators(&out.stdout)),
|
||||
// No Xcode (only the Command Line Tools, or none): there are no simulators.
|
||||
_ => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `simctl list devices -j`, keeping booted devices.
|
||||
pub fn parse_simulators(json: &str) -> Vec<BootedSimulator> {
|
||||
#[derive(Deserialize)]
|
||||
struct List {
|
||||
devices: std::collections::BTreeMap<String, Vec<Device>>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Device {
|
||||
udid: String,
|
||||
name: String,
|
||||
state: String,
|
||||
}
|
||||
let Ok(list) = serde_json::from_str::<List>(json) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (runtime, devices) in list.devices {
|
||||
// "com.apple.CoreSimulator.SimRuntime.iOS-27-0" → "iOS 27.0"
|
||||
let short = runtime.rsplit('.').next().unwrap_or(&runtime);
|
||||
let runtime = short.split_once('-').map_or(short.to_owned(), |(os, v)| format!("{os} {}", v.replace('-', ".")));
|
||||
for d in devices.into_iter().filter(|d| d.state == "Booted") {
|
||||
out.push(BootedSimulator { udid: d.udid, name: d.name, runtime: runtime.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Message type of the unified log → the logcat level the window filters and colors by.
|
||||
fn level(message_type: &str) -> LogcatLevel {
|
||||
match message_type {
|
||||
"Debug" => LogcatLevel::Debug,
|
||||
"Info" | "Default" => LogcatLevel::Info,
|
||||
"Error" => LogcatLevel::Error,
|
||||
"Fault" => LogcatLevel::Fatal,
|
||||
_ => LogcatLevel::Verbose,
|
||||
}
|
||||
}
|
||||
|
||||
/// One NDJSON entry of `log stream --style ndjson`; `None` for anything that is not a
|
||||
/// log message (activities, the trailing "terminated" notice). Unknown fields are ignored.
|
||||
pub fn parse_ndjson(line: &str) -> Option<LogcatLine> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
event_type: String,
|
||||
#[serde(default)]
|
||||
message_type: String,
|
||||
#[serde(default)]
|
||||
timestamp: String,
|
||||
#[serde(default)]
|
||||
process_image_path: String,
|
||||
#[serde(rename = "processID", default)]
|
||||
pid: i64,
|
||||
#[serde(rename = "threadID", default)]
|
||||
tid: i64,
|
||||
#[serde(default)]
|
||||
subsystem: String,
|
||||
#[serde(default)]
|
||||
category: String,
|
||||
#[serde(default)]
|
||||
event_message: String,
|
||||
}
|
||||
let e: Entry = serde_json::from_str(line).ok()?;
|
||||
if e.event_type != "logEvent" {
|
||||
return None;
|
||||
}
|
||||
let process = e.process_image_path.rsplit('/').next().unwrap_or_default();
|
||||
let tag = match (e.subsystem.is_empty(), e.category.is_empty()) {
|
||||
(true, _) => process.to_owned(),
|
||||
(false, true) => format!("{process} ({})", e.subsystem),
|
||||
(false, false) => format!("{process} ({}:{})", e.subsystem, e.category),
|
||||
};
|
||||
// "2026-11-29 14:39:31.696480+0900" → "11-29 14:39:31.696", logcat's shape.
|
||||
let time = e.timestamp.get(5..23).unwrap_or(&e.timestamp).to_owned();
|
||||
Some(LogcatLine {
|
||||
time,
|
||||
pid: e.pid as i32,
|
||||
tid: e.tid as i32,
|
||||
level: level(&e.message_type),
|
||||
tag,
|
||||
message: e.event_message,
|
||||
})
|
||||
}
|
||||
|
||||
/// Follows simulator `udid`'s log until `cancel` fires or the simulator shuts down.
|
||||
pub fn simulator_log(
|
||||
udid: &str,
|
||||
cancel: &CancellationToken,
|
||||
on_batch: &mut dyn FnMut(Vec<LogcatLine>),
|
||||
) -> IdeResult<()> {
|
||||
let mut cmd = Command::new("xcrun");
|
||||
cmd.args(["simctl", "spawn", udid, "log", "stream", "--style", "ndjson", "--level", "debug"]);
|
||||
match process::stream_batched(cmd, cancel, BATCH_IDLE, BATCH_MAX, parse_ndjson, on_batch) {
|
||||
Ok((ok, _)) if ok || cancel.is_cancelled() => Ok(()),
|
||||
// `log stream` is killed when the simulator shuts down: that is an end, not a failure.
|
||||
Ok((_, stderr)) if stderr.iter().any(|l| l.contains("terminated with signal")) => Ok(()),
|
||||
Ok((_, stderr)) => Err(IdeError::unavailable(format!("log stream on {udid} stopped: {}", stderr.join("\n")))),
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ENTRY: &str = r#"{"timezoneName":"","messageType":"Error","eventType":"logEvent","source":null,"subsystem":"com.apple.network","category":"endpoint","threadID":90176044,"processImagePath":"\/usr\/libexec\/remindd","timestamp":"2026-11-29 14:39:31.696480+0900","eventMessage":"endpoint has nothing to cleanup","processID":64339,"someFutureField":{"x":[1,2]}}"#;
|
||||
|
||||
#[test]
|
||||
fn parses_an_entry_and_ignores_unknown_fields() {
|
||||
let line = parse_ndjson(ENTRY).unwrap();
|
||||
assert_eq!(line.time, "11-29 14:39:31.696");
|
||||
assert_eq!(line.pid, 64339);
|
||||
assert_eq!(line.tid, 90176044);
|
||||
assert_eq!(line.level, LogcatLevel::Error);
|
||||
assert_eq!(line.tag, "remindd (com.apple.network:endpoint)");
|
||||
assert_eq!(line.message, "endpoint has nothing to cleanup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_a_multi_line_message_whole() {
|
||||
let entry = r#"{"eventType":"logEvent","messageType":"Default","processImagePath":"/a/MyApp","processID":7,"eventMessage":"first\nsecond"}"#;
|
||||
let line = parse_ndjson(entry).unwrap();
|
||||
assert_eq!(line.message, "first\nsecond");
|
||||
assert_eq!(line.tag, "MyApp");
|
||||
assert_eq!(line.level, LogcatLevel::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_what_is_not_a_log_message() {
|
||||
assert!(parse_ndjson(r#"{"eventType":"activityCreateEvent","eventMessage":"x"}"#).is_none());
|
||||
assert!(parse_ndjson("Child process terminated with signal 15: Terminated").is_none());
|
||||
assert!(parse_ndjson("").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_message_types_to_levels() {
|
||||
assert_eq!(level("Debug"), LogcatLevel::Debug);
|
||||
assert_eq!(level("Info"), LogcatLevel::Info);
|
||||
assert_eq!(level("Default"), LogcatLevel::Info);
|
||||
assert_eq!(level("Error"), LogcatLevel::Error);
|
||||
assert_eq!(level("Fault"), LogcatLevel::Fatal);
|
||||
assert_eq!(level("Signpost"), LogcatLevel::Verbose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_booted_simulators() {
|
||||
let json = r#"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-0":[
|
||||
{"udid":"A","name":"iPhone Air","state":"Booted","isAvailable":true},
|
||||
{"udid":"B","name":"iPhone 18","state":"Shutdown"}]}}"#;
|
||||
assert_eq!(
|
||||
parse_simulators(json),
|
||||
vec![BootedSimulator { udid: "A".into(), name: "iPhone Air".into(), runtime: "iOS 27.0".into() }]
|
||||
);
|
||||
assert!(parse_simulators("not json").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,11 @@
|
||||
//!
|
||||
//! Every function blocks; callers run them off the UI / command threads.
|
||||
|
||||
mod ios;
|
||||
mod model;
|
||||
mod process;
|
||||
|
||||
pub use ios::{BootedSimulator, booted_simulators, parse_ndjson, parse_simulators, simulator_log};
|
||||
pub use model::*;
|
||||
|
||||
use ide_core::process::{own_group, prepare};
|
||||
|
||||
@@ -143,6 +143,9 @@ impl Default for GitAnnotateSettings {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GitSettings {
|
||||
/// Git integration on: off, the IDE finds no repositories and runs no git at all
|
||||
/// (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI.
|
||||
pub enabled: bool,
|
||||
pub annotate: GitAnnotateSettings,
|
||||
/// Show blame after the current editor line.
|
||||
pub inline_blame: bool,
|
||||
@@ -201,6 +204,7 @@ pub struct GitSettings {
|
||||
impl Default for GitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
annotate: GitAnnotateSettings::default(),
|
||||
inline_blame: false,
|
||||
inline_blame_clickable: true,
|
||||
@@ -613,6 +617,8 @@ pub struct TerminalSettings {
|
||||
pub mouse_reporting: bool,
|
||||
pub copy_on_selection: bool,
|
||||
pub paste_on_middle_click: bool,
|
||||
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
|
||||
pub right_click_paste: bool,
|
||||
pub override_ide_shortcuts: bool,
|
||||
pub shell_integration: bool,
|
||||
pub highlight_hyperlinks: bool,
|
||||
@@ -651,6 +657,7 @@ impl Default for TerminalSettings {
|
||||
mouse_reporting: true,
|
||||
copy_on_selection: false,
|
||||
paste_on_middle_click: true,
|
||||
right_click_paste: false,
|
||||
override_ide_shortcuts: true,
|
||||
shell_integration: true,
|
||||
highlight_hyperlinks: true,
|
||||
@@ -755,6 +762,14 @@ mod tests {
|
||||
assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_defaults_enabled_and_can_be_disabled() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
let off: GitSettings = serde_json::from_str(r#"{"enabled":false}"#).unwrap();
|
||||
assert!(missing.enabled);
|
||||
assert!(!off.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_submodules_defaults_on_and_can_be_disabled() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Machine code of a native program (DAP `disassemble`), for the Disassembly view.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
|
||||
/// The most instructions one request asks for.
|
||||
pub const MAX_INSTRUCTIONS: u32 = 1000;
|
||||
|
||||
/// One disassembled instruction.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Instruction {
|
||||
/// Address as the adapter writes it (`0x5555…`); also a memory reference for the next request.
|
||||
pub address: String,
|
||||
/// The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`).
|
||||
pub instruction: String,
|
||||
/// Its machine code as hex (`488b45d8`), when the adapter sends it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub bytes: Option<String>,
|
||||
/// The function it belongs to, when the adapter names it (often on the first instruction only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub symbol: Option<String>,
|
||||
}
|
||||
|
||||
/// `disassemble`'s instructions in order; `None` for the padding adapters put where there is no
|
||||
/// code (`presentationHint: "invalid"`, or no address).
|
||||
pub(crate) fn instructions(body: &Value) -> Vec<Option<Instruction>> {
|
||||
let text = |i: &Value, k: &str| i.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
let Some(list) = body.get("instructions").and_then(Value::as_array) else { return Vec::new() };
|
||||
list.iter()
|
||||
.map(|i| {
|
||||
if i.get("presentationHint").and_then(Value::as_str) == Some("invalid") {
|
||||
return None;
|
||||
}
|
||||
Some(Instruction {
|
||||
address: text(i, "address")?,
|
||||
instruction: text(i, "instruction").unwrap_or_default(),
|
||||
bytes: text(i, "instructionBytes"),
|
||||
symbol: text(i, "symbol"),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A memory reference or address as a number (`0x7ffd…` or decimal).
|
||||
pub(crate) fn address(reference: &str) -> Option<u128> {
|
||||
let r = reference.trim();
|
||||
match r.strip_prefix("0x").or_else(|| r.strip_prefix("0X")) {
|
||||
Some(hex) => u128::from_str_radix(hex, 16).ok(),
|
||||
None => r.parse().ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the instruction at `index` is the one at `reference`. References that are not
|
||||
/// addresses cannot be checked and pass.
|
||||
pub(crate) fn at_index(instructions: &[Option<Instruction>], reference: &str, index: usize) -> bool {
|
||||
let Some(want) = address(reference) else { return instructions.len() > index };
|
||||
instructions.get(index).and_then(Option::as_ref).and_then(|i| address(&i.address)) == Some(want)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn reads_gdbs_instructions() {
|
||||
// GDB 17.1 at the reporter-style C fixture's loop line.
|
||||
let body = json!({"instructions": [
|
||||
{"address": "0x5555555551f5", "instruction": "mov -0x2c(%rbp),%eax", "instructionBytes": "8b45d4", "line": 14},
|
||||
{"address": "0x5555555551f8", "instruction": "cltq", "instructionBytes": "4898", "symbol": "sum"},
|
||||
]});
|
||||
let got = instructions(&body);
|
||||
assert_eq!(
|
||||
got[0],
|
||||
Some(Instruction {
|
||||
address: "0x5555555551f5".into(),
|
||||
instruction: "mov -0x2c(%rbp),%eax".into(),
|
||||
bytes: Some("8b45d4".into()),
|
||||
symbol: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(got[1].as_ref().unwrap().symbol.as_deref(), Some("sum"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_is_not_an_instruction() {
|
||||
let body = json!({"instructions": [
|
||||
{"address": "0xfff0", "instruction": "", "presentationHint": "invalid"},
|
||||
{"instruction": "??"},
|
||||
{"address": "0x10000", "instruction": "nop"},
|
||||
]});
|
||||
let got = instructions(&body);
|
||||
assert_eq!((got[0].is_none(), got[1].is_none(), got[2].is_some()), (true, true, true));
|
||||
assert!(instructions(&json!({})).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_reference_by_its_address() {
|
||||
let list = instructions(&json!({"instructions": [
|
||||
{"address": "0x00001000", "instruction": "push %rbp"},
|
||||
{"address": "0x1001", "instruction": "mov %rsp,%rbp"},
|
||||
]}));
|
||||
assert!(at_index(&list, "0x1001", 1));
|
||||
assert!(at_index(&list, "4097", 1));
|
||||
assert!(at_index(&list, "0X1000", 0));
|
||||
assert!(!at_index(&list, "0x1001", 0));
|
||||
assert!(!at_index(&list, "0x1001", 2));
|
||||
assert!(at_index(&list, "frame-3", 1), "opaque references cannot be checked");
|
||||
assert_eq!(address("0xffffffffffffffff1"), Some(0xffffffffffffffff1));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod debugpy;
|
||||
mod disassembly;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
@@ -20,12 +21,14 @@ mod js_debug;
|
||||
mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
pub mod unity;
|
||||
|
||||
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use connection::{Connection, DapError};
|
||||
pub use disassembly::{Instruction, MAX_INSTRUCTIONS};
|
||||
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
|
||||
use futures::future::join_all;
|
||||
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
|
||||
@@ -33,6 +36,7 @@ use ide_language::LanguageRegistry;
|
||||
pub use js_cdp::JsResponseRule;
|
||||
pub use js_debug::JsResponseBody;
|
||||
pub use jvm_memory::*;
|
||||
pub use memory::{MAX_READ, MemoryBlock};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -159,6 +163,12 @@ pub struct DebugCapabilities {
|
||||
/// A stream chain can be traced while the program runs it ([`DebugManager::stream_trace`]).
|
||||
/// Can change during the session, like `jvm_instances`.
|
||||
pub stream_trace: bool,
|
||||
/// The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View.
|
||||
pub read_memory: bool,
|
||||
/// The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view.
|
||||
pub disassemble: bool,
|
||||
/// Steps can move by one instruction ([`DebugManager::step_instruction`]).
|
||||
pub instruction_stepping: bool,
|
||||
}
|
||||
|
||||
/// Result of [`DebugManager::redefine_classes`].
|
||||
@@ -225,6 +235,10 @@ pub struct StackFrame {
|
||||
pub column: u32,
|
||||
/// `subtle` frames (library/generated) are collapsed in the UI.
|
||||
pub presentation_hint: Option<String>,
|
||||
/// The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub instruction_pointer_reference: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -249,6 +263,10 @@ pub struct Variable {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub lazy: bool,
|
||||
/// Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub memory_reference: Option<String>,
|
||||
}
|
||||
|
||||
/// A completion the adapter offers for an expression (DAP `completions`).
|
||||
@@ -611,6 +629,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
|
||||
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
presentation_hint: hint,
|
||||
instruction_pointer_reference: f
|
||||
.get("instructionPointerReference")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|r| !r.is_empty())
|
||||
.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -687,6 +710,9 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities {
|
||||
js_page: false,
|
||||
live_evaluate: false,
|
||||
stream_trace: false,
|
||||
read_memory: has("supportsReadMemoryRequest"),
|
||||
disassemble: has("supportsDisassembleRequest"),
|
||||
instruction_stepping: has("supportsSteppingGranularity"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -775,9 +801,15 @@ pub(crate) fn variable_from(v: &Value) -> Variable {
|
||||
variables_reference: v.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
|
||||
evaluate_name: s("evaluateName"),
|
||||
lazy: v.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
|
||||
memory_reference: memory_reference(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable's or evaluation result's `memoryReference`.
|
||||
fn memory_reference(v: &Value) -> Option<String> {
|
||||
v.get("memoryReference").and_then(Value::as_str).filter(|r| !r.is_empty()).map(str::to_owned)
|
||||
}
|
||||
|
||||
async fn session_variables(session: &Session, reference: i64) -> IdeResult<Vec<Variable>> {
|
||||
let body =
|
||||
session.conn.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT).await?;
|
||||
@@ -801,6 +833,7 @@ async fn resolve_in(session: &Session, variable: Variable) -> IdeResult<Variable
|
||||
value: value.value,
|
||||
variables_reference: value.variables_reference,
|
||||
lazy: value.lazy,
|
||||
memory_reference: value.memory_reference.or(variable.memory_reference),
|
||||
},
|
||||
_ => variable,
|
||||
})
|
||||
@@ -1333,7 +1366,7 @@ impl DebugManager {
|
||||
"supportsProgressReporting": true,
|
||||
// kotlin-lsp sends `invalidated` either way.
|
||||
"supportsInvalidatedEvent": is_kotlin_lsp,
|
||||
"supportsMemoryReferences": false,
|
||||
"supportsMemoryReferences": true,
|
||||
"supportsArgsCanBeInterpretedByShell": false,
|
||||
}),
|
||||
INIT_TIMEOUT,
|
||||
@@ -1791,6 +1824,7 @@ impl DebugManager {
|
||||
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
|
||||
evaluate_name: evaluate_name.or(Some(name)),
|
||||
lazy: false,
|
||||
memory_reference: memory_reference(&body),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1928,6 +1962,7 @@ impl DebugManager {
|
||||
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
|
||||
evaluate_name: Some(expression),
|
||||
lazy: body.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
|
||||
memory_reference: memory_reference(&body),
|
||||
};
|
||||
if !session.spec.resolve_lazy_variables {
|
||||
return Ok(result);
|
||||
@@ -2019,6 +2054,22 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn step(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
|
||||
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id })).await
|
||||
}
|
||||
|
||||
/// Step Over / Into Instruction: a step by one machine instruction (DAP `granularity`).
|
||||
pub async fn step_instruction(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
|
||||
let session = self.session(s)?;
|
||||
if !session.supports("supportsSteppingGranularity") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"debug adapter `{}` cannot step by instruction",
|
||||
session.adapter
|
||||
)));
|
||||
}
|
||||
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id, "granularity": "instruction" })).await
|
||||
}
|
||||
|
||||
async fn step_with(&self, s: DebugSessionId, thread_id: i64, kind: StepKind, args: Value) -> IdeResult<()> {
|
||||
let command = match kind {
|
||||
StepKind::Over => "next",
|
||||
StepKind::Into => "stepIn",
|
||||
@@ -2030,7 +2081,7 @@ impl DebugManager {
|
||||
quirks.step_sent();
|
||||
}
|
||||
let ticket = session.suspended.ticket();
|
||||
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
|
||||
let sent = session.conn.request_timeout(command, args, REQUEST_TIMEOUT).await;
|
||||
step_settled(&session, sent)?;
|
||||
// A step runs its thread; other threads stopped by their own events stay stopped.
|
||||
session.finish_resume(ticket, thread_id, false);
|
||||
@@ -2184,6 +2235,74 @@ impl DebugManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `count` bytes (at most [`MAX_READ`]) from `offset` bytes after `memory_reference`, which
|
||||
/// comes from a variable, an evaluation result or an earlier read's address.
|
||||
pub async fn read_memory(
|
||||
&self,
|
||||
s: DebugSessionId,
|
||||
memory_reference: String,
|
||||
offset: i64,
|
||||
count: u32,
|
||||
) -> IdeResult<MemoryBlock> {
|
||||
let session = self.session(s)?;
|
||||
if !session.supports("supportsReadMemoryRequest") {
|
||||
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot read memory", session.adapter)));
|
||||
}
|
||||
let count = count.min(MAX_READ);
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
"readMemory",
|
||||
json!({ "memoryReference": memory_reference, "offset": offset, "count": count }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
memory::memory_block(&body, count)
|
||||
}
|
||||
|
||||
/// `count` instructions (at most [`MAX_INSTRUCTIONS`]) from `before` instructions ahead of
|
||||
/// `memory_reference` (a frame's instruction pointer or an instruction's address). Adapters that
|
||||
/// cannot disassemble backwards start at the reference instead.
|
||||
pub async fn disassemble(
|
||||
&self,
|
||||
s: DebugSessionId,
|
||||
memory_reference: String,
|
||||
before: u32,
|
||||
count: u32,
|
||||
) -> IdeResult<Vec<Instruction>> {
|
||||
let session = self.session(s)?;
|
||||
if !session.supports("supportsDisassembleRequest") {
|
||||
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot disassemble", session.adapter)));
|
||||
}
|
||||
let count = count.clamp(1, MAX_INSTRUCTIONS);
|
||||
let before = before.min(count - 1);
|
||||
let request = |offset: i64, count: u32| {
|
||||
session.conn.request_timeout(
|
||||
"disassemble",
|
||||
json!({
|
||||
"memoryReference": memory_reference,
|
||||
"offset": 0,
|
||||
"instructionOffset": offset,
|
||||
"instructionCount": count,
|
||||
"resolveSymbols": true,
|
||||
}),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
};
|
||||
if before > 0 {
|
||||
// GDB (up to 17 at least) answers a negative instruction offset with the instructions after
|
||||
// the reference, or fails: only an answer with the reference in its place is used.
|
||||
if let Ok(body) = request(-i64::from(before), count).await {
|
||||
let instructions = disassembly::instructions(&body);
|
||||
if disassembly::at_index(&instructions, &memory_reference, before as usize) {
|
||||
return Ok(instructions.into_iter().flatten().collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
let body = request(0, count - before).await?;
|
||||
Ok(disassembly::instructions(&body).into_iter().flatten().collect())
|
||||
}
|
||||
|
||||
pub fn capabilities(&self, s: DebugSessionId) -> IdeResult<DebugCapabilities> {
|
||||
Ok(session_capabilities(&*self.session(s)?))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Raw memory of a native program (DAP `readMemory`), for the Memory View.
|
||||
|
||||
use base64::Engine;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
|
||||
/// The most bytes one read asks for: a few pages of the view, never a whole mapping.
|
||||
pub const MAX_READ: u32 = 64 * 1024;
|
||||
|
||||
/// Answer of `readMemory`: `data` starts at `address`; the `unreadable_bytes` after it could not be read.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MemoryBlock {
|
||||
/// Address of the first byte, as the adapter writes it (`0x7ffd…`; may be wider than 53 bits).
|
||||
pub address: String,
|
||||
pub data: Vec<u8>,
|
||||
pub unreadable_bytes: u32,
|
||||
}
|
||||
|
||||
/// `readMemory`'s body for a read of `count` bytes. Adapters leave `data` out (or empty) when
|
||||
/// nothing could be read; the bytes asked for then count as unreadable.
|
||||
pub(crate) fn memory_block(body: &Value, count: u32) -> IdeResult<MemoryBlock> {
|
||||
let address = match body.get("address") {
|
||||
Some(Value::String(a)) if !a.is_empty() => a.clone(),
|
||||
Some(Value::Number(n)) => n.to_string(),
|
||||
_ => return Err(IdeError::internal("the debug adapter answered readMemory without an address")),
|
||||
};
|
||||
let mut data = match body.get("data").and_then(Value::as_str) {
|
||||
Some(b64) if !b64.is_empty() => base64::engine::general_purpose::STANDARD
|
||||
.decode(b64)
|
||||
.map_err(|e| IdeError::internal(format!("the debug adapter sent memory that is not base64: {e}")))?,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
data.truncate(count as usize);
|
||||
// At most the rest of what was asked for (the data is never more than that).
|
||||
let rest = count - data.len() as u32;
|
||||
let unreadable_bytes = match body.get("unreadableBytes").and_then(Value::as_u64) {
|
||||
Some(n) => n.min(u64::from(rest)) as u32,
|
||||
None if data.is_empty() => count,
|
||||
None => 0,
|
||||
};
|
||||
Ok(MemoryBlock { address, data, unreadable_bytes })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn decodes_the_bytes_and_keeps_the_address_as_written() {
|
||||
// The reporter's `&msg[0]` (#5921): "Hello, World!\n" and its terminator.
|
||||
let body = json!({"address": "0x000000016FDFE9A0", "data": "SGVsbG8sIFdvcmxkIQoA"});
|
||||
let block = memory_block(&body, 15).unwrap();
|
||||
assert_eq!(block.address, "0x000000016FDFE9A0");
|
||||
assert_eq!(block.data, b"Hello, World!\n\0");
|
||||
assert_eq!(block.unreadable_bytes, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_data_is_unreadable_not_empty() {
|
||||
let block = memory_block(&json!({"address": "0x0"}), 256).unwrap();
|
||||
assert!(block.data.is_empty());
|
||||
assert_eq!(block.unreadable_bytes, 256);
|
||||
let block = memory_block(&json!({"address": "0x0", "data": "", "unreadableBytes": 16}), 256).unwrap();
|
||||
assert_eq!(block.unreadable_bytes, 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_read_reports_the_rest_as_unreadable() {
|
||||
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 13}), 16).unwrap();
|
||||
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1, 2][..], 13));
|
||||
// Counts that disagree with the request are clamped to it.
|
||||
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 99}), 16).unwrap();
|
||||
assert_eq!(block.unreadable_bytes, 13);
|
||||
let block = memory_block(&json!({"address": "0x1000", "data": "AAECAw=="}), 2).unwrap();
|
||||
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1][..], 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_answers_without_an_address_or_with_bad_data() {
|
||||
assert!(memory_block(&json!({"data": "AA=="}), 1).is_err());
|
||||
assert!(memory_block(&json!({"address": "0x10", "data": "not base64!"}), 1).is_err());
|
||||
assert_eq!(memory_block(&json!({"address": 4096, "data": "AA=="}), 1).unwrap().address, "4096");
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ mod stream_trace;
|
||||
|
||||
use super::*;
|
||||
use crate::adapter::{AdapterIo, LaunchFuture};
|
||||
use base64::Engine;
|
||||
use ide_core::IdeEvent;
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_jsonrpc::framing;
|
||||
@@ -195,6 +196,21 @@ struct Script {
|
||||
accept: &'static [&'static str],
|
||||
/// Requests of the adapter's own answered with a body and followed by events.
|
||||
custom: Option<fn(&Value) -> Option<CustomReply>>,
|
||||
/// Advertise `supportsReadMemoryRequest`: memory below 0x1010 reads as its low address byte,
|
||||
/// memory from there on is unmapped.
|
||||
read_memory: bool,
|
||||
/// Advertise `supportsDisassembleRequest` and `supportsSteppingGranularity`, disassembling like
|
||||
/// this adapter: 4-byte instructions from 0x1000 to 0x1100, nothing mapped around them.
|
||||
disassemble: Option<FakeDisassembler>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum FakeDisassembler {
|
||||
/// Negative instruction offsets work; unmapped places are `invalid` padding.
|
||||
Lldb,
|
||||
/// GDB 17: disassembles `instructionOffset + instructionCount` instructions from the reference and
|
||||
/// drops the first `instructionOffset` of them, the way a Python slice does.
|
||||
Gdb,
|
||||
}
|
||||
|
||||
/// The answer to a request of the adapter's own: the response body, then events (name, body).
|
||||
@@ -242,6 +258,8 @@ impl Default for Script {
|
||||
empty_thread_responses: 0,
|
||||
accept: &[],
|
||||
custom: None,
|
||||
read_memory: false,
|
||||
disassemble: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -328,6 +346,9 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
"supportsDataBreakpoints": true,
|
||||
"supportsStepInTargetsRequest": true,
|
||||
"supportsRestartFrame": true,
|
||||
"supportsReadMemoryRequest": script.read_memory,
|
||||
"supportsDisassembleRequest": script.disassemble.is_some(),
|
||||
"supportsSteppingGranularity": script.disassemble.is_some(),
|
||||
"exceptionBreakpointFilters": [
|
||||
{"filter": "raised", "label": "Raised"},
|
||||
{"filter": "uncaught", "label": "Uncaught", "default": true, "description": "Uncaught exceptions"},
|
||||
@@ -570,7 +591,58 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
]})
|
||||
),
|
||||
},
|
||||
"evaluate" if msg["arguments"]["expression"] == "&msg[0]" => ok!(
|
||||
msg,
|
||||
json!({"result": "0x1000 \"Hello\"", "type": "char *", "variablesReference": 1, "memoryReference": "0x1000"})
|
||||
),
|
||||
"evaluate" => ok!(msg, json!({"result": "42", "type": "int", "variablesReference": 0})),
|
||||
"readMemory" => {
|
||||
let args = &msg["arguments"];
|
||||
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
|
||||
let start = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
|
||||
let count = args["count"].as_i64().unwrap();
|
||||
const END: i64 = 0x1010;
|
||||
if start >= END {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "readMemory", "success": false, "message": format!("Cannot access memory at address {start:#x}")})
|
||||
);
|
||||
} else {
|
||||
let bytes: Vec<u8> = (start..(start + count).min(END)).map(|a| a as u8).collect();
|
||||
ok!(
|
||||
msg,
|
||||
json!({"address": format!("{start:#x}"), "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "unreadableBytes": count - bytes.len() as i64})
|
||||
);
|
||||
}
|
||||
}
|
||||
"disassemble" => {
|
||||
let args = &msg["arguments"];
|
||||
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
|
||||
let pc = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
|
||||
let (offset, count) =
|
||||
(args["instructionOffset"].as_i64().unwrap(), args["instructionCount"].as_i64().unwrap());
|
||||
let insn = |a: i64| {
|
||||
if (0x1000..0x1100).contains(&a) {
|
||||
json!({"address": format!("{a:#x}"), "instruction": format!("insn {}", (a - 0x1000) / 4), "instructionBytes": "90909090"})
|
||||
} else {
|
||||
json!({"address": format!("{a:#x}"), "instruction": "", "presentationHint": "invalid"})
|
||||
}
|
||||
};
|
||||
let addresses: Option<Vec<i64>> = match script.disassemble.unwrap() {
|
||||
FakeDisassembler::Lldb => Some((0..count).map(|i| pc + 4 * (offset + i)).collect()),
|
||||
FakeDisassembler::Gdb if offset + count < 0 => None,
|
||||
FakeDisassembler::Gdb => {
|
||||
let all: Vec<i64> = (0..offset + count).map(|i| pc + 4 * i).collect();
|
||||
let from = if offset >= 0 { offset } else { (all.len() as i64 + offset).max(0) };
|
||||
Some(all[from as usize..].to_vec())
|
||||
}
|
||||
};
|
||||
match addresses {
|
||||
Some(a) => ok!(msg, json!({"instructions": a.into_iter().map(insn).collect::<Vec<_>>()})),
|
||||
None => send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "disassemble", "success": false, "message": "Argument 'count' should be an non-negative integer."})
|
||||
),
|
||||
}
|
||||
}
|
||||
"completions" => ok!(
|
||||
msg,
|
||||
json!({"targets": [
|
||||
@@ -1952,6 +2024,146 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn memory_view_reads_memory_from_a_reference() {
|
||||
let h = harness(Script { read_memory: true, ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
assert_eq!(
|
||||
h.request("initialize")["arguments"]["supportsMemoryReferences"],
|
||||
true,
|
||||
"adapters only send references when asked"
|
||||
);
|
||||
assert!(h.manager.capabilities(id).unwrap().read_memory);
|
||||
|
||||
let pointer = h.manager.evaluate_in(id, Some(10), "&msg[0]".into(), Some("watch".into())).await.unwrap();
|
||||
assert_eq!(pointer.memory_reference.as_deref(), Some("0x1000"));
|
||||
let plain = h.manager.evaluate(id, Some(10), "n".into()).await.unwrap();
|
||||
assert_eq!(plain.memory_reference, None);
|
||||
|
||||
let block = h.manager.read_memory(id, "0x1000".into(), 0, 8).await.unwrap();
|
||||
assert_eq!(block, MemoryBlock { address: "0x1000".into(), data: (0..8).collect(), unreadable_bytes: 0 });
|
||||
assert_eq!(h.request("readMemory")["arguments"], json!({"memoryReference": "0x1000", "offset": 0, "count": 8}));
|
||||
|
||||
// Paging back and forth goes through `offset` on the same reference; the end of the mapping
|
||||
// comes back as unreadable bytes.
|
||||
let block = h.manager.read_memory(id, "0x1000".into(), 8, 16).await.unwrap();
|
||||
assert_eq!((block.address.as_str(), block.data.len(), block.unreadable_bytes), ("0x1008", 8, 8));
|
||||
assert_eq!(block.data[0], 0x08);
|
||||
|
||||
// Unmapped memory is the adapter's error, and the session goes on.
|
||||
let err = h.manager.read_memory(id, "0x1000".into(), 0x20, 16).await.unwrap_err();
|
||||
assert!(err.to_string().contains("Cannot access memory at address 0x1020"), "{err}");
|
||||
assert!(!h.manager.threads(id).await.unwrap().is_empty());
|
||||
|
||||
let _ = h.manager.read_memory(id, "0x1000".into(), 0, u32::MAX).await;
|
||||
let last = h.log.lock().iter().rev().find(|m| m["command"] == "readMemory").cloned().unwrap();
|
||||
assert_eq!(last["arguments"]["count"], MAX_READ, "one read never asks for more than a few pages");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn memory_view_says_when_the_adapter_cannot_read_memory() {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
assert!(!h.manager.capabilities(id).unwrap().read_memory);
|
||||
let err = h.manager.read_memory(id, "0x1000".into(), 0, 16).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(err.to_string().contains("debug adapter `debugpy` cannot read memory"), "{err}");
|
||||
assert!(!h.commands().iter().any(|c| c == "readMemory"), "nothing is sent to an adapter without support");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_keep_their_memory_reference() {
|
||||
let v = variable_from(
|
||||
&json!({"name": "words", "value": "0x4010", "variablesReference": 3, "memoryReference": "0x4010"}),
|
||||
);
|
||||
assert_eq!(v.memory_reference.as_deref(), Some("0x4010"));
|
||||
assert_eq!(variable_from(&json!({"name": "n", "value": "1", "memoryReference": ""})).memory_reference, None);
|
||||
let json = serde_json::to_value(variable_from(&json!({"name": "n", "value": "1"}))).unwrap();
|
||||
assert!(json.get("memoryReference").is_none(), "absent, not null, for the UI's optional field");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disassembly_reads_instructions_around_the_instruction_pointer() {
|
||||
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let caps = h.manager.capabilities(id).unwrap();
|
||||
assert!(caps.disassemble && caps.instruction_stepping);
|
||||
|
||||
let list = h.manager.disassemble(id, "0x1010".into(), 2, 5).await.unwrap();
|
||||
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
|
||||
assert_eq!(addresses, ["0x1008", "0x100c", "0x1010", "0x1014", "0x1018"]);
|
||||
assert_eq!((list[2].instruction.as_str(), list[2].bytes.as_deref()), ("insn 4", Some("90909090")));
|
||||
assert_eq!(
|
||||
requests(&h, "disassemble")[0],
|
||||
json!({"memoryReference": "0x1010", "offset": 0, "instructionOffset": -2, "instructionCount": 5, "resolveSymbols": true})
|
||||
);
|
||||
|
||||
// Before the first mapped instruction the adapter pads; the padding is not shown.
|
||||
let list = h.manager.disassemble(id, "0x1004".into(), 4, 6).await.unwrap();
|
||||
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
|
||||
assert_eq!(addresses, ["0x1000", "0x1004", "0x1008"]);
|
||||
|
||||
let _ = h.manager.disassemble(id, "0x1000".into(), 0, u32::MAX).await;
|
||||
assert_eq!(requests(&h, "disassemble").last().unwrap()["instructionCount"], MAX_INSTRUCTIONS);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disassembly_starts_at_the_instruction_pointer_when_the_adapter_cannot_go_back() {
|
||||
let h = harness(Script { disassemble: Some(FakeDisassembler::Gdb), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
// GDB's answer to "4 before" leaves out the instruction pointer; the view asks again from it.
|
||||
let list = h.manager.disassemble(id, "0x1010".into(), 4, 10).await.unwrap();
|
||||
assert_eq!(list.first().map(|i| i.address.as_str()), Some("0x1010"));
|
||||
assert_eq!(list.len(), 6);
|
||||
let offsets: Vec<Value> = requests(&h, "disassemble").iter().map(|r| r["instructionOffset"].clone()).collect();
|
||||
assert_eq!(offsets, [json!(-4), json!(0)]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn instruction_steps_send_the_granularity_and_line_steps_do_not() {
|
||||
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.step_instruction(id, 1, StepKind::Into).await.unwrap();
|
||||
assert_eq!(requests(&h, "stepIn").last().unwrap(), &json!({"threadId": 1, "granularity": "instruction"}));
|
||||
h.manager.step(id, 1, StepKind::Over).await.unwrap();
|
||||
assert_eq!(requests(&h, "next").last().unwrap(), &json!({"threadId": 1}));
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disassembly_and_instruction_steps_say_when_the_adapter_cannot() {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let caps = h.manager.capabilities(id).unwrap();
|
||||
assert!(!caps.disassemble && !caps.instruction_stepping);
|
||||
let err = h.manager.disassemble(id, "0x1000".into(), 0, 16).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(err.to_string().contains("debug adapter `debugpy` cannot disassemble"), "{err}");
|
||||
let err = h.manager.step_instruction(id, 1, StepKind::Over).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
let sent = h.commands();
|
||||
assert!(!sent.iter().any(|c| c == "disassemble" || c == "next"), "nothing is sent to an adapter without support");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_keep_their_instruction_pointer() {
|
||||
let f = frame_from(&json!({"id": 1, "name": "atoi", "line": 0, "instructionPointerReference": "0x7ffff7c4a2e0"}));
|
||||
assert_eq!(f.instruction_pointer_reference.as_deref(), Some("0x7ffff7c4a2e0"));
|
||||
let json = serde_json::to_value(frame_from(&json!({"id": 1, "name": "main"}))).unwrap();
|
||||
assert!(json.get("instructionPointerReference").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn smart_step_into_and_reset_frame() {
|
||||
let h = harness(Script::default());
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Drives real debug adapters against tiny programs (one per language), checking the
|
||||
//! launch templates and the IDEA-parity features: line / method breakpoints, Smart Step
|
||||
//! Into, Reset Frame, Force Step Over, Force Run to Cursor and Set Value.
|
||||
//! Into, Reset Frame, Force Step Over, Force Run to Cursor, Set Value, the Memory View and the Disassembly view.
|
||||
//!
|
||||
//! Ignored by default (needs the adapters installed). Run with
|
||||
//! `OPENIDEA_DAP_FIXTURES=<dir> cargo test -p ide-dap --test real_adapters -- --ignored --nocapture`
|
||||
//! where `<dir>` holds `py/app.py`, `node/app.js`, `go/demo` (built with `-N -l`),
|
||||
//! `rust/target/debug/demo` and `c/main`. Adapters not found on `PATH` are skipped.
|
||||
//! `rust/target/debug/demo` and `c/main` (whose loop function also has a `char msg[]` local, for
|
||||
//! the Memory View). Adapters not found on `PATH` are skipped.
|
||||
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_core::{DebugSessionId, IdeEvent, SharedSink};
|
||||
@@ -280,6 +281,78 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let caps = m.capabilities(s).map_err(|e| e.message)?;
|
||||
report.push(format!("capabilities: {caps:?}"));
|
||||
|
||||
// Memory View: the bytes at an address expression (the C fixture's `msg`), and an unmapped address.
|
||||
if caps.read_memory {
|
||||
match m.evaluate_in(s, Some(top.id), "&msg[0]".into(), Some("watch".into())).await {
|
||||
Ok(v) => match v.memory_reference {
|
||||
Some(r) => match m.read_memory(s, r.clone(), 0, 16).await {
|
||||
Ok(b) => report.push(format!(
|
||||
"memory view `&msg[0]` ({r}): {} = {:02x?} {:?}, {} unreadable",
|
||||
b.address,
|
||||
b.data,
|
||||
String::from_utf8_lossy(&b.data),
|
||||
b.unreadable_bytes
|
||||
)),
|
||||
Err(e) => report.push(format!("memory view `&msg[0]`: FAILED {}", e.message)),
|
||||
},
|
||||
None => report.push(format!("memory view `&msg[0]` = {}: no memory reference", v.value)),
|
||||
},
|
||||
Err(e) => report.push(format!("memory view `&msg[0]`: not evaluated ({})", e.message)),
|
||||
}
|
||||
match m.read_memory(s, "0x0".into(), 0, 16).await {
|
||||
Ok(b) => report.push(format!("memory view 0x0: {} bytes, {} unreadable", b.data.len(), b.unreadable_bytes)),
|
||||
Err(e) => report.push(format!("memory view 0x0: error `{}`", e.message)),
|
||||
}
|
||||
} else {
|
||||
report.push("memory view: readMemory not supported".into());
|
||||
}
|
||||
|
||||
// Disassembly: the instructions around the stop's instruction pointer, then two instruction steps,
|
||||
// which stay on the loop line and inside the instructions shown.
|
||||
let address = |a: &str| u128::from_str_radix(a.trim_start_matches("0x"), 16).ok();
|
||||
match (caps.disassemble, top.instruction_pointer_reference.clone()) {
|
||||
(true, Some(pc)) => match m.disassemble(s, pc.clone(), 8, 24).await {
|
||||
Ok(list) => {
|
||||
let shown = |a: &str| list.iter().position(|i| address(&i.address) == address(a));
|
||||
match shown(&pc) {
|
||||
Some(at) => report.push(format!(
|
||||
"disassembly at {pc}: {} instructions, the instruction pointer is #{at}: `{}` ({:?})",
|
||||
list.len(),
|
||||
list[at].instruction,
|
||||
list[at].bytes
|
||||
)),
|
||||
None => report.push(format!("disassembly at {pc}: FAILED, not among {list:?}")),
|
||||
}
|
||||
if caps.instruction_stepping {
|
||||
let mut steps = vec![pc];
|
||||
for _ in 0..2 {
|
||||
let seen = run.seen();
|
||||
m.step_instruction(s, thread, StepKind::Over).await.map_err(|e| e.message)?;
|
||||
run.stopped_after(seen).await.ok_or("no stop after step over instruction")?;
|
||||
let f = run.top(s, thread).await;
|
||||
if f.line != case.loop_line {
|
||||
report.push(format!(
|
||||
"step over instruction: left the loop line for {}:{}",
|
||||
f.name,
|
||||
f.line + 1
|
||||
));
|
||||
}
|
||||
steps.push(f.instruction_pointer_reference.unwrap_or_default());
|
||||
}
|
||||
let all = steps.iter().all(|a| shown(a).is_some());
|
||||
report.push(format!("step over instruction: {} (all shown: {all})", steps.join(" -> ")));
|
||||
} else {
|
||||
report.push("instruction stepping: not supported".into());
|
||||
}
|
||||
}
|
||||
Err(e) => report.push(format!("disassembly at {pc}: FAILED {}", e.message)),
|
||||
},
|
||||
(true, None) => report.push("disassembly: the top frame has no instruction pointer".into()),
|
||||
(false, _) => report.push("disassembly: not supported".into()),
|
||||
}
|
||||
// Instruction steps resumed the thread: frame ids from before them may be gone.
|
||||
let top = run.top(s, thread).await;
|
||||
|
||||
// Set Value on the first local that is an integer.
|
||||
let scopes = m.scopes(s, top.id).await.map_err(|e| e.message)?;
|
||||
for scope in scopes.iter().filter(|sc| !sc.expensive) {
|
||||
|
||||
@@ -287,19 +287,56 @@ impl ClickhousePool {
|
||||
}
|
||||
|
||||
/// `max_rows`: the rows the server may send (the skipped ones included).
|
||||
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
|
||||
fn request(
|
||||
&self,
|
||||
client: &Client,
|
||||
query_id: &str,
|
||||
max_rows: usize,
|
||||
session: &Session,
|
||||
workspace_bytes: Option<usize>,
|
||||
) -> RequestBuilder {
|
||||
let mut request = client
|
||||
.post(self.0.endpoint.clone())
|
||||
.basic_auth(&self.0.user, Some(&self.0.password))
|
||||
.header(reqwest::header::CONTENT_TYPE, "text/plain; charset=utf-8")
|
||||
.query(&self.0.settings)
|
||||
.query(&[("query_id", query_id), ("default_format", FORMAT)]);
|
||||
if workspace_bytes.is_some() && !session.strict_read_only {
|
||||
let settings: Vec<_> = self
|
||||
.0
|
||||
.settings
|
||||
.iter()
|
||||
.filter(|(name, _)| !matches!(name.as_str(), "read_overflow_mode" | "timeout_overflow_mode"))
|
||||
.collect();
|
||||
request = request.query(&settings);
|
||||
} else {
|
||||
request = request.query(&self.0.settings);
|
||||
}
|
||||
if !session.strict_read_only {
|
||||
request = request.query(&[
|
||||
("output_format_json_quote_denormals", "1".into()),
|
||||
("max_result_rows", max_rows.saturating_add(1).to_string()),
|
||||
("result_overflow_mode", "break".into()),
|
||||
]);
|
||||
if let Some(bytes) = workspace_bytes {
|
||||
request = request.query(&[
|
||||
("max_result_rows", max_rows.to_string()),
|
||||
("result_overflow_mode", "throw".into()),
|
||||
("read_overflow_mode", "throw".into()),
|
||||
("timeout_overflow_mode", "throw".into()),
|
||||
]);
|
||||
for (name, value) in [
|
||||
("max_result_bytes", bytes),
|
||||
("max_execution_time", 20),
|
||||
("cancel_http_readonly_queries_on_client_close", 1),
|
||||
("max_rows_to_read", 1_000_000),
|
||||
("max_bytes_to_read", 268_435_456),
|
||||
] {
|
||||
if !self.0.settings.iter().any(|(setting, _)| setting == name) {
|
||||
request = request.query(&[(name, value)]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
request = request.query(&[
|
||||
("output_format_json_quote_denormals", "1".into()),
|
||||
("max_result_rows", max_rows.saturating_add(1).to_string()),
|
||||
("result_overflow_mode", "break".into()),
|
||||
]);
|
||||
}
|
||||
}
|
||||
if let Some(session_id) = &session.id {
|
||||
request = request.query(&[("session_id", session_id.as_str()), ("session_timeout", "3600")]);
|
||||
@@ -376,7 +413,8 @@ impl ClickhousePool {
|
||||
));
|
||||
}
|
||||
let query_id = uuid::Uuid::new_v4().to_string();
|
||||
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), session).body(sql.to_owned());
|
||||
let request =
|
||||
self.request(&client, &query_id, skip.saturating_add(max_rows), session, None).body(sql.to_owned());
|
||||
let started = Instant::now();
|
||||
let request_error = |error: reqwest::Error| {
|
||||
if error.is_timeout() && !error.is_connect() {
|
||||
@@ -402,7 +440,7 @@ impl ClickhousePool {
|
||||
.and_then(|n| n.as_str().and_then(|n| n.parse::<u64>().ok()).or_else(|| n.as_u64()))
|
||||
});
|
||||
if !status.is_success() || exception_code.as_deref().is_some_and(|code| code != "0") {
|
||||
let body = response.bytes().await.map_err(request_error)?;
|
||||
let body = response_prefix(response).await.map_err(request_error)?;
|
||||
return Err(self.server_error(status, exception_code.as_deref(), &body));
|
||||
}
|
||||
let (columns, rows, has_more) = if format.as_deref().is_some_and(|f| f != FORMAT) {
|
||||
@@ -458,6 +496,66 @@ impl ClickhousePool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Dedicated workspace sessions consume the response before any grid truncation or formatting.
|
||||
pub(crate) async fn workspace_rows(
|
||||
&self,
|
||||
sql: &str,
|
||||
max_rows: usize,
|
||||
max_bytes: usize,
|
||||
cancel: &CancellationToken,
|
||||
mut consume: impl FnMut(&[u8]) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let mut slot = self.session(&self.0.session, cancel).await?;
|
||||
let state = slot.as_mut().expect("session was initialized");
|
||||
let mut stateless;
|
||||
let session = if self.0.use_http_session {
|
||||
state
|
||||
} else {
|
||||
stateless = state.clone();
|
||||
drop(slot);
|
||||
&mut stateless
|
||||
};
|
||||
let client = self.client()?;
|
||||
let query_id = uuid::Uuid::new_v4().to_string();
|
||||
let request = self.request(&client, &query_id, max_rows, session, Some(max_bytes)).body(sql.to_owned());
|
||||
let fetch = async {
|
||||
let mut response = request.send().await.map_err(http_error)?;
|
||||
let status = response.status();
|
||||
let metadata = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok());
|
||||
let code = metadata("X-ClickHouse-Exception-Code").map(str::to_owned);
|
||||
if !status.is_success() || code.as_deref().is_some_and(|code| code != "0") {
|
||||
let body = response_prefix(response).await.map_err(http_error)?;
|
||||
return Err(self.server_error(status, code.as_deref(), &body));
|
||||
}
|
||||
if metadata("X-ClickHouse-Format").is_some_and(|format| format != FORMAT) {
|
||||
return Err(IdeError::invalid("ClickHouse did not return the workspace response format"));
|
||||
}
|
||||
let mut received = 0;
|
||||
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
|
||||
received += chunk.len();
|
||||
if received > max_bytes {
|
||||
return Err(IdeError::invalid("Workspace input exceeds the source byte limit"));
|
||||
}
|
||||
consume(&chunk)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
() = self.0.closed.cancelled() => Err(IdeError::cancelled()),
|
||||
() = tokio::time::sleep(Duration::from_secs(25)) =>
|
||||
Err(IdeError::new(ErrorKind::TimedOut, "Workspace ClickHouse source read timed out")),
|
||||
result = fetch => result,
|
||||
};
|
||||
if result.is_ok() {
|
||||
session.initialized = true;
|
||||
} else {
|
||||
let _ = self.kill(&client, &query_id, session).await;
|
||||
}
|
||||
result.map_err(|e| self.redact_error(e))
|
||||
}
|
||||
|
||||
async fn kill(&self, client: &Client, query_id: &str, session: &Session) -> IdeResult<()> {
|
||||
let mut request = client
|
||||
.post(self.0.endpoint.clone())
|
||||
@@ -474,7 +572,7 @@ impl ClickhousePool {
|
||||
.get("X-ClickHouse-Exception-Code")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
let body = response.bytes().await.map_err(http_error)?;
|
||||
let body = response_prefix(response).await.map_err(http_error)?;
|
||||
if status.is_success() && !code.as_deref().is_some_and(|code| code != "0") && !body.starts_with(b"Code:") {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -503,6 +601,17 @@ impl ClickhousePool {
|
||||
}
|
||||
}
|
||||
|
||||
async fn response_prefix(mut response: reqwest::Response) -> Result<Vec<u8>, reqwest::Error> {
|
||||
const LIMIT: usize = 16_384;
|
||||
let mut body = Vec::new();
|
||||
while body.len() < LIMIT {
|
||||
let Some(chunk) = response.chunk().await? else { break };
|
||||
let remaining = LIMIT - body.len();
|
||||
body.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
|
||||
|
||||
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
|
||||
@@ -1448,6 +1557,15 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn stateless_queries_do_not_wait_for_a_shared_session() {
|
||||
assert_stateless_requests_overlap(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stateless_workspace_reads_do_not_block_queries() {
|
||||
assert_stateless_requests_overlap(true).await;
|
||||
}
|
||||
|
||||
async fn assert_stateless_requests_overlap(workspace: bool) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let (started, received) = tokio::sync::oneshot::channel();
|
||||
@@ -1465,9 +1583,15 @@ mod tests {
|
||||
(first_request, second_request)
|
||||
});
|
||||
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
|
||||
let pool = Pool::connect(&source, None, None).await.unwrap();
|
||||
let Pool::Clickhouse(pool) = Pool::connect(&source, None, None).await.unwrap() else { unreachable!() };
|
||||
let cancel = CancellationToken::new();
|
||||
let first = pool.execute("SELECT 1", 1, &cancel);
|
||||
let first = async {
|
||||
if workspace {
|
||||
pool.workspace_rows("SELECT 1", 1, 1024, &cancel, |_| Ok(())).await
|
||||
} else {
|
||||
pool.execute("SELECT 1", 1, &cancel).await.map(drop)
|
||||
}
|
||||
};
|
||||
let second = async {
|
||||
received.await.unwrap();
|
||||
pool.execute("SELECT 2", 1, &cancel).await
|
||||
|
||||
@@ -1330,6 +1330,71 @@ impl Pool {
|
||||
Ok(conn.finish_read_only(owned, result).await?.1)
|
||||
}
|
||||
|
||||
pub(crate) async fn read_workspace_postgres(
|
||||
&self,
|
||||
request: &crate::workspace_input::WorkspaceInputRequest,
|
||||
selection: Option<&[&str]>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<crate::workspace_input::WorkspaceInput> {
|
||||
let Pool::Postgres(pool) = self else {
|
||||
return Err(IdeError::internal("Expected a PostgreSQL workspace connection"));
|
||||
};
|
||||
let mut conn = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
result = pool.get() => result?,
|
||||
};
|
||||
let mut backend = None;
|
||||
let read = async {
|
||||
if conn.options.read_only == PgReadOnly::Transaction {
|
||||
conn.start_read_only().await?;
|
||||
} else {
|
||||
sqlx::raw_sql("BEGIN READ ONLY").execute(&mut **conn).await.map_err(db_err)?;
|
||||
}
|
||||
let row = sqlx::raw_sql(
|
||||
"SELECT pg_catalog.pg_backend_pid(), pg_catalog.current_setting('transaction_read_only') = 'on'",
|
||||
)
|
||||
.fetch_one(&mut **conn)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
backend = Some(row.try_get::<i32, _>(0).map_err(db_err)?);
|
||||
if !row.try_get::<bool, _>(1).map_err(db_err)? {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::PermissionDenied,
|
||||
"Workspace PostgreSQL transaction is not read-only",
|
||||
));
|
||||
}
|
||||
crate::workspace_input::read_postgres(&mut conn, request, selection).await
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
() = tokio::time::sleep(Duration::from_secs(30)) =>
|
||||
Err(IdeError::new(ErrorKind::TimedOut, "Workspace PostgreSQL source read timed out")),
|
||||
result = read => result,
|
||||
};
|
||||
if result.is_ok() {
|
||||
// Do not send a PID-based cancel once a pooler may have released this backend.
|
||||
let rollback =
|
||||
tokio::time::timeout(Duration::from_secs(3), sqlx::raw_sql("ROLLBACK").execute(&mut **conn)).await;
|
||||
if matches!(rollback, Ok(Ok(_))) {
|
||||
conn.in_transaction = false;
|
||||
} else {
|
||||
conn.conn.take();
|
||||
}
|
||||
} else {
|
||||
if let Some(pid) = backend {
|
||||
let _ = tokio::time::timeout(
|
||||
Duration::from_secs(3),
|
||||
self.cancel_query(format!("SELECT pg_catalog.pg_cancel_backend({pid})")),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
conn.conn.take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
|
||||
/// the statement on the server (PostgreSQL, MySQL) and drops the connection.
|
||||
pub async fn execute(&self, sql: &str, max_rows: usize, cancel: &CancellationToken) -> IdeResult<QueryResult> {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
use super::{DbJdbcDriver, JdbcPool};
|
||||
use crate::source::{DUCKDB_URL, duck_lake_path};
|
||||
use crate::{DataSource, DbDuckLake, DbDuckLakeKind, DbManager, Pool};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
|
||||
const DUCKDB_CLASS: &str = "org.duckdb.DuckDBDriver";
|
||||
|
||||
impl DbManager {
|
||||
pub fn approve_ducklake_source(&self, source: &DataSource) -> IdeResult<()> {
|
||||
if source.duck_lake.is_none() {
|
||||
return Err(IdeError::invalid("Expected a DuckLake data source"));
|
||||
}
|
||||
source.validate_duck_lake()?;
|
||||
self.duck_lake_driver(&source.jdbc_driver)?.validate()?;
|
||||
if source.global {
|
||||
return Ok(());
|
||||
}
|
||||
self.record_jdbc_approval(source)
|
||||
}
|
||||
|
||||
fn duck_lake_driver(&self, id: &str) -> IdeResult<DbJdbcDriver> {
|
||||
let driver = self.jdbc_driver_by_id(id)?;
|
||||
driver.require_vendor("duckdb")?;
|
||||
if driver.class_name != DUCKDB_CLASS {
|
||||
return Err(IdeError::invalid("Select a DuckDB driver profile with the official DuckDB JDBC driver class"));
|
||||
}
|
||||
Ok(driver)
|
||||
}
|
||||
|
||||
/// Creates a lake in a new directory through a separate, disposable JDBC session.
|
||||
pub async fn create_ducklake(&self, jdbc_driver: &str, directory: &str) -> IdeResult<()> {
|
||||
duck_lake_path(directory, false)?;
|
||||
let driver = self.duck_lake_driver(jdbc_driver)?;
|
||||
let fields = duck_lake_fields("create", directory.to_owned(), "");
|
||||
let pool = JdbcPool::open(driver, self.jdbc_registry()?.with_file_name("jdbc"), fields).await?;
|
||||
pool.close().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn open_ducklake(&self, source: &DataSource, lake: &DbDuckLake, testing: bool) -> IdeResult<Pool> {
|
||||
source.validate_duck_lake()?;
|
||||
self.check_jdbc_project_approval(source, testing)?;
|
||||
let driver = self.duck_lake_driver(&source.jdbc_driver)?;
|
||||
let cache = self.jdbc_registry()?.with_file_name("jdbc");
|
||||
let (mode, value) = match lake.kind {
|
||||
DbDuckLakeKind::Secret => ("secret", lake.value.clone()),
|
||||
DbDuckLakeKind::File => {
|
||||
let path = self.root.join(&lake.value);
|
||||
let value = path.to_str().ok_or_else(|| IdeError::invalid("Invalid DuckLake catalog file path"))?;
|
||||
duck_lake_path(value, false)?;
|
||||
("file", value.to_owned())
|
||||
}
|
||||
};
|
||||
let fields = duck_lake_fields(mode, value, lake.data_path.as_deref().unwrap_or_default());
|
||||
JdbcPool::open(driver, cache, fields).await.map(Box::new).map(Pool::Jdbc)
|
||||
}
|
||||
}
|
||||
|
||||
fn duck_lake_fields(mode: &str, value: String, data_path: &str) -> Vec<String> {
|
||||
vec![
|
||||
"openDuckLake".into(),
|
||||
DUCKDB_CLASS.into(),
|
||||
DUCKDB_URL.into(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
(mode != "create").to_string(),
|
||||
mode.into(),
|
||||
value,
|
||||
data_path.to_owned(),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_jdbc_rejects_a_ducklake_even_with_a_file_url() {
|
||||
let source = DataSource {
|
||||
driver: crate::DbDriver::Jdbc,
|
||||
url: "jdbc:duckdb:existing.duckdb".into(),
|
||||
duck_lake: Some(DbDuckLake {
|
||||
kind: DbDuckLakeKind::File,
|
||||
value: "catalog.ducklake".into(),
|
||||
data_path: None,
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let driver = DbJdbcDriver {
|
||||
id: "duckdb".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: Some("duckdb".into()),
|
||||
jars: vec![],
|
||||
class_name: DUCKDB_CLASS.into(),
|
||||
url_template: DUCKDB_URL.into(),
|
||||
};
|
||||
let error = JdbcPool::connect(&source, None, driver, Default::default())
|
||||
.await
|
||||
.err()
|
||||
.expect("ordinary JDBC must reject DuckLake fields before opening a connection");
|
||||
assert_eq!(error.message, "DuckLake catalogs require a DuckLake connection");
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ use tokio::sync::Mutex;
|
||||
use tokio::time::timeout;
|
||||
|
||||
mod bridge;
|
||||
mod ducklake;
|
||||
|
||||
use bridge::Bridge;
|
||||
|
||||
@@ -79,6 +80,13 @@ pub fn jdbc_driver_classes(jars: &[String]) -> IdeResult<Vec<String>> {
|
||||
}
|
||||
|
||||
impl DbJdbcDriver {
|
||||
fn require_vendor(&self, vendor: &str) -> IdeResult<()> {
|
||||
if self.vendor.as_deref() != Some(vendor) {
|
||||
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate(&self) -> IdeResult<()> {
|
||||
if self.id.is_empty()
|
||||
|| self.name.trim().is_empty()
|
||||
@@ -138,6 +146,30 @@ impl DbManager {
|
||||
self.update_jdbc_driver(id, None)
|
||||
}
|
||||
|
||||
fn record_jdbc_approval(&self, source: &DataSource) -> IdeResult<()> {
|
||||
let (path, fingerprint) = self.jdbc_approval(source)?;
|
||||
persist_local(&path, fingerprint.as_bytes())
|
||||
}
|
||||
|
||||
fn jdbc_driver_by_id(&self, id: &str) -> IdeResult<DbJdbcDriver> {
|
||||
self.jdbc_drivers()?
|
||||
.into_iter()
|
||||
.find(|d| d.id == id)
|
||||
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))
|
||||
}
|
||||
|
||||
fn check_jdbc_project_approval(&self, source: &DataSource, testing: bool) -> IdeResult<()> {
|
||||
if !testing && !source.global {
|
||||
let (path, expected) = self.jdbc_approval(source)?;
|
||||
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
|
||||
return Err(IdeError::invalid(
|
||||
"Review this project's JDBC URL and properties, then save the data source before connecting",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn jdbc_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
|
||||
let registry = self.jdbc_registry()?;
|
||||
let key = serde_json::to_vec(&(&self.root, &source.id)).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
@@ -150,7 +182,10 @@ impl DbManager {
|
||||
&source.options,
|
||||
))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
if self.jdbc_password_isolated(source) {
|
||||
if let Some(lake) = &source.duck_lake {
|
||||
settings.extend_from_slice(b"\0ducklake\0");
|
||||
serde_json::to_writer(&mut settings, lake).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
} else if self.jdbc_password_isolated(source) {
|
||||
settings.extend_from_slice(b"\0jdbc-password");
|
||||
}
|
||||
Ok((
|
||||
@@ -164,8 +199,70 @@ impl DbManager {
|
||||
if source.driver != crate::DbDriver::Jdbc || source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Expected a user-managed JDBC data source"));
|
||||
}
|
||||
let (path, fingerprint) = self.jdbc_approval(source)?;
|
||||
persist_local(&path, fingerprint.as_bytes())
|
||||
if source.duck_lake.is_some() {
|
||||
return self.approve_ducklake_source(source);
|
||||
}
|
||||
self.record_jdbc_approval(source)
|
||||
}
|
||||
|
||||
/// A workspace uses only the selected host driver and a fresh in-memory database.
|
||||
pub(crate) async fn workspace_engine(&self, profile: &str) -> IdeResult<JdbcPool> {
|
||||
let driver = self
|
||||
.jdbc_drivers()?
|
||||
.into_iter()
|
||||
.find(|driver| {
|
||||
driver.id == profile
|
||||
&& driver.vendor.as_deref() == Some("duckdb")
|
||||
&& driver.class_name == "org.duckdb.DuckDBDriver"
|
||||
})
|
||||
.ok_or_else(|| IdeError::invalid("Choose an installed DuckDB JDBC driver for the workspace"))?;
|
||||
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
|
||||
JdbcPool::connect(&source, None, driver, self.jdbc_registry()?.with_file_name("jdbc")).await
|
||||
}
|
||||
|
||||
pub(crate) async fn prepare_workspace_duckdb_source(
|
||||
&self,
|
||||
source: &DataSource,
|
||||
) -> IdeResult<WorkspaceDuckDbSource> {
|
||||
let driver = self.approved_jdbc_driver(source, false)?;
|
||||
if driver.vendor.as_deref() != Some("duckdb") || driver.class_name != "org.duckdb.DuckDBDriver" {
|
||||
return Err(IdeError::invalid("Choose a saved DuckDB source with an installed DuckDB driver"));
|
||||
}
|
||||
let target = source.url.strip_prefix("jdbc:duckdb:").unwrap_or_default();
|
||||
let mut parts = target.split(';');
|
||||
let filename = parts.next().unwrap_or_default();
|
||||
let cache = self.jdbc_registry()?.with_file_name("jdbc");
|
||||
let path = cache.join("files").join(filename);
|
||||
if filename.is_empty()
|
||||
|| filename.starts_with([':', ' '])
|
||||
|| filename.starts_with("memory:")
|
||||
|| filename.starts_with("md:")
|
||||
|| filename.contains("://")
|
||||
|| !tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file())
|
||||
{
|
||||
return Err(IdeError::invalid("Choose an existing local DuckDB database file as the workspace source"));
|
||||
}
|
||||
let limits = [
|
||||
("enable_external_access", "false"),
|
||||
("allow_unsigned_extensions", "false"),
|
||||
("autoinstall_known_extensions", "false"),
|
||||
("autoload_known_extensions", "false"),
|
||||
("memory_limit", "96MiB"),
|
||||
("threads", "1"),
|
||||
("temp_directory", ""),
|
||||
("max_temp_directory_size", "0B"),
|
||||
];
|
||||
let protected = |name: &str| limits.iter().any(|(key, _)| name.trim().eq_ignore_ascii_case(key));
|
||||
if parts.any(|option| protected(option.split('=').next().unwrap_or_default())) {
|
||||
return Err(IdeError::invalid("DuckDB Workspace source URL changes a workspace read limit"));
|
||||
}
|
||||
let mut target = source.clone();
|
||||
target.read_only = true;
|
||||
target.properties.retain(|property| !protected(&property.name));
|
||||
target
|
||||
.properties
|
||||
.extend(limits.map(|(name, value)| crate::DbProperty { name: name.into(), value: value.into() }));
|
||||
Ok(WorkspaceDuckDbSource { target, driver, cache })
|
||||
}
|
||||
|
||||
pub(crate) async fn open_pool(
|
||||
@@ -174,33 +271,42 @@ impl DbManager {
|
||||
password: Option<&str>,
|
||||
testing: bool,
|
||||
) -> IdeResult<crate::Pool> {
|
||||
if let Some(lake) = &source.duck_lake {
|
||||
return self.open_ducklake(source, lake, testing).await;
|
||||
}
|
||||
if source.driver != crate::DbDriver::Jdbc {
|
||||
return crate::Pool::connect(source, password, Some(&self.root)).await;
|
||||
}
|
||||
if source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
|
||||
}
|
||||
if !testing && !source.global {
|
||||
let (path, expected) = self.jdbc_approval(source)?;
|
||||
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
|
||||
return Err(IdeError::invalid(
|
||||
"Review this project's JDBC URL and properties, then save the data source before connecting",
|
||||
));
|
||||
}
|
||||
}
|
||||
let driver = self
|
||||
.jdbc_drivers()?
|
||||
.into_iter()
|
||||
.find(|d| d.id == source.jdbc_driver)
|
||||
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))?;
|
||||
if !source.vendor.is_empty() && driver.vendor.as_deref() != Some(source.vendor.as_str()) {
|
||||
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
|
||||
}
|
||||
let driver = self.approved_jdbc_driver(source, testing)?;
|
||||
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
|
||||
.await
|
||||
.map(Box::new)
|
||||
.map(crate::Pool::Jdbc)
|
||||
}
|
||||
|
||||
fn approved_jdbc_driver(&self, source: &DataSource, testing: bool) -> IdeResult<DbJdbcDriver> {
|
||||
if source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
|
||||
}
|
||||
self.check_jdbc_project_approval(source, testing)?;
|
||||
let driver = self.jdbc_driver_by_id(&source.jdbc_driver)?;
|
||||
if !source.vendor.is_empty() {
|
||||
driver.require_vendor(&source.vendor)?;
|
||||
}
|
||||
Ok(driver)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct WorkspaceDuckDbSource {
|
||||
target: DataSource,
|
||||
driver: DbJdbcDriver,
|
||||
cache: PathBuf,
|
||||
}
|
||||
|
||||
impl WorkspaceDuckDbSource {
|
||||
pub(crate) async fn connect(self, password: Option<&str>) -> IdeResult<JdbcPool> {
|
||||
JdbcPool::connect(&self.target, password, self.driver, self.cache).await
|
||||
}
|
||||
}
|
||||
|
||||
struct Session {
|
||||
@@ -277,10 +383,12 @@ impl JdbcPool {
|
||||
driver: DbJdbcDriver,
|
||||
cache: PathBuf,
|
||||
) -> IdeResult<Self> {
|
||||
driver.validate()?;
|
||||
if source.duck_lake.is_some() {
|
||||
return Err(IdeError::invalid("DuckLake catalogs require a DuckLake connection"));
|
||||
}
|
||||
let mut fields = vec![
|
||||
"open".to_string(),
|
||||
driver.class_name,
|
||||
driver.class_name.clone(),
|
||||
source.url.clone(),
|
||||
source.user.clone(),
|
||||
password.unwrap_or_default().to_owned(),
|
||||
@@ -292,6 +400,11 @@ impl JdbcPool {
|
||||
}
|
||||
fields.extend([p.name.clone(), p.value.clone()]);
|
||||
}
|
||||
Self::open(driver, cache, fields).await
|
||||
}
|
||||
|
||||
async fn open(driver: DbJdbcDriver, cache: PathBuf, fields: Vec<String>) -> IdeResult<Self> {
|
||||
driver.validate()?;
|
||||
let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
@@ -306,7 +419,7 @@ impl JdbcPool {
|
||||
bridge: Arc::new(bridge),
|
||||
service: Session::new(0),
|
||||
consoles: Default::default(),
|
||||
shared_connection: private_database_url(&source.url),
|
||||
shared_connection: private_database_url(&fields[2]),
|
||||
version: metadata.next().flatten().unwrap_or_else(|| "Connected".into()),
|
||||
identifier_quote: metadata.next().flatten().unwrap_or_default().trim().into(),
|
||||
})
|
||||
@@ -748,7 +861,9 @@ mod tests {
|
||||
assert!(catalogs.contains(&vec![Some("memory".into()), Some("1".into())]));
|
||||
assert!(catalogs.contains(&vec![Some("first".into()), Some("0".into())]));
|
||||
assert!(catalogs.contains(&vec![Some(archive.into()), Some("0".into())]));
|
||||
let schemas = pool.metadata(&["schemas", archive]).await?;
|
||||
let mut schemas = pool.metadata(&["schemas", archive]).await?;
|
||||
// DuckDB JDBC 1.1.3 also lists these system schemas for attached catalogs.
|
||||
schemas.retain(|row| !matches!(row[0].as_deref(), Some("information_schema" | "pg_catalog")));
|
||||
assert_eq!(schemas, ["main", "qaSimilar", "qa_%"].map(|schema| vec![Some(schema.into())]));
|
||||
let tables = pool.metadata(&["tables", "qa_%", archive]).await?;
|
||||
assert_eq!(tables.len(), 1);
|
||||
|
||||
+114
-14
@@ -25,14 +25,17 @@ pub mod sql;
|
||||
pub mod tools;
|
||||
mod watch;
|
||||
pub use watch::SourcesWatch;
|
||||
pub mod workspace;
|
||||
pub mod workspace_input;
|
||||
|
||||
pub use catalog::{CatalogDatabase, CatalogSchema, SourceCatalog};
|
||||
pub use conn::{Held, Pool, QueryResult, ResultColumn, TruncatedCell};
|
||||
pub use history::HistoryEntry;
|
||||
pub use plan::{PlanNode, PlanProperty};
|
||||
pub use source::{
|
||||
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
|
||||
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
DataSource, DbColor, DbDriver, DbDuckLake, DbDuckLakeKind, DbExternalTunnel, DbIntrospection, DbOptions,
|
||||
DbProperty, DbSchemaSelection, DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode,
|
||||
DbVisibilityChange,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
@@ -201,7 +204,7 @@ impl DbKeyKind {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableDetails")]
|
||||
pub struct TableDetails {
|
||||
@@ -213,6 +216,53 @@ pub struct TableDetails {
|
||||
pub indexes: Vec<IndexInfo>,
|
||||
pub foreign_keys: Vec<ForeignKey>,
|
||||
pub triggers: Vec<TriggerInfo>,
|
||||
/// The role owning the table (PostgreSQL); `None` where the schema owns its tables.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
/// The table's tablespace, the database's default one when it names none (PostgreSQL).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub tablespace: Option<String>,
|
||||
/// The table access method (PostgreSQL's `heap`, …); `None` for a partitioned table, and on
|
||||
/// the engines without one.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub access_method: Option<String>,
|
||||
/// The storage parameters set on the table, as `(name, value)`: PostgreSQL's reloptions,
|
||||
/// its TOAST table's prefixed `toast.`. `None` on the engines without any.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub storage_options: Option<Vec<(String, String)>>,
|
||||
/// The partition key (`RANGE (created)`); `None` when the table isn't partitioned.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub partitioning: Option<String>,
|
||||
/// Whether the table is logged, unlogged or temporary (PostgreSQL).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub persistence: Option<DbPersistence>,
|
||||
}
|
||||
|
||||
/// Whether a table's changes are written to the write-ahead log, and whether it outlives the session.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DbPersistence {
|
||||
Permanent,
|
||||
Unlogged,
|
||||
Temporary,
|
||||
}
|
||||
|
||||
impl DbPersistence {
|
||||
/// PostgreSQL's `pg_class.relpersistence`.
|
||||
fn from_catalog(v: &str) -> Option<Self> {
|
||||
match v {
|
||||
"p" => Some(Self::Permanent),
|
||||
"u" => Some(Self::Unlogged),
|
||||
"t" => Some(Self::Temporary),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One object privilege on a table: `grantee` may run `privilege` (`SELECT`, …), granted
|
||||
@@ -330,6 +380,7 @@ pub struct DbManager {
|
||||
sessions: Mutex<HashMap<String, Session>>,
|
||||
/// Result pages read on from where the previous page stopped, not by running the statement again.
|
||||
cursors: conn::Cursors,
|
||||
workspace_run: tokio::sync::Mutex<()>,
|
||||
/// The data sources as last read from disk, for [`DbManager::reconcile_sources`]
|
||||
/// (`None` until [`DbManager::watch_sources`]).
|
||||
on_disk: Mutex<Option<Vec<DataSource>>>,
|
||||
@@ -379,6 +430,25 @@ async fn catalog_rows(pool: &Pool, q: &str) -> IdeResult<Vec<Vec<Option<String>>
|
||||
}
|
||||
}
|
||||
|
||||
/// One [`sql::table_properties`] row into `details`.
|
||||
fn read_table_properties(details: &mut TableDetails, row: Vec<Option<String>>) {
|
||||
let mut it = row.into_iter().map(|v| v.filter(|v| !v.is_empty()));
|
||||
let mut next = || it.next().flatten();
|
||||
details.owner = next();
|
||||
details.tablespace = next();
|
||||
details.access_method = next();
|
||||
details.storage_options = Some(
|
||||
next()
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.filter_map(|o| o.split_once('='))
|
||||
.map(|(name, value)| (name.to_owned(), value.to_owned()))
|
||||
.collect(),
|
||||
);
|
||||
details.partitioning = next();
|
||||
details.persistence = next().as_deref().and_then(DbPersistence::from_catalog);
|
||||
}
|
||||
|
||||
fn flag(v: &Option<String>) -> bool {
|
||||
matches!(v.as_deref(), Some("1" | "t" | "true" | "YES"))
|
||||
}
|
||||
@@ -478,6 +548,13 @@ pub fn split_target(target: &str) -> (&str, Option<&str>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn reject_duck_lake_password(password: Option<&str>) -> IdeResult<()> {
|
||||
if password.is_some_and(|p| !p.is_empty()) {
|
||||
return Err(IdeError::invalid("DuckLake uses a catalog file or named secret without a JDBC or SSH password"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Says which leg failed when the database is unreachable from the SSH host.
|
||||
fn through_tunnel(e: IdeError, source: &DataSource, via: Option<&str>) -> IdeError {
|
||||
let Some(via) = via.filter(|_| e.kind == ErrorKind::Io) else { return e };
|
||||
@@ -548,6 +625,7 @@ impl DbManager {
|
||||
on_disk: Mutex::default(),
|
||||
sessions: Mutex::default(),
|
||||
cursors: conn::Cursors::default(),
|
||||
workspace_run: tokio::sync::Mutex::new(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -631,13 +709,16 @@ impl DbManager {
|
||||
/// Saves the data source list, preserving connections when only visibility rules change.
|
||||
/// Global ones (`global`) go to the app-wide list, the others to the project's.
|
||||
pub async fn save_sources(&self, mut sources: Vec<DataSource>) -> IdeResult<()> {
|
||||
for source in &sources {
|
||||
source.validate_duck_lake()?;
|
||||
}
|
||||
if sources.iter().any(|s| s.global && s.plugin_owner.is_some()) {
|
||||
return Err(IdeError::invalid("plugin-owned data sources must stay project-scoped"));
|
||||
}
|
||||
let old = {
|
||||
let _guard = plugin::EDIT.lock();
|
||||
let old = self.sources().unwrap_or_default();
|
||||
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc) {
|
||||
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc && s.duck_lake.is_none()) {
|
||||
// Retain the credential scope even when URL-only settings supplied the old authenticator.
|
||||
if let Some(settings) = old.iter().find(|s| s.id == source.id).and_then(Self::non_password_snowflake) {
|
||||
source.snowflake = Some(settings);
|
||||
@@ -686,7 +767,7 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
// Made global or project-level: its saved passwords move along.
|
||||
Some(n) if n.global != o.global => {
|
||||
Some(n) if n.global != o.global && n.duck_lake.is_none() && o.duck_lake.is_none() => {
|
||||
for k in &keys {
|
||||
if let Some(p) = self.store_of(&o).get(k) {
|
||||
self.store_of(n).set(k, &p)?;
|
||||
@@ -768,6 +849,9 @@ impl DbManager {
|
||||
/// the data source saves passwords (`None` forgets it).
|
||||
pub async fn set_password(&self, id: &str, password: Option<String>, save: bool) -> IdeResult<()> {
|
||||
let source = self.sources()?.into_iter().find(|s| s.id == id);
|
||||
if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) {
|
||||
return reject_duck_lake_password(password.as_deref());
|
||||
}
|
||||
let (store, key) = match source.as_ref() {
|
||||
Some(source) => (self.store_of(source), self.password_key(source)),
|
||||
None => (&self.saved_passwords, id.to_owned()),
|
||||
@@ -778,7 +862,11 @@ impl DbManager {
|
||||
/// [`DbManager::set_password`] for the SSH password / key passphrase.
|
||||
/// A data source using an SSH configuration sets that configuration's secret.
|
||||
pub async fn set_ssh_secret(&self, id: &str, secret: Option<String>, save: bool) -> IdeResult<()> {
|
||||
let config = self.sources()?.into_iter().find(|s| s.id == id).and_then(|s| s.ssh).map(|s| s.config);
|
||||
let source = self.sources()?.into_iter().find(|s| s.id == id);
|
||||
if source.as_ref().is_some_and(|s| s.duck_lake.is_some()) {
|
||||
return reject_duck_lake_password(secret.as_deref());
|
||||
}
|
||||
let config = source.and_then(|s| s.ssh).map(|s| s.config);
|
||||
if let Some(c) = config.filter(|c| !c.trim().is_empty()) {
|
||||
let save = self.ssh.config(&c).map(|c| c.save_secret).unwrap_or(save);
|
||||
return self.ssh.set_secret(&c, secret, save);
|
||||
@@ -823,6 +911,9 @@ impl DbManager {
|
||||
}
|
||||
|
||||
async fn password(&self, source: &DataSource) -> Option<String> {
|
||||
if source.duck_lake.is_some() {
|
||||
return None;
|
||||
}
|
||||
match self
|
||||
.secret(source, self.password_key(source), source.driver != DbDriver::Sqlite && source.save_password)
|
||||
.await
|
||||
@@ -931,6 +1022,10 @@ impl DbManager {
|
||||
purpose: route::RouteUse,
|
||||
) -> IdeResult<String> {
|
||||
let source = &source.resolved()?;
|
||||
if source.duck_lake.is_some() {
|
||||
reject_duck_lake_password(password.as_deref())?;
|
||||
reject_duck_lake_password(ssh_secret.as_deref())?;
|
||||
}
|
||||
let password = match password {
|
||||
Some(p) => Some(p),
|
||||
None => self.password(source).await,
|
||||
@@ -1287,13 +1382,7 @@ impl DbManager {
|
||||
})
|
||||
.collect();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails {
|
||||
comment: None,
|
||||
columns,
|
||||
indexes: vec![],
|
||||
foreign_keys: vec![],
|
||||
triggers: vec![],
|
||||
});
|
||||
return Ok(TableDetails { columns, ..Default::default() });
|
||||
}
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
@@ -1360,7 +1449,18 @@ impl DbManager {
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
|
||||
let mut details = TableDetails { comment, columns, indexes, foreign_keys, triggers, ..Default::default() };
|
||||
if let Some(q) = sql::table_properties(driver, schema, table) {
|
||||
match catalog_rows(pool, &q).await {
|
||||
Ok(rows) => {
|
||||
if let Some(row) = rows.into_iter().next() {
|
||||
read_table_properties(&mut details, row);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("table properties: {}", e.message),
|
||||
}
|
||||
}
|
||||
Ok(details)
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
|
||||
@@ -154,7 +154,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
|
||||
Err(_) => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
Ok(TableDetails { comment, columns, foreign_keys, ..Default::default() })
|
||||
}
|
||||
|
||||
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
|
||||
|
||||
@@ -11,6 +11,7 @@ use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) const FILE: &str = "data-sources.toml";
|
||||
pub(crate) const DUCKDB_URL: &str = "jdbc:duckdb:";
|
||||
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
@@ -306,6 +307,25 @@ pub struct DbExternalTunnel {
|
||||
pub arguments: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DbDuckLakeKind {
|
||||
File,
|
||||
Secret,
|
||||
}
|
||||
|
||||
/// How to open an existing DuckLake catalog read-only through DuckDB.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct DbDuckLake {
|
||||
pub kind: DbDuckLakeKind,
|
||||
/// A local catalog file or an existing DuckDB secret name.
|
||||
pub value: String,
|
||||
/// An existing local data directory overriding the catalog's data path.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub data_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct DataSource {
|
||||
@@ -346,6 +366,8 @@ pub struct DataSource {
|
||||
pub properties: Vec<DbProperty>,
|
||||
/// Snowflake settings (`None`: not a Snowflake data source, or all defaults).
|
||||
pub snowflake: Option<DbSnowflake>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub duck_lake: Option<DbDuckLake>,
|
||||
/// Stored app-wide and listed in every project. Implied by the file it is read from,
|
||||
/// so not written to it.
|
||||
pub global: bool,
|
||||
@@ -386,6 +408,7 @@ impl Default for DataSource {
|
||||
introspection: DbIntrospection::default(),
|
||||
properties: Vec::new(),
|
||||
snowflake: None,
|
||||
duck_lake: None,
|
||||
global: false,
|
||||
plugin_owner: None,
|
||||
plugin_source_id: None,
|
||||
@@ -513,7 +536,69 @@ pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
pub(crate) fn duck_lake_path(value: &str, relative: bool) -> IdeResult<&Path> {
|
||||
let path = Path::new(value);
|
||||
if value.trim().is_empty()
|
||||
|| value.contains(['\0', '\r', '\n'])
|
||||
|| value.starts_with("//")
|
||||
|| value.starts_with('\\')
|
||||
|| (!path.is_absolute() && (!relative || value.starts_with('/') || value.contains(':')))
|
||||
{
|
||||
return Err(IdeError::invalid("Choose a local DuckLake path on the database host"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
impl DataSource {
|
||||
pub(crate) fn validate_duck_lake(&self) -> IdeResult<()> {
|
||||
let Some(lake) = &self.duck_lake else { return Ok(()) };
|
||||
if self.driver != DbDriver::Jdbc
|
||||
|| self.vendor != "duckdb"
|
||||
|| self.url != DUCKDB_URL
|
||||
|| self.url_only
|
||||
|| !self.read_only
|
||||
|| self.plugin_owner.is_some()
|
||||
{
|
||||
return Err(IdeError::invalid("Existing DuckLake catalogs require a read-only DuckDB JDBC data source"));
|
||||
}
|
||||
if !self.user.is_empty()
|
||||
|| self.save_password
|
||||
|| self.ssh.is_some()
|
||||
|| self.external_tunnel.is_some()
|
||||
|| !self.properties.is_empty()
|
||||
{
|
||||
return Err(IdeError::invalid(
|
||||
"DuckLake uses its catalog file or named secret without JDBC credentials, properties or tunnels",
|
||||
));
|
||||
}
|
||||
if self.options.transaction != DbTxMode::Auto
|
||||
|| !self.options.default_schema.is_empty()
|
||||
|| !self.options.time_zone.is_empty()
|
||||
|| !self.options.startup_script.is_empty()
|
||||
{
|
||||
return Err(IdeError::invalid("DuckLake does not use JDBC session overrides"));
|
||||
}
|
||||
match lake.kind {
|
||||
DbDuckLakeKind::File => {
|
||||
duck_lake_path(&lake.value, true)?;
|
||||
}
|
||||
DbDuckLakeKind::Secret => {
|
||||
let mut chars = lake.value.bytes();
|
||||
if !chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == b'_')
|
||||
|| !chars.all(|c| c.is_ascii_alphanumeric() || c == b'_')
|
||||
{
|
||||
return Err(IdeError::invalid(
|
||||
"Enter an existing DuckLake secret name using letters, digits or underscores",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(path) = lake.data_path.as_deref().filter(|path| !path.is_empty()) {
|
||||
duck_lake_path(path, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn select_database(&mut self, database: Option<&str>) {
|
||||
if let Some(db) = database {
|
||||
// The configured schema belongs to the configured database.
|
||||
@@ -536,6 +621,7 @@ impl DataSource {
|
||||
/// database, user, SSL and driver properties come from the URL (properties
|
||||
/// of the Advanced tab still apply after the URL's).
|
||||
pub fn resolved(&self) -> IdeResult<DataSource> {
|
||||
self.validate_duck_lake()?;
|
||||
if self.driver == DbDriver::Jdbc {
|
||||
if !self.url.starts_with("jdbc:") {
|
||||
return Err(IdeError::invalid("Enter a JDBC URL starting with jdbc:"));
|
||||
|
||||
@@ -236,6 +236,29 @@ pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<Stri
|
||||
}
|
||||
}
|
||||
|
||||
/// One row: `owner, tablespace, access method, storage options (name=value per line),
|
||||
/// partition key, persistence (p/u/t)` of a table. `None` for the engines whose tables have none
|
||||
/// of these the IDE reads (all but PostgreSQL).
|
||||
pub fn table_properties(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
// `reltablespace` 0 is the database's default tablespace; the TOAST table's options are
|
||||
// set as `toast.name`.
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT pg_get_userbyid(c.relowner), COALESCE(ts.spcname, (SELECT dt.spcname FROM pg_database d \
|
||||
JOIN pg_tablespace dt ON dt.oid = d.dattablespace WHERE d.datname = current_database())), \
|
||||
am.amname, array_to_string(array_cat(c.reloptions, \
|
||||
(SELECT array_agg('toast.' || o) FROM unnest(tc.reloptions) o)), chr(10)), \
|
||||
pg_get_partkeydef(c.oid), c.relpersistence \
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
|
||||
LEFT JOIN pg_class tc ON tc.oid = c.reltoastrelid \
|
||||
LEFT JOIN pg_tablespace ts ON ts.oid = c.reltablespace LEFT JOIN pg_am am ON am.oid = c.relam \
|
||||
WHERE n.nspname = {s} AND c.relname = {t} AND c.relkind IN ('r', 'p')"
|
||||
)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `index name, unique (0/1), column, key` (one row per indexed column, in order); `key` is
|
||||
/// `p` for the primary key's index, `u` for a unique constraint's, NULL otherwise (ClickHouse: absent).
|
||||
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
|
||||
@@ -812,7 +835,12 @@ pub fn sqlite_trigger_event(sql: &str) -> (String, String) {
|
||||
pub fn postgres_legacy(sql: &str) -> Option<String> {
|
||||
let legacy = sql
|
||||
.replace("CASE WHEN p.prokind = 'p' THEN 'procedure' ELSE 'function' END", "'function'")
|
||||
.replace("p.prokind IN ('f', 'p')", "NOT p.proisagg AND NOT p.proiswindow");
|
||||
.replace("p.prokind IN ('f', 'p')", "NOT p.proisagg AND NOT p.proiswindow")
|
||||
// Table access methods (PostgreSQL 12) and partitioned tables (10).
|
||||
.replace(" LEFT JOIN pg_am am ON am.oid = c.relam", "")
|
||||
.replace("am.amname", "NULL")
|
||||
.replace("pg_get_partkeydef(c.oid)", "NULL")
|
||||
.replace("c.relkind IN ('r', 'p')", "c.relkind = 'r'");
|
||||
(legacy != sql).then_some(legacy)
|
||||
}
|
||||
|
||||
@@ -1534,5 +1562,7 @@ mod tests {
|
||||
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
|
||||
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
|
||||
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
|
||||
let properties = postgres_legacy(&table_properties(pg, "s", "t").unwrap()).unwrap();
|
||||
assert!(!properties.contains("relam") && !properties.contains("partkeydef"), "{properties}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
//! A read-only equality join of explicitly selected source tables on the project host.
|
||||
use crate::jdbc::JdbcPool;
|
||||
use crate::workspace_input::{
|
||||
self, WorkspaceInput, WorkspaceInputColumn, WorkspaceInputLimits, WorkspaceInputRequest, WorkspaceInputType,
|
||||
};
|
||||
use crate::{DbDriver, DbManager, QueryResult, sql};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::time::{Duration, Instant};
|
||||
use tempfile::{NamedTempFile, TempPath};
|
||||
|
||||
const MAX_TABLES: usize = 8;
|
||||
const MAX_RESULT_ROWS: usize = 100_000;
|
||||
const MAX_RESULT_COLUMNS: usize = 256;
|
||||
const WORKSPACE_INPUT_LIMITS: WorkspaceInputLimits =
|
||||
WorkspaceInputLimits { max_rows: 100_000, max_cell_bytes: 1_048_576, max_bytes: 16_777_216 };
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinRelation")]
|
||||
pub struct WorkspaceJoinRelation {
|
||||
pub source_id: String,
|
||||
pub database: String,
|
||||
pub schema: String,
|
||||
pub table: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinColumn")]
|
||||
pub struct WorkspaceJoinColumn {
|
||||
pub relation: u32,
|
||||
pub column: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinCondition")]
|
||||
pub struct WorkspaceJoinCondition {
|
||||
/// The right relation is the next table in the chain.
|
||||
pub left: WorkspaceJoinColumn,
|
||||
pub right_column: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinProjection")]
|
||||
pub struct WorkspaceJoinProjection {
|
||||
pub relation: u32,
|
||||
/// None expands this relation's columns in source order.
|
||||
pub column: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase", rename = "DbWorkspaceJoinPlan")]
|
||||
pub struct WorkspaceJoinPlan {
|
||||
pub tables: Vec<WorkspaceJoinRelation>,
|
||||
pub joins: Vec<WorkspaceJoinCondition>,
|
||||
/// None expands all relations in FROM/JOIN order.
|
||||
pub projection: Option<Vec<WorkspaceJoinProjection>>,
|
||||
}
|
||||
|
||||
fn validate_plan(
|
||||
table_count: usize,
|
||||
joins: &[WorkspaceJoinCondition],
|
||||
projection: Option<&[WorkspaceJoinProjection]>,
|
||||
) -> IdeResult<()> {
|
||||
if !(2..=MAX_TABLES).contains(&table_count) || joins.len() + 1 != table_count {
|
||||
return Err(IdeError::invalid("A workspace JOIN needs 2 to 8 tables and one equality per JOIN"));
|
||||
}
|
||||
let valid_column = |name: &str| !name.is_empty() && name.len() <= 255 && !name.contains('\0');
|
||||
for (index, link) in joins.iter().enumerate() {
|
||||
if link.left.relation as usize > index || !valid_column(&link.left.column) || !valid_column(&link.right_column)
|
||||
{
|
||||
return Err(IdeError::invalid("Each JOIN must compare a column of its new table with an earlier table"));
|
||||
}
|
||||
}
|
||||
if let Some(projection) = projection
|
||||
&& (projection.is_empty()
|
||||
|| projection.len() > MAX_RESULT_COLUMNS
|
||||
|| projection.iter().any(|item| {
|
||||
item.relation as usize >= table_count || item.column.as_deref().is_some_and(|name| !valid_column(name))
|
||||
}))
|
||||
{
|
||||
return Err(IdeError::invalid("Invalid workspace SELECT columns"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct StagedTable {
|
||||
path: TempPath,
|
||||
longest_row: usize,
|
||||
columns: Vec<WorkspaceInputColumn>,
|
||||
}
|
||||
|
||||
impl WorkspaceInputType {
|
||||
fn is_integer(self) -> bool {
|
||||
use WorkspaceInputType::*;
|
||||
matches!(self, Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64)
|
||||
}
|
||||
|
||||
fn duckdb_type(self) -> String {
|
||||
use WorkspaceInputType::*;
|
||||
match self {
|
||||
Boolean => "BOOLEAN",
|
||||
Int8 => "TINYINT",
|
||||
Int16 => "SMALLINT",
|
||||
Int32 => "INTEGER",
|
||||
Int64 => "BIGINT",
|
||||
UInt8 => "UTINYINT",
|
||||
UInt16 => "USMALLINT",
|
||||
UInt32 => "UINTEGER",
|
||||
UInt64 => "UBIGINT",
|
||||
Float32 => "FLOAT",
|
||||
Float64 => "DOUBLE",
|
||||
Decimal { precision, scale } => return format!("DECIMAL({precision},{scale})"),
|
||||
Text => "VARCHAR",
|
||||
Date => "DATE",
|
||||
Time => "TIME",
|
||||
Timestamp => "TIMESTAMP",
|
||||
TimestampTz => "TIMESTAMPTZ",
|
||||
Uuid => "UUID",
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
fn stage(input: WorkspaceInput, cancel: &CancellationToken) -> IdeResult<StagedTable> {
|
||||
let mut file = NamedTempFile::new()?;
|
||||
let mut longest_row = 1;
|
||||
{
|
||||
let mut out = BufWriter::new(file.as_file_mut());
|
||||
for row in input.rows {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if row.len() != input.columns.len() {
|
||||
return Err(IdeError::invalid("Incomplete workspace input row"));
|
||||
}
|
||||
let mut bytes = row.len(); // separators and newline
|
||||
for (column, cell) in row.into_iter().enumerate() {
|
||||
if column > 0 {
|
||||
out.write_all(b",")?;
|
||||
}
|
||||
bytes += 2; // quotes or the NULL marker
|
||||
if let Some(value) = cell {
|
||||
bytes += value.len();
|
||||
out.write_all(b"\"")?;
|
||||
let mut pieces = value.split('"');
|
||||
out.write_all(pieces.next().unwrap_or_default().as_bytes())?;
|
||||
for piece in pieces {
|
||||
bytes += 1;
|
||||
out.write_all(b"\"\"")?;
|
||||
out.write_all(piece.as_bytes())?;
|
||||
}
|
||||
out.write_all(b"\"")?;
|
||||
} else {
|
||||
out.write_all(br"\N")?;
|
||||
}
|
||||
}
|
||||
longest_row = longest_row.max(bytes);
|
||||
out.write_all(b"\n")?;
|
||||
}
|
||||
out.flush()?;
|
||||
}
|
||||
Ok(StagedTable { path: file.into_temp_path(), longest_row, columns: input.columns })
|
||||
}
|
||||
|
||||
impl StagedTable {
|
||||
fn quoted_path(&self) -> IdeResult<String> {
|
||||
self.path
|
||||
.to_str()
|
||||
.map(|p| sql::quote_literal(DbDriver::Jdbc, p))
|
||||
.ok_or_else(|| IdeError::invalid("The workspace temporary directory needs a UTF-8 path"))
|
||||
}
|
||||
|
||||
fn scan(&self, path: &str) -> String {
|
||||
// Synthetic column names also preserve case-distinct names from the source.
|
||||
let columns = self
|
||||
.columns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| format!("'c{i}':'{}'", c.data_type.duckdb_type()))
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let line = self.longest_row;
|
||||
// The single-threaded reader only needs one complete CSV record per buffer.
|
||||
let buffer = line.max(64 * 1024);
|
||||
format!(
|
||||
r#"read_csv({path},columns={{{columns}}},auto_detect=false,header=false,delim=',',quote='"',escape='"',nullstr='\N',allow_quoted_nulls=false,parallel=false,max_line_size={line},buffer_size={buffer})"#
|
||||
)
|
||||
}
|
||||
|
||||
fn column(&self, name: &str) -> IdeResult<usize> {
|
||||
self.columns
|
||||
.iter()
|
||||
.position(|c| c.name == name)
|
||||
.ok_or_else(|| IdeError::invalid(format!("Unknown workspace column: {name}")))
|
||||
}
|
||||
}
|
||||
|
||||
fn staging_columns<'a>(
|
||||
table_count: usize,
|
||||
joins: &'a [WorkspaceJoinCondition],
|
||||
projection: Option<&'a [WorkspaceJoinProjection]>,
|
||||
) -> Vec<Option<Vec<&'a str>>> {
|
||||
let Some(projection) = projection else {
|
||||
return vec![None; table_count];
|
||||
};
|
||||
let mut columns: Vec<Option<Vec<&str>>> = vec![Some(Vec::new()); table_count];
|
||||
for item in projection {
|
||||
let selected = &mut columns[item.relation as usize];
|
||||
match (&item.column, selected) {
|
||||
(Some(name), Some(selected)) => selected.push(name),
|
||||
(None, selected) => *selected = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for (index, link) in joins.iter().enumerate() {
|
||||
if let Some(selected) = &mut columns[link.left.relation as usize] {
|
||||
selected.push(&link.left.column);
|
||||
}
|
||||
if let Some(selected) = &mut columns[index + 1] {
|
||||
selected.push(&link.right_column);
|
||||
}
|
||||
}
|
||||
for selected in columns.iter_mut().flatten() {
|
||||
selected.sort_unstable();
|
||||
selected.dedup();
|
||||
}
|
||||
columns
|
||||
}
|
||||
|
||||
fn result_projection(
|
||||
tables: &[StagedTable],
|
||||
selection: Option<&[WorkspaceJoinProjection]>,
|
||||
) -> IdeResult<Vec<(usize, usize)>> {
|
||||
let mut fields = Vec::new();
|
||||
match selection {
|
||||
Some(selection) => {
|
||||
for item in selection {
|
||||
let relation = item.relation as usize;
|
||||
let table = &tables[relation];
|
||||
match &item.column {
|
||||
Some(name) => fields.push((relation, table.column(name)?)),
|
||||
None => fields.extend((0..table.columns.len()).map(|column| (relation, column))),
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
for (relation, table) in tables.iter().enumerate() {
|
||||
fields.extend((0..table.columns.len()).map(|column| (relation, column)));
|
||||
}
|
||||
}
|
||||
}
|
||||
if fields.len() > MAX_RESULT_COLUMNS {
|
||||
return Err(IdeError::invalid("Workspace result exceeds 256 columns"));
|
||||
}
|
||||
Ok(fields)
|
||||
}
|
||||
|
||||
async fn join(
|
||||
engine: &JdbcPool,
|
||||
tables: &[StagedTable],
|
||||
joins: &[WorkspaceJoinCondition],
|
||||
selection: Option<&[WorkspaceJoinProjection]>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
use std::fmt::Write as _;
|
||||
let fields = result_projection(tables, selection)?;
|
||||
let names = fields.iter().map(|(relation, column)| format!("r{relation}.c{column}")).collect::<Vec<_>>().join(", ");
|
||||
let paths = tables.iter().map(StagedTable::quoted_path).collect::<IdeResult<Vec<_>>>()?;
|
||||
let mut query = format!("SELECT {names} FROM {} r0", tables[0].scan(&paths[0]));
|
||||
for (index, condition) in joins.iter().enumerate() {
|
||||
let left_relation = condition.left.relation as usize;
|
||||
let right_relation = index + 1;
|
||||
let left = &tables[left_relation];
|
||||
let right = &tables[right_relation];
|
||||
let li = left.column(&condition.left.column)?;
|
||||
let ri = right.column(&condition.right_column)?;
|
||||
let (a, b) = (left.columns[li].data_type, right.columns[ri].data_type);
|
||||
// DuckDB compares mixed integer widths and signs exactly, up to BIGINT against UBIGINT.
|
||||
if a != b && !(a.is_integer() && b.is_integer()) {
|
||||
return Err(IdeError::invalid("Choose integer join columns or columns of the same type and precision"));
|
||||
}
|
||||
write!(
|
||||
query,
|
||||
" INNER JOIN {} r{right_relation} ON r{left_relation}.c{li}=r{right_relation}.c{ri}",
|
||||
right.scan(&paths[right_relation]),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
write!(query, " LIMIT {}", MAX_RESULT_ROWS + 1).unwrap();
|
||||
for setting in [
|
||||
"SET threads=1",
|
||||
"SET memory_limit='96MiB'",
|
||||
"SET temp_directory=''",
|
||||
"SET max_temp_directory_size='0B'",
|
||||
&format!("SET allowed_paths=[{}]", paths.join(",")),
|
||||
"SET enable_external_access=false",
|
||||
"SET lock_configuration=true",
|
||||
] {
|
||||
engine.query(setting, 0, 0, cancel).await?;
|
||||
}
|
||||
let mut result = engine.query(&query, 0, MAX_RESULT_ROWS, cancel).await?;
|
||||
if result.has_more {
|
||||
return Err(IdeError::invalid("Workspace result exceeds 100,000 rows"));
|
||||
}
|
||||
if result.columns.len() != fields.len() {
|
||||
return Err(IdeError::invalid("Unexpected workspace result columns"));
|
||||
}
|
||||
for (display, (relation, column)) in result.columns.iter_mut().zip(fields) {
|
||||
display.name.clone_from(&tables[relation].columns[column].name);
|
||||
}
|
||||
result.statement.clear();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn two_table_join(keys: [&str; 2]) -> WorkspaceJoinCondition {
|
||||
WorkspaceJoinCondition {
|
||||
left: WorkspaceJoinColumn { relation: 0, column: keys[0].into() },
|
||||
right_column: keys[1].into(),
|
||||
}
|
||||
}
|
||||
|
||||
impl DbManager {
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn workspace_join_pair_for_test(
|
||||
&self,
|
||||
driver: &str,
|
||||
tables: [&WorkspaceInputRequest; 2],
|
||||
keys: [&str; 2],
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let joins = [two_table_join(keys)];
|
||||
validate_plan(tables.len(), &joins, None)?;
|
||||
self.execute_workspace_join(driver, &tables, &joins, None, cancel).await
|
||||
}
|
||||
|
||||
/// The caller retains the bounded result for paging. Reading another page never reruns the sources.
|
||||
pub async fn workspace_join(
|
||||
&self,
|
||||
driver: &str,
|
||||
plan: WorkspaceJoinPlan,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
validate_plan(plan.tables.len(), &plan.joins, plan.projection.as_deref())?;
|
||||
let tables: Vec<_> = plan
|
||||
.tables
|
||||
.into_iter()
|
||||
.map(|table| WorkspaceInputRequest {
|
||||
source_id: table.source_id,
|
||||
database: table.database,
|
||||
schema: table.schema,
|
||||
table: table.table,
|
||||
limits: WORKSPACE_INPUT_LIMITS,
|
||||
})
|
||||
.collect();
|
||||
let tables: Vec<_> = tables.iter().collect();
|
||||
self.execute_workspace_join(driver, &tables, &plan.joins, plan.projection.as_deref(), cancel).await
|
||||
}
|
||||
|
||||
async fn execute_workspace_join(
|
||||
&self,
|
||||
driver: &str,
|
||||
tables: &[&WorkspaceInputRequest],
|
||||
joins: &[WorkspaceJoinCondition],
|
||||
projection: Option<&[WorkspaceJoinProjection]>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let _run =
|
||||
self.workspace_run.try_lock().map_err(|_| IdeError::invalid("A workspace query is already running"))?;
|
||||
let start = Instant::now();
|
||||
let child = cancel.child_token();
|
||||
let run = async {
|
||||
let cancel = &child;
|
||||
let mut prepared = Vec::with_capacity(tables.len());
|
||||
for table in tables {
|
||||
let input = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
input = workspace_input::prepare_table(self, table) => input?,
|
||||
};
|
||||
prepared.push(input);
|
||||
}
|
||||
let selection = staging_columns(tables.len(), joins, projection);
|
||||
let mut staged = Vec::with_capacity(tables.len());
|
||||
let engine = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
engine = self.workspace_engine(driver) => engine?,
|
||||
};
|
||||
let result = async {
|
||||
let mut remaining_rows = 200_000;
|
||||
let mut remaining_bytes = 32 * 1024 * 1024;
|
||||
for (mut table, columns) in prepared.into_iter().zip(&selection) {
|
||||
let limits = &mut table.request.limits;
|
||||
limits.max_rows = limits.max_rows.min(remaining_rows);
|
||||
limits.max_bytes = limits.max_bytes.min(remaining_bytes);
|
||||
let input = workspace_input::read_prepared_table(self, table, columns.as_deref(), cancel).await?;
|
||||
remaining_rows -= input.rows.len();
|
||||
remaining_bytes -= input.bytes;
|
||||
let cancellation = cancel.clone();
|
||||
let table = tokio::task::spawn_blocking(move || stage(input, &cancellation))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
staged.push(table);
|
||||
}
|
||||
join(&engine, &staged, joins, projection, cancel).await
|
||||
}
|
||||
.await;
|
||||
// Windows cannot remove a staged file while the JDBC process still has it open.
|
||||
engine.close().await;
|
||||
drop(staged);
|
||||
let mut result = result?;
|
||||
result.elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
Ok(result)
|
||||
};
|
||||
tokio::pin!(run);
|
||||
let stopped = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => IdeError::cancelled(),
|
||||
result = &mut run => return result,
|
||||
() = tokio::time::sleep(Duration::from_secs(90)) => IdeError::new(ide_core::error::ErrorKind::TimedOut, "Workspace query timed out"),
|
||||
};
|
||||
child.cancel();
|
||||
// Let the source or JDBC bridge deliver cancellation before dropping its connection.
|
||||
let _ = tokio::time::timeout(Duration::from_secs(15), run).await;
|
||||
Err(stopped)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::DbJdbcDriver;
|
||||
|
||||
fn input(values: &[(&str, Option<&str>)]) -> WorkspaceInput {
|
||||
WorkspaceInput {
|
||||
columns: vec![
|
||||
WorkspaceInputColumn {
|
||||
name: "key".into(),
|
||||
data_type: WorkspaceInputType::Decimal { precision: 32, scale: 6 },
|
||||
},
|
||||
WorkspaceInputColumn { name: "text".into(), data_type: WorkspaceInputType::Text },
|
||||
],
|
||||
rows: values.iter().map(|(k, v)| vec![Some(k.to_string()), v.map(str::to_owned)]).collect(),
|
||||
bytes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_join_chain_links_must_target_an_earlier_table() -> IdeResult<()> {
|
||||
let first = two_table_join(["key", "key"]);
|
||||
let second = two_table_join(["key", "id"]);
|
||||
let links = [first, second];
|
||||
validate_plan(3, &links, None)?;
|
||||
let over_limit: Vec<_> = (0..8).map(|_| two_table_join(["key", "key"])).collect();
|
||||
assert!(validate_plan(9, &over_limit, None).is_err());
|
||||
validate_plan(8, &over_limit[..7], None)?;
|
||||
assert!(validate_plan(4, &links, None).is_err());
|
||||
assert!(validate_plan(3, &links, Some(&[])).is_err());
|
||||
let invalid = WorkspaceJoinProjection { relation: 3, column: None };
|
||||
assert!(validate_plan(3, &links, Some(&[invalid])).is_err());
|
||||
let mut links = links;
|
||||
links[0].left.relation = 1;
|
||||
assert!(validate_plan(3, &links, None).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_preserves_null_and_csv_text_and_removes_the_file_on_drop() -> IdeResult<()> {
|
||||
let cancel = CancellationToken::new();
|
||||
let table = stage(input(&[("1", None), ("2", Some("")), ("3", Some("a,\"b\"\nc"))]), &cancel)?;
|
||||
let path = table.path.to_path_buf();
|
||||
assert_eq!(std::fs::read_to_string(&path)?, "\"1\",\\N\n\"2\",\"\"\n\"3\",\"a,\"\"b\"\"\nc\"\n");
|
||||
drop(table);
|
||||
assert!(!path.exists());
|
||||
cancel.cancel();
|
||||
assert!(stage(input(&[("1", None)]), &cancel).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
|
||||
async fn workspace_engine_joins_exact_keys_nulls_and_empty_inputs() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let root = tmp.path();
|
||||
let db = DbManager::new(
|
||||
root.join("project"),
|
||||
root.join("passwords"),
|
||||
root.join("history"),
|
||||
std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh"))),
|
||||
)
|
||||
.with_global_sources(root.join("global"));
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "duck".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: Some("duckdb".into()),
|
||||
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("driver fixture")],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: "jdbc:duckdb:".into(),
|
||||
})?;
|
||||
let cancel = CancellationToken::new();
|
||||
let mut signed = input(&[("-1", None), ("9007199254740993", None), ("9223372036854775807", None)]);
|
||||
signed.columns[0].data_type = WorkspaceInputType::Int64;
|
||||
let mut unsigned = input(&[
|
||||
("18446744073709551615", None),
|
||||
("9007199254740992", None),
|
||||
("9007199254740993", None),
|
||||
("9223372036854775807", None),
|
||||
]);
|
||||
unsigned.columns[0].data_type = WorkspaceInputType::UInt64;
|
||||
let tables = [stage(signed, &cancel)?, stage(unsigned, &cancel)?];
|
||||
let engine = db.workspace_engine("duck").await?;
|
||||
let output = join(&engine, &tables, &[two_table_join(["key", "key"])], None, &cancel).await?;
|
||||
let mut matches: Vec<_> = output.rows.iter().map(|row| (row[0].as_deref(), row[2].as_deref())).collect();
|
||||
matches.sort_unstable();
|
||||
assert_eq!(
|
||||
matches,
|
||||
[
|
||||
(Some("9007199254740993"), Some("9007199254740993")),
|
||||
(Some("9223372036854775807"), Some("9223372036854775807")),
|
||||
]
|
||||
);
|
||||
engine.close().await;
|
||||
let wide = "a,\n\"b\"".repeat(32 * 1024);
|
||||
let left = stage(input(&[("0", None), ("1", Some(&wide)), ("2", Some("short"))]), &cancel)?;
|
||||
let right = stage(input(&[("1", Some(&wide))]), &cancel)?;
|
||||
let engine = db.workspace_engine("duck").await?;
|
||||
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
|
||||
assert_eq!(output.rows.len(), 1);
|
||||
assert_eq!(output.rows[0][1].as_deref(), Some(wide.as_str()));
|
||||
assert_eq!(output.rows[0][3].as_deref(), Some(wide.as_str()));
|
||||
engine.close().await;
|
||||
for empty in [false, true] {
|
||||
let left =
|
||||
stage(input(&[("9007199254740993.000001", None), ("9007199254740993.000002", Some(""))]), &cancel)?;
|
||||
let mut right =
|
||||
input(&[("9007199254740993.000001", Some("a,\"b\"\nc")), ("9007199254740993.000002", Some(r"\N"))]);
|
||||
if empty {
|
||||
right.rows.clear();
|
||||
}
|
||||
let engine = db.workspace_engine("duck").await?;
|
||||
let right = stage(right, &cancel)?;
|
||||
let output = join(&engine, &[left, right], &[two_table_join(["key", "key"])], None, &cancel).await?;
|
||||
assert_eq!(
|
||||
output.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
|
||||
["key", "text", "key", "text"]
|
||||
);
|
||||
let mut rows = output.rows;
|
||||
rows.sort();
|
||||
if empty {
|
||||
assert!(rows.is_empty());
|
||||
} else {
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(
|
||||
rows[0],
|
||||
[
|
||||
Some("9007199254740993.000001".into()),
|
||||
None,
|
||||
Some("9007199254740993.000001".into()),
|
||||
Some("a,\"b\"\nc".into())
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
rows[1],
|
||||
[
|
||||
Some("9007199254740993.000002".into()),
|
||||
Some("".into()),
|
||||
Some("9007199254740993.000002".into()),
|
||||
Some(r"\N".into())
|
||||
]
|
||||
);
|
||||
}
|
||||
engine.close().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+134
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env bash
|
||||
# Requires Docker, curl and Cargo. To exercise the JOIN and its cancellation as well
|
||||
# as source reads, install Java 17+ and set DUCKDB_JDBC_JAR to an absolute JAR path.
|
||||
# Usage: bash crates/ide-db/tests/fixtures/workspace.sh [command args...]
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/../../../.."
|
||||
fixtures=$(mktemp -d "${TMPDIR:-/tmp}/openidea-workspace.XXXXXXXX")
|
||||
pg=
|
||||
ch=
|
||||
cleanup() {
|
||||
if [[ -n "$ch" ]]; then docker stop -t 2 "$ch" >/dev/null || true; fi
|
||||
if [[ -n "$pg" ]]; then docker stop -t 2 "$pg" >/dev/null || true; fi
|
||||
rm -f "$fixtures/users.xml"
|
||||
rmdir "$fixtures"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
cat > "$fixtures/users.xml" <<'XML'
|
||||
<clickhouse>
|
||||
<profiles>
|
||||
<workspace_strict>
|
||||
<readonly>1</readonly>
|
||||
<max_threads>1</max_threads>
|
||||
<max_memory_usage>134217728</max_memory_usage>
|
||||
<max_rows_to_read>100000</max_rows_to_read>
|
||||
<max_execution_time>20</max_execution_time>
|
||||
</workspace_strict>
|
||||
<workspace_break>
|
||||
<readonly>1</readonly>
|
||||
<result_overflow_mode>break</result_overflow_mode>
|
||||
</workspace_break>
|
||||
<workspace_cap>
|
||||
<readonly>1</readonly>
|
||||
<max_result_rows>2</max_result_rows>
|
||||
</workspace_cap>
|
||||
</profiles>
|
||||
<users>
|
||||
<fixture_writer>
|
||||
<no_password/>
|
||||
<networks><ip>::/0</ip></networks>
|
||||
<profile>default</profile>
|
||||
<quota>default</quota>
|
||||
</fixture_writer>
|
||||
<fixture_strict>
|
||||
<no_password/>
|
||||
<networks><ip>::/0</ip></networks>
|
||||
<profile>workspace_strict</profile>
|
||||
<quota>default</quota>
|
||||
</fixture_strict>
|
||||
<fixture_break>
|
||||
<no_password/>
|
||||
<networks><ip>::/0</ip></networks>
|
||||
<profile>workspace_break</profile>
|
||||
<quota>default</quota>
|
||||
</fixture_break>
|
||||
<fixture_cap>
|
||||
<no_password/>
|
||||
<networks><ip>::/0</ip></networks>
|
||||
<profile>workspace_cap</profile>
|
||||
<quota>default</quota>
|
||||
</fixture_cap>
|
||||
</users>
|
||||
</clickhouse>
|
||||
XML
|
||||
chmod 644 "$fixtures/users.xml"
|
||||
|
||||
pg=$(docker run --rm -d -p 127.0.0.1::5432 --cpus 1 --memory 320m \
|
||||
--tmpfs /var/lib/postgresql/data:rw,size=128m \
|
||||
-e POSTGRES_HOST_AUTH_METHOD=trust postgres:17-alpine)
|
||||
ch=$(docker run --rm -d -p 127.0.0.1::8123 --cpus 1 --memory 1536m \
|
||||
--tmpfs /var/lib/clickhouse --tmpfs /var/log/clickhouse-server \
|
||||
--mount "type=bind,source=$fixtures/users.xml,target=/etc/clickhouse-server/users.d/workspace-fixture.xml,readonly" \
|
||||
clickhouse/clickhouse-server:25.8.12.129)
|
||||
WORKSPACE_PG_PORT=$(docker port "$pg" 5432/tcp | sed 's/^127\.0\.0\.1://')
|
||||
WORKSPACE_CH_PORT=$(docker port "$ch" 8123/tcp | sed 's/^127\.0\.0\.1://')
|
||||
export WORKSPACE_PG_PORT WORKSPACE_CH_PORT
|
||||
ch_http="http://127.0.0.1:$WORKSPACE_CH_PORT"
|
||||
|
||||
ready() {
|
||||
for ((attempt = 0; attempt < 45; ++attempt)); do
|
||||
if "$@" >/dev/null 2>&1; then return 0; fi
|
||||
sleep 1
|
||||
done
|
||||
printf 'Workspace fixture did not become ready: %s\n' "$1" >&2
|
||||
return 1
|
||||
}
|
||||
ready docker exec "$pg" pg_isready -h 127.0.0.1 -U postgres
|
||||
ready curl -fsS --max-time 1 "$ch_http/ping"
|
||||
|
||||
docker exec -i "$pg" psql -h 127.0.0.1 -U postgres -Xq -v ON_ERROR_STOP=1 <<'SQL'
|
||||
CREATE TABLE "exact data" ("exact key" numeric(32,6), id bigint, ts timestamp(6) with time zone, label text);
|
||||
INSERT INTO "exact data" VALUES
|
||||
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456+03', E'a,b"c\nd'),
|
||||
(100000000000000000002.000001, 9007199254740994, NULL, ''),
|
||||
(NULL, 9007199254740995, NULL, NULL);
|
||||
CREATE TABLE "empty data" (LIKE "exact data");
|
||||
CREATE TABLE "unsupported data" (payload jsonb);
|
||||
CREATE VIEW "fixture view" AS SELECT * FROM "exact data";
|
||||
SQL
|
||||
|
||||
ch_sql() {
|
||||
curl -fsS --max-time 5 --user fixture_writer: --data-binary "$1" "$ch_http/"
|
||||
}
|
||||
ch_sql "CREATE TABLE default.\"exact data\" (
|
||||
\"exact key\" Nullable(Decimal(32,6)), id Int64, ts Nullable(DateTime64(6, 'Europe/Moscow')), label Nullable(String)
|
||||
) ENGINE=Memory"
|
||||
ch_sql "INSERT INTO default.\"exact data\" VALUES
|
||||
(100000000000000000001.000001, 9007199254740993, '2025-01-03 07:05:06.123456', 'a,b\"c\\nd'),
|
||||
(100000000000000000002.000001, 9007199254740994, NULL, ''),
|
||||
(NULL, 9007199254740995, NULL, NULL)"
|
||||
ch_sql 'CREATE TABLE default."empty data" AS default."exact data" ENGINE=Memory'
|
||||
ch_sql 'CREATE TABLE default."unsupported data" (payload Array(String)) ENGINE=Memory'
|
||||
ch_sql 'CREATE VIEW default."fixture view" AS SELECT * FROM default."exact data"'
|
||||
ch_sql 'CREATE TABLE default."unsigned data" (id UInt64) ENGINE=Memory'
|
||||
ch_sql 'INSERT INTO default."unsigned data" VALUES (9007199254740992), (9007199254740993), (18446744073709551615)'
|
||||
|
||||
ch_sql 'CREATE TABLE default."overflow data" (id Int64) ENGINE=Memory'
|
||||
ch_sql 'INSERT INTO default."overflow data" VALUES (1), (2), (3), (4), (5)'
|
||||
|
||||
export WORKSPACE_CH_USER=fixture_writer
|
||||
if (( $# > 0 )); then
|
||||
"$@"
|
||||
else
|
||||
test_name=workspace_input::tests::native_workspace_sources_are_exact_and_fail_on_limits
|
||||
cargo test --locked -p ide-db --lib "$test_name" -- --ignored
|
||||
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib "$test_name" -- --ignored
|
||||
cargo test --locked -p ide-db --lib clickhouse_workspace_refuses_truncated_reads -- --ignored
|
||||
if [[ -n "${DUCKDB_JDBC_JAR:-}" ]]; then
|
||||
WORKSPACE_CH_USER=fixture_strict cargo test --locked -p ide-db --lib workspace_join_chains_four_live_engines -- --ignored
|
||||
fi
|
||||
fi
|
||||
@@ -1,5 +1,7 @@
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{ConsoleId, DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
|
||||
use ide_db::{
|
||||
ConsoleId, DataSource, DbDriver, DbDuckLake, DbDuckLakeKind, DbJdbcDriver, DbManager, DbProperty, SortKey,
|
||||
};
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
fn manager(dir: &Path) -> DbManager {
|
||||
@@ -8,6 +10,158 @@ fn manager(dir: &Path) -> DbManager {
|
||||
.with_global_sources(dir.join("global"))
|
||||
}
|
||||
|
||||
fn duck_lake_source(catalog: &str) -> DataSource {
|
||||
DataSource {
|
||||
id: "lake".into(),
|
||||
name: "DuckLake".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "duckdb".into(),
|
||||
jdbc_driver: "duck".into(),
|
||||
url: "jdbc:duckdb:".into(),
|
||||
read_only: true,
|
||||
duck_lake: Some(DbDuckLake { kind: DbDuckLakeKind::File, value: catalog.into(), data_path: None }),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn duck_lake_driver(jar: String) -> DbJdbcDriver {
|
||||
DbJdbcDriver {
|
||||
id: "duck".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: Some("duckdb".into()),
|
||||
jars: vec![jar],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: "jdbc:duckdb:".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duck_lake_settings_are_validated_and_covered_by_project_approval() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let jar = tmp.path().join("fixture.jar");
|
||||
std::fs::write(&jar, [])?;
|
||||
let db = manager(tmp.path());
|
||||
let profile = duck_lake_driver(jar.display().to_string());
|
||||
let source = duck_lake_source("lake/catalog.ducklake");
|
||||
let mut other_profile = profile.clone();
|
||||
other_profile.class_name = "test.NotDuckDB".into();
|
||||
db.save_jdbc_driver(other_profile)?;
|
||||
assert!(db.approve_ducklake_source(&source).is_err());
|
||||
let directory = tmp.path().join("create");
|
||||
assert!(db.create_ducklake("duck", directory.to_str().unwrap()).await.is_err());
|
||||
assert!(!directory.exists());
|
||||
db.save_jdbc_driver(profile)?;
|
||||
assert!(db.approve_ducklake_source(&DataSource { duck_lake: None, ..source.clone() }).is_err());
|
||||
|
||||
let mut invalid_secret = source.clone();
|
||||
invalid_secret.duck_lake =
|
||||
Some(DbDuckLake { kind: DbDuckLakeKind::Secret, value: "key=value".into(), data_path: None });
|
||||
let mut data_path = source.clone();
|
||||
data_path.duck_lake.as_mut().unwrap().data_path = Some("s3://example/ducklake".into());
|
||||
let mut scripted = source.clone();
|
||||
scripted.options.startup_script = "CREATE TABLE t (n int)".into();
|
||||
for invalid in [
|
||||
invalid_secret,
|
||||
data_path,
|
||||
scripted,
|
||||
DataSource { driver: DbDriver::Sqlite, ..source.clone() },
|
||||
DataSource { url: "jdbc:duckdb:unrelated.duckdb".into(), ..source.clone() },
|
||||
DataSource { read_only: false, ..source.clone() },
|
||||
DataSource { save_password: true, ..source.clone() },
|
||||
DataSource {
|
||||
properties: vec![DbProperty { name: "access_mode".into(), value: "READ_WRITE".into() }],
|
||||
..source.clone()
|
||||
},
|
||||
] {
|
||||
assert!(invalid.resolved().is_err());
|
||||
assert!(db.save_sources(vec![invalid.clone()]).await.is_err());
|
||||
assert!(db.approve_ducklake_source(&invalid).is_err());
|
||||
}
|
||||
assert!(db.sources()?.is_empty());
|
||||
|
||||
db.approve_ducklake_source(&DataSource { global: true, ..source.clone() })?;
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
assert_eq!(db.source("lake")?, source);
|
||||
let err = db.pool("lake").await.err().expect("global validation must not approve a project connection");
|
||||
assert!(err.message.contains("Review this project"));
|
||||
assert!(db.set_password("lake", Some("unused".into()), true).await.is_err());
|
||||
assert!(db.test(&source, Some("unused".into()), None).await.is_err());
|
||||
db.approve_ducklake_source(&source)?;
|
||||
let mut changed = source;
|
||||
changed.duck_lake.as_mut().unwrap().value = "another/catalog.ducklake".into();
|
||||
db.save_sources(vec![changed]).await?;
|
||||
let err = db.pool("lake").await.err().expect("new catalog path must be approved");
|
||||
assert!(err.message.contains("Review this project"));
|
||||
assert!(serde_json::from_value::<DbDuckLake>(serde_json::json!({"kind":"create", "value":"lake"})).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR, DuckLake extension access, and Java 17+"]
|
||||
async fn duck_lake_creates_only_explicitly_and_reopens_read_only() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR");
|
||||
db.save_jdbc_driver(duck_lake_driver(jar))?;
|
||||
let source = duck_lake_source("lake's files/catalog.ducklake");
|
||||
let directory = tmp.path().join("project").join("lake's files");
|
||||
let path = directory.to_str().unwrap();
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
let err = db.test(&source, None, None).await.expect_err("Test must not create a missing catalog");
|
||||
assert!(err.message.contains("does not exist"), "{}", err.message);
|
||||
assert!(!directory.exists());
|
||||
db.approve_ducklake_source(&source)?;
|
||||
assert!(db.pool("lake").await.is_err());
|
||||
assert!(!directory.exists());
|
||||
|
||||
db.create_ducklake("duck", path).await?;
|
||||
assert!(directory.join("catalog.ducklake").is_file());
|
||||
let err = db.create_ducklake("duck", path).await.expect_err("Create must reject an existing directory");
|
||||
assert!(err.message.contains("already exists"), "{}", err.message);
|
||||
assert!(db.test(&source, None, None).await?.contains("DuckDB"));
|
||||
|
||||
let db = manager(tmp.path());
|
||||
assert_eq!(db.source("lake")?, source);
|
||||
let cancel = CancellationToken::new();
|
||||
let console = ConsoleId::new("window", "/lake.sql");
|
||||
for scope in [None, Some(console)] {
|
||||
let result = db
|
||||
.execute_in_console(
|
||||
"lake",
|
||||
"SELECT readonly FROM duckdb_databases() WHERE database_name = current_database() AND type = 'ducklake'",
|
||||
0,
|
||||
1,
|
||||
&cancel,
|
||||
None,
|
||||
scope,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(result.rows, [vec![Some("true".into())]]);
|
||||
assert!(
|
||||
db.execute_in_console("lake", "CREATE TABLE main.rejected(id INTEGER)", 0, 1, &cancel, None, scope)
|
||||
.await
|
||||
.is_err(),
|
||||
"the attached catalog must be read-only"
|
||||
);
|
||||
}
|
||||
assert!(db.schemas("lake").await?.contains(&"main".into()));
|
||||
assert!(db.tables("lake", "main").await?.is_empty());
|
||||
let databases = db.databases("lake").await?;
|
||||
assert_eq!(databases.current, "openidea_lake");
|
||||
assert!(databases.names.contains(&databases.current));
|
||||
let catalog = db.database_catalog("lake", &databases.current).await?;
|
||||
assert!(catalog.iter().any(|schema| schema.name == "main" && schema.tables.is_empty()));
|
||||
db.release_target_console(console, Some("lake")).await?;
|
||||
db.disconnect("lake").await;
|
||||
|
||||
let global = DataSource { id: "global-lake".into(), global: true, ..source };
|
||||
db.approve_ducklake_source(&global)?;
|
||||
db.save_sources(vec![global]).await?;
|
||||
assert!(db.schemas("global-lake").await?.contains(&"main".into()));
|
||||
db.disconnect("global-lake").await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
@@ -278,34 +432,39 @@ async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
|
||||
vendor: "duckdb".into(),
|
||||
global: true,
|
||||
jdbc_driver: "duck".into(),
|
||||
url: "jdbc:duckdb:".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
|
||||
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
|
||||
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
|
||||
let nodes = db.explain("test", join, &cancel, None).await?;
|
||||
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
|
||||
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
|
||||
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
|
||||
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
|
||||
assert!(batch.message.contains("one statement"));
|
||||
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
|
||||
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
|
||||
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
|
||||
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
|
||||
assert_eq!(
|
||||
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
|
||||
[vec![Some("1".into())]]
|
||||
);
|
||||
db.disconnect("test").await;
|
||||
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
|
||||
db.disconnect("test").await;
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb:memory:default"] {
|
||||
source.url = url.into();
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
|
||||
assert_eq!(
|
||||
db.execute("test", "select id from session_items", 1, &cancel).await?.rows,
|
||||
[vec![Some("42".into())]]
|
||||
);
|
||||
let join = "SELECT a.id FROM session_items a JOIN session_items b ON a.id = b.id";
|
||||
let nodes = db.explain("test", join, &cancel, None).await?;
|
||||
let join_node = nodes.iter().position(|n| n.operation == "HASH_JOIN").expect("physical join");
|
||||
assert_eq!(nodes.iter().filter(|n| n.parent == Some(join_node as u32)).count(), 2);
|
||||
assert!(nodes[join_node].properties.iter().any(|p| p.name == "Conditions" && p.value.contains("id")));
|
||||
let batch = db.explain("test", "SELECT 1; SELECT 2", &cancel, None).await.unwrap_err();
|
||||
assert!(batch.message.contains("one statement"));
|
||||
assert!(!db.explain("test", "SELECT ';' AS delimiter", &cancel, None).await?.is_empty());
|
||||
db.execute("test", "SET explain_output = 'optimized_only'", 1, &cancel).await?;
|
||||
assert!(!db.explain("test", "SELECT id FROM session_items", &cancel, None).await?.is_empty());
|
||||
db.explain("test", "INSERT INTO session_items VALUES (43)", &cancel, None).await?;
|
||||
assert_eq!(
|
||||
db.execute("test", "SELECT count(*) FROM session_items", 1, &cancel).await?.rows,
|
||||
[vec![Some("1".into())]]
|
||||
);
|
||||
db.disconnect("test").await;
|
||||
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
|
||||
db.disconnect("test").await;
|
||||
}
|
||||
|
||||
source.read_only = true;
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
|
||||
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:", "jdbc:duckdb:memory:default"] {
|
||||
source.url = url.into();
|
||||
let err = db.test(&source, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("existing database file"), "{}", err.message);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! `OPENIDEA_TEST_POSTGRES=host:port:user:password` names a throwaway server.
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{DataSource, DbDriver, DbManager};
|
||||
use ide_db::{DataSource, DbDriver, DbManager, DbPersistence};
|
||||
|
||||
fn server() -> Option<(String, u16, String, String)> {
|
||||
endpoint("OPENIDEA_TEST_POSTGRES")
|
||||
@@ -813,6 +813,75 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Modify Table's properties: owner, tablespace, access method, storage options (the TOAST
|
||||
/// table's too), partition key and persistence, read again after the statements it runs.
|
||||
#[tokio::test]
|
||||
async fn table_details_read_the_storage_properties() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
for stmt in [
|
||||
"DROP SCHEMA IF EXISTS oi_props CASCADE",
|
||||
"DROP ROLE IF EXISTS oi_props_owner",
|
||||
"CREATE ROLE oi_props_owner",
|
||||
"CREATE SCHEMA oi_props",
|
||||
"CREATE UNLOGGED TABLE oi_props.bulk (id INT, v TEXT) WITH (fillfactor = 70, toast.autovacuum_enabled = false)",
|
||||
"CREATE TABLE oi_props.events (id INT, at DATE) PARTITION BY RANGE (at)",
|
||||
"CREATE VIEW oi_props.recent AS SELECT 1 AS n",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
let owner = db.execute("p", "SELECT current_user", 1, &c).await?.rows[0][0].clone().unwrap();
|
||||
let default_tablespace = db
|
||||
.execute(
|
||||
"p",
|
||||
"SELECT t.spcname FROM pg_database d JOIN pg_tablespace t ON t.oid = d.dattablespace \
|
||||
WHERE d.datname = current_database()",
|
||||
1,
|
||||
&c,
|
||||
)
|
||||
.await?
|
||||
.rows[0][0]
|
||||
.clone();
|
||||
let options = |pairs: &[(&str, &str)]| Some(pairs.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect());
|
||||
|
||||
let bulk = db.table_details("p", "oi_props", "bulk").await?;
|
||||
assert_eq!(bulk.owner.as_deref(), Some(owner.as_str()));
|
||||
assert_eq!(bulk.tablespace, default_tablespace);
|
||||
assert_eq!(bulk.access_method.as_deref(), Some("heap"));
|
||||
assert_eq!(bulk.storage_options, options(&[("fillfactor", "70"), ("toast.autovacuum_enabled", "false")]));
|
||||
assert_eq!(bulk.partitioning, None);
|
||||
assert_eq!(bulk.persistence, Some(DbPersistence::Unlogged));
|
||||
|
||||
let events = db.table_details("p", "oi_props", "events").await?;
|
||||
assert_eq!(events.partitioning.as_deref(), Some("RANGE (at)"));
|
||||
assert_eq!(events.storage_options, options(&[]));
|
||||
assert_eq!(events.persistence, Some(DbPersistence::Permanent));
|
||||
// A view has none of a table's storage.
|
||||
let recent = db.table_details("p", "oi_props", "recent").await?;
|
||||
assert_eq!((recent.owner, recent.storage_options, recent.persistence), (None, None, None));
|
||||
|
||||
// The statements Modify Table generates (objects.ts `tablePropertiesSql`).
|
||||
for stmt in [
|
||||
"alter table oi_props.bulk set logged;",
|
||||
"alter table oi_props.bulk reset (toast.autovacuum_enabled);",
|
||||
"alter table oi_props.bulk set (fillfactor = 50, autovacuum_enabled = false);",
|
||||
"alter table oi_props.bulk set tablespace pg_default;",
|
||||
"alter table oi_props.bulk owner to oi_props_owner;",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
let bulk = db.table_details("p", "oi_props", "bulk").await?;
|
||||
assert_eq!(bulk.owner.as_deref(), Some("oi_props_owner"));
|
||||
assert_eq!(bulk.tablespace.as_deref(), Some("pg_default"));
|
||||
assert_eq!(bulk.storage_options, options(&[("fillfactor", "50"), ("autovacuum_enabled", "false")]));
|
||||
assert_eq!(bulk.persistence, Some(DbPersistence::Permanent));
|
||||
for stmt in ["DROP SCHEMA oi_props CASCADE", "DROP ROLE oi_props_owner"] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
|
||||
/// the other schemas, and the tables sorting last lost theirs (#6118).
|
||||
#[tokio::test]
|
||||
|
||||
@@ -423,11 +423,25 @@ pub struct CapabilityInfo {
|
||||
pub optional: bool,
|
||||
/// Currently granted.
|
||||
pub granted: bool,
|
||||
/// The plugin's own explanation (`[capabilities.reasons]`), shown below `description`.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
/// `reason` translated by the plugin's `locales/<tag>.json`, by language tag.
|
||||
#[serde(default)]
|
||||
pub reason_locales: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl CapabilityInfo {
|
||||
pub fn new(cap: &Capability, optional: bool, granted: bool) -> Self {
|
||||
Self { id: cap.to_string(), risk: cap.risk(), description: cap.describe(), optional, granted }
|
||||
Self {
|
||||
id: cap.to_string(),
|
||||
risk: cap.risk(),
|
||||
description: cap.describe(),
|
||||
optional,
|
||||
granted,
|
||||
reason: None,
|
||||
reason_locales: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,12 +29,14 @@ use crate::capability::Capability;
|
||||
use crate::plugin_point::PointDecl;
|
||||
use crate::resolve::Dependency;
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.18.0";
|
||||
pub const ENGINE_VERSION: &str = "1.19.0";
|
||||
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
|
||||
pub const MAX_CAPABILITY_REASON: usize = 500;
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
@@ -84,6 +86,10 @@ pub struct Manifest {
|
||||
pub struct Capabilities {
|
||||
pub required: Vec<Capability>,
|
||||
pub optional: Vec<Capability>,
|
||||
/// `[capabilities.reasons]` (API 1.19): the plugin's own words on why it asks for a
|
||||
/// declared capability, keyed by the capability as printed (`net:127.0.0.1`). Shown
|
||||
/// below the host's description, never instead of it.
|
||||
pub reasons: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Capabilities {
|
||||
@@ -94,6 +100,11 @@ impl Capabilities {
|
||||
pub fn is_optional(&self, cap: &Capability) -> bool {
|
||||
self.optional.contains(cap) && !self.required.contains(cap)
|
||||
}
|
||||
|
||||
/// The plugin's explanation of `cap`, if it gave one.
|
||||
pub fn reason(&self, cap: &Capability) -> Option<&str> {
|
||||
self.reasons.get(&cap.to_string()).map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
/// When a plugin's code is instantiated (plan 4.4). Contributions are live
|
||||
@@ -251,6 +262,8 @@ struct RawCapabilities {
|
||||
required: Vec<String>,
|
||||
#[serde(default)]
|
||||
optional: Vec<String>,
|
||||
#[serde(default)]
|
||||
reasons: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
@@ -279,8 +292,18 @@ impl Manifest {
|
||||
Ok(out)
|
||||
};
|
||||
let capabilities = match (raw.capabilities, raw.permissions) {
|
||||
(Some(c), _) => Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)? },
|
||||
(None, Some(p)) => Capabilities { required: parse_caps(p)?, optional: Vec::new() },
|
||||
(Some(c), _) => {
|
||||
let mut reasons = BTreeMap::new();
|
||||
for (key, text) in c.reasons {
|
||||
// Keyed as the capability prints, so `net:Example.com` finds `net:example.com`.
|
||||
let cap: Capability = key.parse().map_err(|e| format!("capabilities.reasons: {e}"))?;
|
||||
reasons.insert(cap.to_string(), text);
|
||||
}
|
||||
Capabilities { required: parse_caps(c.required)?, optional: parse_caps(c.optional)?, reasons }
|
||||
}
|
||||
(None, Some(p)) => {
|
||||
Capabilities { required: parse_caps(p)?, optional: Vec::new(), reasons: BTreeMap::new() }
|
||||
}
|
||||
(None, None) => Capabilities::default(),
|
||||
};
|
||||
let activation = match raw.activation {
|
||||
@@ -365,6 +388,19 @@ impl Manifest {
|
||||
self.needs_api("`change-notes-file`", 18)?;
|
||||
check_relative(path, "change-notes-file")?;
|
||||
}
|
||||
if !self.capabilities.reasons.is_empty() {
|
||||
self.needs_api("`capabilities.reasons`", 19)?;
|
||||
}
|
||||
for (key, text) in &self.capabilities.reasons {
|
||||
if !self.capabilities.all().any(|c| c.to_string() == *key) {
|
||||
return Err(format!("capabilities.reasons: {key:?} is not under `required` or `optional`"));
|
||||
}
|
||||
if text.trim().is_empty() || text.chars().count() > MAX_CAPABILITY_REASON {
|
||||
return Err(format!(
|
||||
"capabilities.reasons: the reason for {key:?} must be 1 to {MAX_CAPABILITY_REASON} characters"
|
||||
));
|
||||
}
|
||||
}
|
||||
for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) {
|
||||
if matches!(
|
||||
cap,
|
||||
@@ -780,6 +816,33 @@ required = [\"lsp:phoxite\"]
|
||||
assert_eq!(m.capabilities.optional, [Capability::BuildRead]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_reasons_explain_declared_capabilities_from_api_1_19() {
|
||||
let caps = "[capabilities]\nrequired = [\"net:Example.com\"]\noptional = [\"clipboard.read\"]\n\
|
||||
[capabilities.reasons]\n\"net:Example.com\" = \"Fetches the schema.\"\n\
|
||||
\"clipboard.read\" = \"Imports a log you copied.\"\n";
|
||||
assert!(err(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).contains("new in plugin API 1.19"));
|
||||
let src = |caps: &str| format!("{}{caps}", BASE.replace("^1.2", "^1.19"));
|
||||
let m = Manifest::parse(&src(caps)).unwrap();
|
||||
// Keyed as the capability prints.
|
||||
assert_eq!(m.capabilities.reason(&Capability::Net("example.com".into())), Some("Fetches the schema."));
|
||||
assert_eq!(m.capabilities.reason(&Capability::ClipboardRead), Some("Imports a log you copied."));
|
||||
assert_eq!(m.capabilities.reason(&Capability::ProjectRead), None);
|
||||
|
||||
let undeclared =
|
||||
"[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.write\" = \"x\"\n";
|
||||
assert!(err(&src(undeclared)).contains("not under `required` or `optional`"));
|
||||
let invalid = "[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"teleport\" = \"x\"\n";
|
||||
assert!(err(&src(invalid)).contains("capabilities.reasons"));
|
||||
let empty = "[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.read\" = \" \"\n";
|
||||
assert!(err(&src(empty)).contains("1 to 500 characters"));
|
||||
let long = format!(
|
||||
"[capabilities]\nrequired = [\"project.read\"]\n[capabilities.reasons]\n\"project.read\" = \"{}\"\n",
|
||||
"x".repeat(MAX_CAPABILITY_REASON + 1)
|
||||
);
|
||||
assert!(err(&src(&long)).contains("1 to 500 characters"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipboard_read_capability_needs_api_1_11() {
|
||||
let caps = "[capabilities]\noptional = [\"clipboard.read\"]\n";
|
||||
|
||||
@@ -404,12 +404,19 @@ impl Host {
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
self.debugger.forget_breakpoints(self.owner_window(window));
|
||||
self.external_logs.write().remove(self.owner_window(window));
|
||||
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
|
||||
let owner = self.owner_window(window);
|
||||
let (project, requests) = {
|
||||
// A request registering after the drain must not resolve the old project.
|
||||
let mut project_requests = self.project_requests.write();
|
||||
let mut projects = self.projects.write();
|
||||
(projects.remove(window), project_requests.remove(owner).unwrap_or_default())
|
||||
};
|
||||
for request in requests {
|
||||
self.cancel_request(request);
|
||||
}
|
||||
// After the cancels: a capture or open still running then discards what it registers.
|
||||
ops::heap::close_window_snapshots(self, window);
|
||||
let project = self.projects.write().remove(window)?;
|
||||
let project = project?;
|
||||
project.closed.cancel();
|
||||
if let Some(plugins) = self.plugin_host() {
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
@@ -791,6 +798,25 @@ impl Host {
|
||||
let exe = self.global_settings.read_effective(|s| s.vcs.git.executable.trim().to_owned());
|
||||
ide_vcs::set_default_git_executable((!exe.is_empty()).then(|| Path::new(&exe)));
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Git › Enable Git integration, as it applies to `window`
|
||||
/// (its project's effective value, the global one without a project).
|
||||
pub fn git_enabled(&self, window: &str) -> bool {
|
||||
match self.project(window) {
|
||||
Ok(project) => project.git_enabled(),
|
||||
Err(_) => self.global_settings.read_effective(|s| s.vcs.git.enabled),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fails while Git integration is switched off for `window`: commands that start git
|
||||
/// outside the project's repositories (clone, init, an external log) check it first.
|
||||
pub fn ensure_git_enabled(&self, window: &str) -> IdeResult<()> {
|
||||
if self.git_enabled(window) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ide_core::IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -251,6 +251,7 @@ fn git_status() -> Tool {
|
||||
Returns porcelain-style index/worktree status codes and summary counters.
|
||||
By default all Git repositories are returned.",
|
||||
|call| async move {
|
||||
call.host.ensure_git_enabled(&call.window)?;
|
||||
let include_untracked = call.flag("includeUntracked", true)?;
|
||||
let include_ignored = call.flag("includeIgnored", false)?;
|
||||
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
|
||||
@@ -360,6 +361,7 @@ By default all Git repositories are returned.",
|
||||
|
||||
fn git_diff() -> Tool {
|
||||
Tool::new("git_diff", "Read a Git diff for a file or the working tree. staged=true compares the index with HEAD; otherwise compares disk with the index. Unsaved editor text is not part of this diff.", |call| async move {
|
||||
call.host.ensure_git_enabled(&call.window)?;
|
||||
let wanted = call.opt_str("repositoryPathRelativeToProject")?;
|
||||
let path = wanted.as_deref().map(|p| call.resolve_inside(p)).transpose()?.unwrap_or_else(|| call.root().to_path_buf());
|
||||
let root = find_git_root(call.root(), &path).ok_or_else(|| IdeError::not_found("No git repository found"))?;
|
||||
|
||||
@@ -947,12 +947,27 @@ pub fn route(spec: &[Entry], id: &str) -> Option<MenuRoute> {
|
||||
|
||||
/// `entries` without the action `id` (and a separator it leaves doubled or trailing).
|
||||
pub fn without_action(entries: Vec<Entry>, id: &str) -> Vec<Entry> {
|
||||
without(entries, &|e| e == id)
|
||||
}
|
||||
|
||||
/// `entries` without the submenus and actions [`MenuConfig::hidden`] lists.
|
||||
pub fn without_hidden(entries: Vec<Entry>, config: &MenuConfig) -> Vec<Entry> {
|
||||
if config.hidden.is_empty() {
|
||||
return entries;
|
||||
}
|
||||
without(entries, &|id| config.hidden.iter().any(|h| h == id))
|
||||
}
|
||||
|
||||
/// `entries` without the actions and submenus whose id `drop` matches, and the separators
|
||||
/// left dangling.
|
||||
fn without(entries: Vec<Entry>, drop: &dyn Fn(&str) -> bool) -> Vec<Entry> {
|
||||
let mut out: Vec<Entry> = Vec::with_capacity(entries.len());
|
||||
for e in entries {
|
||||
match e {
|
||||
Entry::Action { id: a, .. } if a == id => {}
|
||||
Entry::Action { id: a, .. } if drop(a) => {}
|
||||
Entry::Submenu { id: sid, .. } if drop(sid) => {}
|
||||
Entry::Submenu { id: sid, label, children } => {
|
||||
out.push(Entry::Submenu { id: sid, label, children: without_action(children, id) })
|
||||
out.push(Entry::Submenu { id: sid, label, children: without(children, drop) })
|
||||
}
|
||||
Entry::Separator if matches!(out.last(), None | Some(Entry::Separator)) => {}
|
||||
e => out.push(e),
|
||||
@@ -996,6 +1011,9 @@ pub struct MenuConfig {
|
||||
/// Ids of the toggle actions currently on.
|
||||
#[serde(default)]
|
||||
pub checked: Vec<String>,
|
||||
/// Ids of submenus and actions left out of the menu (the Git menu while Git integration is off).
|
||||
#[serde(default)]
|
||||
pub hidden: Vec<String>,
|
||||
}
|
||||
|
||||
/// An item of a frontend-listed menu slot.
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, IpcPath, RequestId};
|
||||
use ide_db::split::SqlStatement;
|
||||
use ide_db::workspace::WorkspaceJoinPlan;
|
||||
use ide_db::{
|
||||
CompletionModel, ConsoleId, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange,
|
||||
HistoryEntry, PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
|
||||
@@ -15,6 +16,27 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_workspace_join(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
driver: String,
|
||||
plan: WorkspaceJoinPlan,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = async {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.workspace_join(&driver, plan, &cancel).await
|
||||
}
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// One statement of a console run.
|
||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -33,6 +55,11 @@ pub enum ExecutionEvent {
|
||||
Done { error: Option<IdeError> },
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_approve_ducklake_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
|
||||
host.project(window)?.db.approve_ducklake_source(&source)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_approve_jdbc_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
|
||||
host.project(window)?.db.approve_jdbc_source(&source)
|
||||
@@ -75,6 +102,12 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_create_ducklake(host: &Host, window: &str, jdbc_driver: String, directory: String) -> IdeResult<()> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.create_ducklake(&jdbc_driver, &directory).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
|
||||
// The project's user-created folders and their data source members.
|
||||
@@ -829,6 +862,7 @@ pub async fn server_version(host: &Host, window: &str, id: &str) -> IdeResult<u3
|
||||
ide_command::domain!(
|
||||
db:
|
||||
db_apply_edits,
|
||||
db_workspace_join,
|
||||
db_completion,
|
||||
db_connect,
|
||||
db_connected,
|
||||
@@ -836,6 +870,7 @@ ide_command::domain!(
|
||||
db_consoles_dir,
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_create_ducklake,
|
||||
db_database_catalog,
|
||||
db_catalog_table_details,
|
||||
db_catalog_table_page,
|
||||
@@ -851,6 +886,7 @@ ide_command::domain!(
|
||||
db_history,
|
||||
db_jdbc_driver_classes,
|
||||
db_jdbc_drivers,
|
||||
db_approve_ducklake_source,
|
||||
db_approve_jdbc_source,
|
||||
db_save_jdbc_driver,
|
||||
db_remove_jdbc_driver,
|
||||
@@ -911,6 +947,118 @@ mod tests {
|
||||
host
|
||||
}
|
||||
|
||||
fn workspace_test_plan() -> WorkspaceJoinPlan {
|
||||
use ide_db::workspace::{WorkspaceJoinColumn, WorkspaceJoinCondition, WorkspaceJoinRelation};
|
||||
let relation = |id: &str| WorkspaceJoinRelation {
|
||||
source_id: id.into(),
|
||||
database: "default".into(),
|
||||
schema: "default".into(),
|
||||
table: "items".into(),
|
||||
};
|
||||
WorkspaceJoinPlan {
|
||||
tables: vec![relation("left"), relation("right")],
|
||||
joins: vec![WorkspaceJoinCondition {
|
||||
left: WorkspaceJoinColumn { relation: 0, column: "id".into() },
|
||||
right_column: "id".into(),
|
||||
}],
|
||||
projection: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn workspace_join_respects_an_early_cancel() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let request = RequestId(1);
|
||||
host.cancel_request(request);
|
||||
let error = db_workspace_join(&host, "main", request, "no driver installed".into(), workspace_test_plan())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn workspace_join_cannot_resolve_a_project_after_its_requests_are_drained() {
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let window = "main";
|
||||
let active = host.begin_project_request(window, RequestId(1));
|
||||
std::thread::scope(|threads| {
|
||||
// Hold close at heap cleanup, which follows cancellation of registered requests.
|
||||
let heap = host.heap_windows.lock();
|
||||
let close = threads.spawn(|| host.close_project_detached(window));
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
while !active.is_cancelled() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let drained = active.is_cancelled();
|
||||
let detached = host.project(window).is_err();
|
||||
drop(heap);
|
||||
close.join().unwrap();
|
||||
|
||||
assert!(drained, "close did not reach the cancellation step");
|
||||
assert!(detached, "close drained its requests while the old project was still available");
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and Java 17+"]
|
||||
async fn workspace_join_stops_when_its_project_closes() {
|
||||
use std::time::Duration;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let host = host_with_sqlite(&temp).await;
|
||||
let window = "main";
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let sources = ["left", "right"].map(|id| DataSource {
|
||||
id: id.into(),
|
||||
name: format!("ClickHouse fixture {id}"),
|
||||
driver: DbDriver::Clickhouse,
|
||||
host: "127.0.0.1".into(),
|
||||
port: Some(listener.local_addr().unwrap().port()),
|
||||
..Default::default()
|
||||
});
|
||||
db_save_sources(&host, window, sources.into()).await.unwrap();
|
||||
host.project(window)
|
||||
.unwrap()
|
||||
.db
|
||||
.save_jdbc_driver(ide_db::DbJdbcDriver {
|
||||
id: "duck".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: Some("duckdb".into()),
|
||||
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("official JDBC fixture")],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: "jdbc:duckdb:".into(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
for (request, close_project) in [(RequestId(2), false), (RequestId(3), true)] {
|
||||
let join = db_workspace_join(&host, window, request, "duck".into(), workspace_test_plan());
|
||||
tokio::pin!(join);
|
||||
// Accept the source connection and leave it open without replying.
|
||||
let (socket, _) = tokio::select! {
|
||||
result = &mut join => panic!("workspace ended before reaching the source: {result:?}"),
|
||||
peer = tokio::time::timeout(Duration::from_secs(15), listener.accept()) => peer.unwrap().unwrap(),
|
||||
};
|
||||
if close_project {
|
||||
host.close_project_detached(window);
|
||||
} else {
|
||||
host.cancel_request(request);
|
||||
}
|
||||
let stopped = tokio::time::timeout(Duration::from_secs(3), &mut join).await;
|
||||
if stopped.is_err() {
|
||||
host.cancel_request(request);
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), &mut join).await;
|
||||
}
|
||||
let error = stopped.expect("workspace JOIN did not stop after cancellation").unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(!host.project_requests.read().values().flatten().any(|entry| *entry == request));
|
||||
drop(socket);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "requires a disposable loopback PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT"]
|
||||
async fn postgres_console_commands_keep_commit_result_reads_and_release_scoped() {
|
||||
|
||||
@@ -515,6 +515,17 @@ pub async fn debug_step(host: &Host, session: DebugSessionId, thread_id: i64, ki
|
||||
host.debugger.step(session, thread_id, kind).await
|
||||
}
|
||||
|
||||
/// Step Over / Into Instruction: a step by one machine instruction.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_step_instruction(
|
||||
host: &Host,
|
||||
session: DebugSessionId,
|
||||
thread_id: i64,
|
||||
kind: StepKind,
|
||||
) -> IdeResult<()> {
|
||||
host.debugger.step_instruction(session, thread_id, kind).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_run_to(
|
||||
host: &Host,
|
||||
@@ -557,6 +568,32 @@ pub async fn debug_evaluate_in(
|
||||
host.debugger.evaluate_in(session, frame_id, expression, context).await
|
||||
}
|
||||
|
||||
/// Memory View: `count` bytes from `offset` bytes after `memory_reference` (a variable's,
|
||||
/// an evaluation result's or an earlier read's address).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_read_memory(
|
||||
host: &Host,
|
||||
session: DebugSessionId,
|
||||
memory_reference: String,
|
||||
offset: i64,
|
||||
count: u32,
|
||||
) -> IdeResult<ide_dap::MemoryBlock> {
|
||||
host.debugger.read_memory(session, memory_reference, offset, count).await
|
||||
}
|
||||
|
||||
/// Disassembly view: `count` instructions from `before` instructions ahead of `memory_reference`
|
||||
/// (a frame's instruction pointer or an instruction's address).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_disassemble(
|
||||
host: &Host,
|
||||
session: DebugSessionId,
|
||||
memory_reference: String,
|
||||
before: u32,
|
||||
count: u32,
|
||||
) -> IdeResult<Vec<ide_dap::Instruction>> {
|
||||
host.debugger.disassemble(session, memory_reference, before, count).await
|
||||
}
|
||||
|
||||
/// Last known verification states of a file's breakpoints (refetch on `breakpointsChanged`).
|
||||
#[command(trust = trusted)]
|
||||
pub fn debug_breakpoint_states(host: &Host, path: PathBuf) -> IdeResult<Vec<BreakpointState>> {
|
||||
@@ -1066,6 +1103,7 @@ ide_command::domain!(
|
||||
debug_capabilities,
|
||||
debug_completions,
|
||||
debug_data_breakpoint_info,
|
||||
debug_disassemble,
|
||||
debug_evaluate,
|
||||
debug_evaluate_in,
|
||||
debug_exception_filters,
|
||||
@@ -1083,6 +1121,7 @@ ide_command::domain!(
|
||||
debug_jvm_thread_dump,
|
||||
debug_listen_for_jvm,
|
||||
debug_pause,
|
||||
debug_read_memory,
|
||||
debug_redefine_classes,
|
||||
debug_replace_breakpoints,
|
||||
debug_resolve_variable,
|
||||
@@ -1103,6 +1142,7 @@ ide_command::domain!(
|
||||
debug_step,
|
||||
debug_step_in_target,
|
||||
debug_step_in_targets,
|
||||
debug_step_instruction,
|
||||
debug_stop,
|
||||
debug_threads,
|
||||
debug_unity_processes,
|
||||
|
||||
@@ -18,6 +18,9 @@ use std::path::{Path, PathBuf};
|
||||
/// primary repository (a folder holding several repositories is not one itself).
|
||||
fn root(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<PathBuf> {
|
||||
let project = host.project(window)?;
|
||||
if !project.git_enabled() {
|
||||
return Err(IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"));
|
||||
}
|
||||
let repos = project.repos();
|
||||
match repo {
|
||||
Some(at) => match repos.at_root(&at) {
|
||||
@@ -220,6 +223,7 @@ mod tests {
|
||||
use crate::rpc::Dispatcher;
|
||||
use crate::{Host, HostConfig};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_workspace::SettingsScope;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -272,4 +276,17 @@ mod tests {
|
||||
let outsider = root(&host, "main", Some(dir.path().join("other"))).unwrap_err();
|
||||
assert_eq!(outsider.kind, ErrorKind::Unavailable);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_gh_while_git_integration_is_off() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let host = test_host(dir.path());
|
||||
let proj_dir = dir.path().join("repo");
|
||||
std::fs::create_dir_all(&proj_dir).unwrap();
|
||||
host.global_settings.set(SettingsScope::Global, "vcs.git.enabled", serde_json::json!(false)).unwrap();
|
||||
host.open_project("main", &proj_dir).unwrap();
|
||||
let err = root(&host, "main", None).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert!(err.message.contains("Git integration is disabled"), "{}", err.message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//! iOS Simulators for Xcode projects, through `xcrun simctl` on the project host.
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_run::simulator::{self, IosSimulator};
|
||||
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// The available iOS simulators, booted first; `None` outside macOS or when the project has no
|
||||
/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has
|
||||
/// no change feed, and one listing takes a fraction of a second.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult<Option<Vec<IosSimulator>>> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
if !cfg!(target_os = "macos") || !simulator::is_xcode_project(&root) {
|
||||
return Ok(None);
|
||||
}
|
||||
blocking(simulator::list).await.map(Some)
|
||||
}
|
||||
|
||||
/// Boots a simulator; returns once it is booted.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulator_boot(_host: &Host, udid: String) -> IdeResult<()> {
|
||||
blocking(move || simulator::boot(&udid)).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulator_shutdown(_host: &Host, udid: String) -> IdeResult<()> {
|
||||
blocking(move || simulator::shutdown(&udid)).await
|
||||
}
|
||||
|
||||
/// Opens Simulator.app.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn ios_simulator_open_app(_host: &Host) -> IdeResult<()> {
|
||||
blocking(simulator::open_app).await
|
||||
}
|
||||
|
||||
ide_command::domain!(ios: ios_simulators, ios_simulator_boot, ios_simulator_shutdown, ios_simulator_open_app);
|
||||
@@ -22,6 +22,7 @@ pub mod heap;
|
||||
pub mod history;
|
||||
pub mod host_metrics;
|
||||
pub mod http;
|
||||
pub mod ios;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
pub mod lsp;
|
||||
@@ -103,6 +104,7 @@ ide_command::domains!(
|
||||
history: crate::ops::history,
|
||||
host_metrics: crate::ops::host_metrics,
|
||||
http: crate::ops::http,
|
||||
ios: crate::ops::ios,
|
||||
java: crate::ops::java,
|
||||
jvm_icons: crate::ops::jvm_icons,
|
||||
lsp: crate::ops::lsp,
|
||||
|
||||
@@ -4,12 +4,14 @@ use super::pytest_fixtures::{
|
||||
fixture_usages, rename_fixture,
|
||||
};
|
||||
use super::python_stubs::{
|
||||
PythonStubLinks, counterpart_candidates, match_declarations, module_name, site_packages, stub_path,
|
||||
PythonStubLinks, counterpart_candidates, interpreter_site_packages, match_declarations, module_name, site_packages,
|
||||
stub_path,
|
||||
};
|
||||
use crate::Host;
|
||||
use crate::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos, RequestId};
|
||||
use ide_index::python_library::{PythonImportCandidate, PythonLibraries};
|
||||
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
|
||||
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
|
||||
use ide_workspace::file_refs::{self, PathCompletion};
|
||||
@@ -499,6 +501,41 @@ pub async fn nav_pytest_fixtures(host: &Host, window: &str, doc: DocId, pos: Pos
|
||||
.await
|
||||
}
|
||||
|
||||
static PYTHON_LIBRARIES: std::sync::LazyLock<PythonLibraries> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// Imports that bind `name` from the packages installed in the interpreter of the Python document
|
||||
/// `doc` (its workspace member's, else the project's): PyCharm's "Import this name" for library
|
||||
/// symbols, which basedpyright offers for the project and the standard library only. The first
|
||||
/// request indexes the interpreter's `site-packages` in the background, and a change there
|
||||
/// re-indexes it; a request waits for the index until cancelled.
|
||||
#[command(trust = always)]
|
||||
pub async fn nav_python_library_imports(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
name: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<PythonImportCandidate>> {
|
||||
let project = host.project(window)?;
|
||||
let syntax = host.syntax();
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_request(request);
|
||||
let result = blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.language.as_str() != "python" {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let Some(python) = super::sdk::effective_python(&config_dir, &project, Some(&snap.path)) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let roots = interpreter_site_packages(&python);
|
||||
Ok(PYTHON_LIBRARIES.index(&roots, &syntax, &token).map(|index| index.candidates(&name)).unwrap_or_default())
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Find Usages of the pytest fixture at `pos` (its definition, or a place asking for it): every
|
||||
/// test and fixture parameter, `usefixtures` and `getfixturevalue` string that gets it.
|
||||
/// None when `pos` names no fixture. Cancellable.
|
||||
@@ -593,6 +630,7 @@ ide_command::domain!(
|
||||
nav_pytest_fixture_target,
|
||||
nav_pytest_fixture_usages,
|
||||
nav_pytest_fixtures,
|
||||
nav_python_library_imports,
|
||||
nav_python_stubs,
|
||||
nav_resolve_module,
|
||||
path_completions,
|
||||
|
||||
@@ -437,8 +437,13 @@ pub fn set_settings(
|
||||
}
|
||||
});
|
||||
}
|
||||
// Directory Mappings change which repositories the project has.
|
||||
if key == "vcs" || key == "vcs.mappings" || key.starts_with("vcs.mappings.") {
|
||||
// Directory Mappings and Enable Git integration change which repositories the project has.
|
||||
if key == "vcs"
|
||||
|| key == "vcs.mappings"
|
||||
|| key.starts_with("vcs.mappings.")
|
||||
|| key == "vcs.git"
|
||||
|| key == "vcs.git.enabled"
|
||||
{
|
||||
let affected = affected();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
for project in affected {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! plugins' `pytest11` entry points, pytest's own `_pytest` package), for Go to Declaration
|
||||
//! and completion of fixture names.
|
||||
|
||||
use super::python_stubs::site_packages;
|
||||
use super::python_stubs::interpreter_site_packages as python_site_packages;
|
||||
use crate::Project;
|
||||
use ide_core::{FileEdit, IdeError, IdeResult, IpcPath, LanguageId, Location, Pos, Range, TextEdit, WorkspaceEdit};
|
||||
use ide_language::{PytestModule, Syntax, resolve_fixture, visible_fixtures};
|
||||
@@ -623,8 +623,7 @@ fn glob_match(pattern: &str, name: &str) -> bool {
|
||||
fn interpreter_site_packages(project: &Project) -> Vec<PathBuf> {
|
||||
let settings = project.settings.effective();
|
||||
let Some(python) = ide_sdk::apply::python_interpreter(&project.root, &settings) else { return Vec::new() };
|
||||
let prefix = ide_sdk::venv_of(&python).or_else(|| python.parent()?.parent().map(Path::to_path_buf));
|
||||
prefix.map(|p| site_packages(&p)).unwrap_or_default()
|
||||
python_site_packages(&python)
|
||||
}
|
||||
|
||||
/// `pkg.mod` → `pkg/mod.py` or `pkg/mod/__init__.py` in the first folder that has it.
|
||||
|
||||
@@ -56,6 +56,19 @@ pub(crate) fn site_packages(venv: &Path) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The `site-packages` of the interpreter `python`, found on disk without running it: in the
|
||||
/// environment holding its `bin` / `Scripts` folder (a virtualenv, a conda environment, an install
|
||||
/// prefix), else in its own folder (a conda environment on Windows keeps `python.exe` at its root).
|
||||
pub(crate) fn interpreter_site_packages(python: &Path) -> Vec<PathBuf> {
|
||||
let home = python.parent();
|
||||
[home.and_then(Path::parent), home]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(site_packages)
|
||||
.find(|p| !p.is_empty())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The dotted module of a Python file, from the innermost `search` folder holding it
|
||||
/// (`src/a/b.py` → `a.b`, `site-packages/a/__init__.py` → `a`).
|
||||
pub(crate) fn module_name(path: &Path, search: &[PathBuf]) -> Option<String> {
|
||||
@@ -227,4 +240,20 @@ mod tests {
|
||||
links.iter().map(|l| (l.name.as_str(), l.range.start.line, l.target.start.line)).collect();
|
||||
assert_eq!(names, [("f", 0, 2), ("C", 4, 5), ("C.__init__", 5, 6), ("C.m", 6, 7)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreter_site_packages_of_venvs_and_conda_environments() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let unix = dir.path().join("envs/langchain");
|
||||
std::fs::create_dir_all(unix.join("lib/python3.13/site-packages")).unwrap();
|
||||
assert_eq!(interpreter_site_packages(&unix.join("bin/python")), [unix.join("lib/python3.13/site-packages")]);
|
||||
// Windows: `.venv\Scripts\python.exe`, and conda's `<env>\python.exe`.
|
||||
let venv = dir.path().join(".venv");
|
||||
std::fs::create_dir_all(venv.join("Lib/site-packages")).unwrap();
|
||||
assert_eq!(interpreter_site_packages(&venv.join("Scripts/python.exe")), [venv.join("Lib/site-packages")]);
|
||||
let conda = dir.path().join("miniconda/envs/data");
|
||||
std::fs::create_dir_all(conda.join("Lib/site-packages")).unwrap();
|
||||
assert_eq!(interpreter_site_packages(&conda.join("python.exe")), [conda.join("Lib/site-packages")]);
|
||||
assert!(interpreter_site_packages(&dir.path().join("nowhere/bin/python")).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -540,6 +540,15 @@ async fn start_inner(
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
}
|
||||
if config.kind == "xcode" {
|
||||
let (dir, cache) = (run_dir.clone(), project.cache_dir.clone());
|
||||
config = host
|
||||
.blocking(move || {
|
||||
ide_run::xcode::prepare(&dir, &cache, &mut config)?;
|
||||
Ok(config)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
if config.kind == "go" && config.extras.params.get("scope").is_some_and(|s| s == "file") {
|
||||
let root = project.root.clone();
|
||||
config = host
|
||||
|
||||
@@ -45,6 +45,7 @@ fn frame(line: u32) -> StackFrame {
|
||||
line,
|
||||
column: 8,
|
||||
presentation_hint: None,
|
||||
instruction_pointer_reference: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -911,6 +911,7 @@ pub async fn vcs_log_users(host: &Host, window: &str, repo: Option<PathBuf>) ->
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_open_external_log(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
|
||||
host.ensure_git_enabled(window)?;
|
||||
let path = dunce::canonicalize(path)?;
|
||||
let repo = Repo::discover(&path)?.ok_or_else(|| ide_core::IdeError::unavailable("folder is not a Git worktree"))?;
|
||||
let root = repo.root().to_path_buf();
|
||||
@@ -2002,6 +2003,9 @@ pub async fn vcs_clone(
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
let settings = host.global_settings.effective();
|
||||
if !settings.vcs.git.enabled {
|
||||
return Err(ide_core::IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git"));
|
||||
}
|
||||
let recurse_submodules = settings.vcs.git.clone_submodules;
|
||||
let cancel = host.begin_request(request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
@@ -2020,6 +2024,7 @@ pub async fn vcs_clone(
|
||||
/// detected again before it returns, so the new one is known to the next command.
|
||||
#[command(trust = always)]
|
||||
pub async fn vcs_init(host: &Host, window: &str, dir: PathBuf) -> IdeResult<()> {
|
||||
host.ensure_git_enabled(window)?;
|
||||
let project = host.project(window).ok();
|
||||
let git = project.as_ref().and_then(|p| p.git_executable());
|
||||
blocking(move || {
|
||||
|
||||
@@ -10,7 +10,7 @@ use ide_extension::ledger::{Ledger, Subject};
|
||||
use ide_language::ProgramPin;
|
||||
use ide_plugin::{
|
||||
CommitChange, CommitDraft, EventKind, HostApi, HostError, HttpRequest, HttpResponse, NotificationLevel,
|
||||
ProcessChunk, ProcessCommand, ProcessOptions, ProcessOutput, Prompt, RepositoryStatus, StatusItem,
|
||||
ProcessChunk, ProcessCommand, ProcessOptions, ProcessOutput, Prompt, RepositoryStatus, SettingsTarget, StatusItem,
|
||||
};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
@@ -155,6 +155,11 @@ pub trait PluginWorkspace: Send + Sync {
|
||||
fn git_executable(&self, _root: &Path) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
/// Settings › Version Control › Git › Enable Git integration of the project at `root`:
|
||||
/// off, plugins find no repository there.
|
||||
fn git_enabled(&self, _root: &Path) -> bool {
|
||||
true
|
||||
}
|
||||
/// Root of the project open in `window`.
|
||||
fn project_of(&self, window: &str) -> Option<PathBuf>;
|
||||
/// Windows showing the open project at `root`, the most recently focused first.
|
||||
@@ -1584,6 +1589,9 @@ pub(super) fn commit_draft(
|
||||
if cancel.is_cancelled() {
|
||||
return Err(HostError::Cancelled);
|
||||
}
|
||||
if !workspace.git_enabled(&repo.root.0) {
|
||||
return Err(HostError::Failed("Git integration is disabled".into()));
|
||||
}
|
||||
let Some(r) = ide_vcs::Repo::discover(&repo.root.0).map_err(failed)? else {
|
||||
return Err(HostError::NotFound(format!("{} is not in a git repository", repo.root.0.display())));
|
||||
};
|
||||
@@ -2442,6 +2450,31 @@ impl HostApi for PluginApi {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_settings(&self, client: Option<&str>, target: SettingsTarget) -> Result<(), HostError> {
|
||||
let client = from_window(client, "open Settings")?;
|
||||
let (page, permissions) = match target {
|
||||
SettingsTarget::Permissions => (None, true),
|
||||
SettingsTarget::Page(page) => {
|
||||
let decls = self.shared.ui.items(super::ui_points::SETTINGS, Some(self.id()));
|
||||
let Some(decl) = decls.first().map(|i| &i.decl) else {
|
||||
return Err(HostError::NotFound("the plugin declares no [contributes.settings]".into()));
|
||||
};
|
||||
if let Some(page) = &page {
|
||||
let pages = decl.get("pages").and_then(|p| p.as_array());
|
||||
if !pages.is_some_and(|ps| ps.iter().any(|p| p.get("id").and_then(|id| id.as_str()) == Some(page)))
|
||||
{
|
||||
return Err(HostError::NotFound(format!("the plugin declares no settings page {page:?}")));
|
||||
}
|
||||
}
|
||||
(page, false)
|
||||
}
|
||||
};
|
||||
self.shared
|
||||
.sink
|
||||
.emit(Some(client), PluginEvent::OpenSettings { plugin_id: self.id().to_owned(), page, permissions });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn status_item(&self, id: &str, item: Option<StatusItem>) {
|
||||
let key = (self.id().to_owned(), id.to_owned());
|
||||
{
|
||||
@@ -2633,6 +2666,9 @@ impl HostApi for PluginApi {
|
||||
}
|
||||
|
||||
fn vcs_remotes(&self, root: &Path) -> Result<Vec<(String, String)>, HostError> {
|
||||
if self.shared.workspace().is_some_and(|w| !w.git_enabled(root)) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let Some(repo) = ide_vcs::Repo::discover(root).map_err(failed)? else { return Ok(Vec::new()) };
|
||||
plugin_remotes(&repo)
|
||||
}
|
||||
@@ -4053,6 +4089,13 @@ impl PluginWorkspace for HostWorkspace {
|
||||
HostWorkspace::project_covering(self, root)?.git_executable()
|
||||
}
|
||||
|
||||
fn git_enabled(&self, root: &Path) -> bool {
|
||||
match HostWorkspace::project_covering(self, root) {
|
||||
Some(project) => project.git_enabled(),
|
||||
None => self.0.upgrade().is_none_or(|host| host.global_settings.read_effective(|s| s.vcs.git.enabled)),
|
||||
}
|
||||
}
|
||||
|
||||
fn project_of(&self, window: &str) -> Option<PathBuf> {
|
||||
self.0.upgrade()?.project(window).ok().map(|p| p.root.clone())
|
||||
}
|
||||
@@ -5144,6 +5187,9 @@ impl PluginApi {
|
||||
/// Status needs it there: a restricted repository is read without its config, so it knows
|
||||
/// no upstream. The other reads use [`Self::read_repo`] and never execute.
|
||||
fn repo(&self, root: &Path) -> Result<Option<ide_vcs::Repo>, HostError> {
|
||||
if self.shared.workspace().is_some_and(|w| !w.git_enabled(root)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let repo = ide_vcs::Repo::discover(root).map_err(failed)?;
|
||||
if let Some(repo) = &repo
|
||||
&& let Some(workspace) = self.shared.workspace()
|
||||
@@ -5158,6 +5204,9 @@ impl PluginApi {
|
||||
if !self.shared.workspace().is_some_and(|w| w.trusted(root)) {
|
||||
return Err(HostError::Failed("the project is in Restricted Mode: git does not run there".into()));
|
||||
}
|
||||
if self.shared.workspace().is_some_and(|w| !w.git_enabled(root)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let repo = ide_vcs::Repo::discover(root).map_err(failed)?;
|
||||
if let Some(repo) = &repo {
|
||||
repo.set_execution_allowed(false);
|
||||
|
||||
@@ -144,6 +144,24 @@ fn lookup_translation<'a>(catalog: &'a BTreeMap<String, String>, source: &str) -
|
||||
None
|
||||
}
|
||||
|
||||
/// Adds the plugin's own explanations (`[capabilities.reasons]`) to `capabilities`, with their
|
||||
/// translations from the package's `locales/<tag>.json`.
|
||||
pub fn explain_capabilities(capabilities: &mut [ide_extension::CapabilityInfo], pkg: &Package) {
|
||||
let reasons = &pkg.manifest.capabilities.reasons;
|
||||
if reasons.is_empty() {
|
||||
return;
|
||||
}
|
||||
let catalogs = read_locale_catalogs(pkg);
|
||||
for cap in capabilities.iter_mut() {
|
||||
let Some(reason) = reasons.get(&cap.id) else { continue };
|
||||
cap.reason_locales = catalogs
|
||||
.iter()
|
||||
.filter_map(|(tag, catalog)| Some((tag.clone(), lookup_translation(catalog, reason)?.to_owned())))
|
||||
.collect();
|
||||
cap.reason = Some(reason.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and validates a plugin package's Overview (`description` / `description-file`)
|
||||
/// and What's New (`change-notes` / `change-notes-file`), along with their
|
||||
/// per-locale translations from `locales/<tag>.json` and localized Markdown siblings.
|
||||
@@ -234,6 +252,32 @@ mod tests {
|
||||
assert!(docs.files.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_reasons_come_with_their_translations() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join("locales")).unwrap();
|
||||
std::fs::write(tmp.path().join("locales/zh-CN.json"), r#"{ "Imports a log you copied.": "导入复制的日志。" }"#)
|
||||
.unwrap();
|
||||
let src = "id = \"acme.docs\"\nname = \"Docs\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.19\"\n\
|
||||
[capabilities]\nrequired = [\"project.read\"]\noptional = [\"clipboard.read\"]\n\
|
||||
[capabilities.reasons]\n\"clipboard.read\" = \"Imports a log you copied.\"\n";
|
||||
let pkg = Package::new(Manifest::parse(src).unwrap(), tmp.path().to_path_buf());
|
||||
let m = &pkg.manifest;
|
||||
let mut caps: Vec<_> = m
|
||||
.capabilities
|
||||
.all()
|
||||
.map(|c| ide_extension::CapabilityInfo::new(c, m.capabilities.is_optional(c), false))
|
||||
.collect();
|
||||
explain_capabilities(&mut caps, &pkg);
|
||||
let clipboard = caps.iter().find(|c| c.id == "clipboard.read").unwrap();
|
||||
assert_eq!(clipboard.reason.as_deref(), Some("Imports a log you copied."));
|
||||
assert_eq!(clipboard.reason_locales.get("zh-CN").map(String::as_str), Some("导入复制的日志。"));
|
||||
// The host's own description stays.
|
||||
assert_eq!(clipboard.description, ide_extension::Capability::ClipboardRead.describe());
|
||||
let read = caps.iter().find(|c| c.id == "project.read").unwrap();
|
||||
assert_eq!((read.reason.as_deref(), read.reason_locales.len()), (None, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_files_and_localized_siblings_are_loaded_and_tracked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -66,7 +66,7 @@ mod websocket;
|
||||
|
||||
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use build_graph::{BuildGraph, GradleModule};
|
||||
pub use docs::{MAX_PLUGIN_DOC, PluginDocs, plugin_docs};
|
||||
pub use docs::{MAX_PLUGIN_DOC, PluginDocs, explain_capabilities, plugin_docs};
|
||||
pub(crate) use hover::merge as merge_hover;
|
||||
pub use icons::{
|
||||
MAX_PLUGIN_ICON, map_asset as icon_theme_map_asset, plugin_icon, sanitize_svg, svg_prefix as icon_theme_svg_prefix,
|
||||
@@ -950,6 +950,7 @@ impl PluginHost {
|
||||
}
|
||||
}
|
||||
annotate_java_agent_vm_options(&mut capabilities, m);
|
||||
explain_capabilities(&mut capabilities, &pkg);
|
||||
capabilities.sort_by(|a, b| b.risk.cmp(&a.risk).then(a.id.cmp(&b.id)));
|
||||
let signer_changed = self.signer_changed(&m.id, src);
|
||||
let answered = |c: &CapabilityInfo| {
|
||||
@@ -1811,7 +1812,12 @@ impl PluginHost {
|
||||
client.as_deref(),
|
||||
PluginEvent::ConsentRequested {
|
||||
plugin_id: id.to_owned(),
|
||||
capabilities: pending.iter().map(|c| CapabilityInfo::new(c, false, false)).collect(),
|
||||
capabilities: {
|
||||
let mut caps: Vec<CapabilityInfo> =
|
||||
pending.iter().map(|c| CapabilityInfo::new(c, false, false)).collect();
|
||||
explain_capabilities(&mut caps, &plugin.pkg);
|
||||
caps
|
||||
},
|
||||
},
|
||||
);
|
||||
return Err(IdeError::new(
|
||||
@@ -2765,13 +2771,12 @@ impl PluginHost {
|
||||
.map(|w| format!("{} is missing; build the plugin first", w.display())),
|
||||
};
|
||||
let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(&m));
|
||||
let mut capabilities: Vec<CapabilityInfo> =
|
||||
m.capabilities.all().map(|c| CapabilityInfo::new(c, m.capabilities.is_optional(c), false)).collect();
|
||||
explain_capabilities(&mut capabilities, &pkg);
|
||||
out.push(CatalogPlugin {
|
||||
has_code: m.wasm.is_some(),
|
||||
capabilities: m
|
||||
.capabilities
|
||||
.all()
|
||||
.map(|c| CapabilityInfo::new(c, m.capabilities.is_optional(c), false))
|
||||
.collect(),
|
||||
capabilities,
|
||||
contributions: counts(&m),
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
@@ -3557,6 +3562,7 @@ impl PluginHost {
|
||||
}
|
||||
}
|
||||
annotate_java_agent_vm_options(&mut capabilities, m);
|
||||
explain_capabilities(&mut capabilities, &p.pkg);
|
||||
// Hosts remembered through `net:ask` are grants of their own: listed
|
||||
// separately so the user can revoke them one by one.
|
||||
let net_hosts = grant
|
||||
|
||||
@@ -169,6 +169,7 @@ pub fn forwarded(event: &PluginEvent) -> bool {
|
||||
| PluginEvent::PromptClosed { .. }
|
||||
| PluginEvent::PromptWaiting { .. }
|
||||
| PluginEvent::RevealView { .. }
|
||||
| PluginEvent::OpenSettings { .. }
|
||||
| PluginEvent::CommitRequested { .. }
|
||||
| PluginEvent::ClipboardRequested { .. }
|
||||
| PluginEvent::EndpointsChanged { .. }
|
||||
|
||||
@@ -384,6 +384,10 @@ pub enum PluginEvent {
|
||||
/// Bring the tool window of the plugin's view `view` to the front.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
RevealView { plugin_id: String, view: String },
|
||||
/// Open Settings at the plugin's own page: its settings node (`page` none), the declared
|
||||
/// sub-page `page`, or (`permissions`) Settings › Plugins with its permissions in view.
|
||||
#[serde(rename_all = "camelCase")]
|
||||
OpenSettings { plugin_id: String, page: Option<String>, permissions: bool },
|
||||
/// A command needs the window's Commit view: answer with
|
||||
/// `plugin_answer_commit(request_id, …)`. Closed like a prompt (`PromptClosed`).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -1521,12 +1521,16 @@ mod tests {
|
||||
#[test]
|
||||
fn settings_pages_validate_manifest_files_commands_and_api() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/settings-pages");
|
||||
let source = std::fs::read_to_string(root.join("plugin.toml")).unwrap();
|
||||
let full = std::fs::read_to_string(root.join("plugin.toml")).unwrap();
|
||||
let check = |source: &str| {
|
||||
let manifest = ide_extension::Manifest::parse(source)?;
|
||||
let decl = manifest.declarations(SETTINGS).into_iter().next().unwrap();
|
||||
settings(&Package::new(manifest, root.clone()), decl)
|
||||
};
|
||||
check(&full).unwrap();
|
||||
// Pages need API 1.3: without the fixture's 1.19 `[capabilities]`, that is the gate.
|
||||
let (start, end) = (full.find("[capabilities]").unwrap(), full.find("[[contributes.commands]]").unwrap());
|
||||
let source = format!("{}{}", &full[..start], &full[end..]).replace("^1.19", "^1.3");
|
||||
let valid = check(&source).unwrap();
|
||||
assert_eq!(valid.json["pages"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(valid.json["properties"].as_array().unwrap().len(), 3);
|
||||
|
||||
@@ -765,6 +765,8 @@ impl Host {
|
||||
{
|
||||
let weak = Arc::downgrade(&project);
|
||||
project.agents.set_git_executable_hook(Arc::new(move || weak.upgrade()?.git_executable()));
|
||||
let weak = Arc::downgrade(&project);
|
||||
project.agents.set_git_enabled_hook(Arc::new(move || weak.upgrade().is_some_and(|p| p.git_enabled())));
|
||||
}
|
||||
self.insert_project(window, project.clone());
|
||||
for (key, text, dirty) in &carried {
|
||||
@@ -1134,6 +1136,10 @@ fn scan_repositories(
|
||||
/// The project-open scan and the watcher's rescan share these skip rules.
|
||||
fn discover_repositories(root: &Path, settings: &SettingsStore, build_cache: &Path, trusted: bool) -> IdeResult<Repos> {
|
||||
let settings = settings.effective();
|
||||
// Git integration off: the project has no repositories, so nothing runs git for it.
|
||||
if !settings.vcs.git.enabled {
|
||||
return Ok(Repos::default());
|
||||
}
|
||||
let found = detect_repositories(root, &settings, build_cache, trusted)?;
|
||||
let mappings = &settings.vcs.mappings;
|
||||
if mappings.is_empty() {
|
||||
@@ -1182,6 +1188,11 @@ impl Project {
|
||||
);
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Git › Enable Git integration (effective value).
|
||||
pub fn git_enabled(&self) -> bool {
|
||||
self.settings.read_effective(|s| s.vcs.git.enabled)
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Git › Path to Git executable, this project's value (its own
|
||||
/// layer over the global one); `None` when it is empty or the project is not trusted.
|
||||
/// Every git started for the project runs it: the project's repositories carry it, and work
|
||||
|
||||
@@ -3555,6 +3555,43 @@ fn settings_actions_choose_their_layer_without_losing_the_project() {
|
||||
}
|
||||
}
|
||||
|
||||
/// API 1.19: a plugin opens Settings at its own node, one of its declared pages or its
|
||||
/// permissions, in the invoking window; it can't name a page it doesn't declare. Its
|
||||
/// `[capabilities.reasons]` come with the permissions, translated.
|
||||
#[test]
|
||||
fn plugins_open_their_own_settings_and_explain_their_permissions() {
|
||||
let f = fixture(Limits::default());
|
||||
let info = f.install(&sample("settings-pages"));
|
||||
let net = info.capabilities.iter().find(|c| c.id == "net:api.example.com").unwrap();
|
||||
assert_eq!(net.reason.as_deref(), Some("Tests a model profile against the provider's API."));
|
||||
assert_eq!(net.reason_locales.get("zh-CN").map(String::as_str), Some("用服务商的 API 测试模型配置。"));
|
||||
assert!(net.description.contains("api.example.com"), "the host's description stays: {}", net.description);
|
||||
|
||||
let opened = |f: &Fixture| {
|
||||
f.take_events().into_iter().find_map(|(client, e)| match e {
|
||||
PluginEvent::OpenSettings { plugin_id, page, permissions } => Some((client, plugin_id, page, permissions)),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
f.take_events();
|
||||
let main = Some("main".to_owned());
|
||||
let id = "settings-pages".to_owned();
|
||||
f.run("settings-pages", "open-settings", None).unwrap();
|
||||
assert_eq!(opened(&f), Some((main.clone(), id.clone(), None, false)));
|
||||
f.run("settings-pages", "open-settings", Some("llm")).unwrap();
|
||||
assert_eq!(opened(&f), Some((main.clone(), id.clone(), Some("llm".into()), false)));
|
||||
f.run("settings-pages", "open-permissions", None).unwrap();
|
||||
assert_eq!(opened(&f), Some((main, id, None, true)));
|
||||
|
||||
let err = f.run("settings-pages", "open-settings", Some("Plugins")).unwrap_err();
|
||||
assert!(err.contains("declares no settings page"), "{err}");
|
||||
assert_eq!(opened(&f), None);
|
||||
// Without a window there is nowhere to open it.
|
||||
let no_window = Invocation { client: None, ..f.inv() };
|
||||
assert!(f.host.run_command("settings-pages", "open-permissions", None, no_window).is_err());
|
||||
assert_eq!(opened(&f), None);
|
||||
}
|
||||
|
||||
/// A tree filled from a pinned program's output, and a terminal for the
|
||||
/// activated entry in the invoking window, titled and sized by the plugin's
|
||||
/// settings (the `jobs` fixture).
|
||||
|
||||
@@ -19,6 +19,7 @@ use std::time::Duration;
|
||||
mod data;
|
||||
mod filter;
|
||||
mod matching;
|
||||
pub mod python_library;
|
||||
mod store;
|
||||
mod worker;
|
||||
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
//! Import candidates for a name from a Python interpreter's installed packages (PyCharm's
|
||||
//! "Import this name" for library symbols). basedpyright offers import fixes for the project's
|
||||
//! own symbols and the standard library only; this index covers `site-packages`.
|
||||
//!
|
||||
//! Every public module of the installed packages is read once: its `__all__`, else its public
|
||||
//! top-level definitions ([`Syntax::python_exports`]). Indexes are shared by every request for
|
||||
//! the same folders and rebuilt in the background when one of the folders changes: installing,
|
||||
//! upgrading or removing a package adds or removes entries there (its `.dist-info` at least).
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_language::Syntax;
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
use rayon::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
/// Modules read at most: a very large environment is indexed in part rather than for minutes.
|
||||
const MAX_MODULES: usize = 60_000;
|
||||
/// Package nesting below `site-packages` that is still walked.
|
||||
const MAX_DEPTH: usize = 8;
|
||||
/// Candidates returned for one name.
|
||||
const MAX_CANDIDATES: usize = 10;
|
||||
|
||||
/// An import that binds a name: `from module import name`, or `import module` without `name`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PythonImportCandidate {
|
||||
pub module: String,
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
/// The public names of the modules below some `site-packages` folders.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct PythonLibraryIndex {
|
||||
modules: Vec<String>,
|
||||
/// Name → the modules exporting it (indexes into `modules`).
|
||||
names: HashMap<String, Vec<u32>>,
|
||||
/// Importable top-level modules and packages.
|
||||
top_level: HashSet<String>,
|
||||
}
|
||||
|
||||
/// A module found on disk and the file its names are read from (none for an extension module
|
||||
/// without a stub).
|
||||
struct Source {
|
||||
module: String,
|
||||
file: Option<PathBuf>,
|
||||
/// A folder without `__init__` holding modules: `from google import protobuf`, not `import google`.
|
||||
namespace: bool,
|
||||
}
|
||||
|
||||
impl PythonLibraryIndex {
|
||||
/// Indexes the modules of `roots`, in `sys.path` order (the first folder holding a top-level
|
||||
/// name wins). None when `cancel` fired first.
|
||||
pub fn scan(roots: &[PathBuf], syntax: &Syntax, cancel: &CancellationToken) -> Option<Self> {
|
||||
let mut sources = Vec::new();
|
||||
let mut taken = HashSet::new();
|
||||
for root in roots {
|
||||
let mut found = Vec::new();
|
||||
walk(root, "", 0, &mut found, cancel);
|
||||
for source in found {
|
||||
let top = source.module.split('.').next().unwrap_or_default();
|
||||
// A package shadowed by an earlier folder is not importable from this one.
|
||||
if taken.contains(top) || sources.len() >= MAX_MODULES {
|
||||
continue;
|
||||
}
|
||||
sources.push(source);
|
||||
}
|
||||
// Namespace packages span folders (`google.protobuf` here, `google.api` there).
|
||||
taken.extend(sources.iter().filter(|s| !s.namespace && !s.module.contains('.')).map(|s| s.module.clone()));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
let exports: Vec<Vec<String>> = sources
|
||||
.par_iter()
|
||||
.map(|s| match &s.file {
|
||||
Some(file) if !cancel.is_cancelled() => std::fs::metadata(file)
|
||||
.ok()
|
||||
.filter(|m| m.len() <= crate::MAX_SYMBOL_FILE)
|
||||
.and_then(|_| std::fs::read_to_string(file).ok())
|
||||
.map(|text| syntax.python_exports(&text))
|
||||
.unwrap_or_default(),
|
||||
_ => Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
if cancel.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
let mut index = Self::default();
|
||||
let ids: HashMap<&str, u32> = sources.iter().enumerate().map(|(i, s)| (s.module.as_str(), i as u32)).collect();
|
||||
for (i, (source, names)) in sources.iter().zip(exports).enumerate() {
|
||||
let module = &source.module;
|
||||
index.modules.push(module.clone());
|
||||
for name in names {
|
||||
index.names.entry(name).or_default().push(i as u32);
|
||||
}
|
||||
match module.rsplit_once('.') {
|
||||
// `from matplotlib import pyplot`
|
||||
Some((parent, last)) => {
|
||||
if let Some(&parent) = ids.get(parent) {
|
||||
index.names.entry(last.to_owned()).or_default().push(parent);
|
||||
}
|
||||
}
|
||||
None if !source.namespace => {
|
||||
index.top_level.insert(module.clone());
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
for modules in index.names.values_mut() {
|
||||
modules.sort_unstable();
|
||||
modules.dedup();
|
||||
}
|
||||
Some(index)
|
||||
}
|
||||
|
||||
/// The imports that bind `name`: `import name` for a top-level module, then the modules that
|
||||
/// export it, the shortest module path first (a package re-exporting a name before the
|
||||
/// submodule defining it).
|
||||
pub fn candidates(&self, name: &str) -> Vec<PythonImportCandidate> {
|
||||
let mut out = Vec::new();
|
||||
if self.top_level.contains(name) {
|
||||
out.push(PythonImportCandidate { module: name.to_owned(), name: None });
|
||||
}
|
||||
let mut modules: Vec<&String> =
|
||||
self.names.get(name).into_iter().flatten().map(|&i| &self.modules[i as usize]).collect();
|
||||
let key = |m: &String| (m.matches('.').count(), m.len());
|
||||
modules.sort_by(|a, b| key(a).cmp(&key(b)).then_with(|| a.cmp(b)));
|
||||
out.extend(
|
||||
modules.into_iter().map(|m| PythonImportCandidate { module: m.clone(), name: Some(name.to_owned()) }),
|
||||
);
|
||||
out.truncate(MAX_CANDIDATES);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// A Python identifier that is not private (`_name`).
|
||||
fn public_identifier(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
chars.next().is_some_and(|c| c.is_alphabetic()) && chars.all(|c| c == '_' || c.is_alphanumeric())
|
||||
}
|
||||
|
||||
/// The public modules below `dir` (the package `prefix`, empty for a `site-packages` folder).
|
||||
fn walk(dir: &Path, prefix: &str, depth: usize, out: &mut Vec<Source>, cancel: &CancellationToken) {
|
||||
if depth > MAX_DEPTH || out.len() >= MAX_MODULES || cancel.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
// Module name → (`.py`, `.pyi`, extension module); packages → their folder.
|
||||
let mut files: BTreeMap<String, (Option<PathBuf>, Option<PathBuf>, bool)> = BTreeMap::new();
|
||||
let mut packages: BTreeMap<String, PathBuf> = BTreeMap::new();
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let file_name = entry.file_name().to_string_lossy().into_owned();
|
||||
if path.is_dir() {
|
||||
// `pkg-stubs` (PEP 561 stub-only package) holds the stubs of `pkg`.
|
||||
let name = if depth == 0 { file_name.strip_suffix("-stubs").unwrap_or(&file_name) } else { &file_name };
|
||||
if public_identifier(name) && !matches!(name, "test" | "tests") {
|
||||
let stubs = name.len() != file_name.len();
|
||||
// Stubs win over the package itself.
|
||||
if stubs || !packages.contains_key(name) {
|
||||
packages.insert(name.to_owned(), path);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (stem, kind) = if let Some(stem) = file_name.strip_suffix(".pyi") {
|
||||
(stem, 1)
|
||||
} else if let Some(stem) = file_name.strip_suffix(".py") {
|
||||
(stem, 0)
|
||||
} else if file_name.ends_with(".so") || file_name.ends_with(".pyd") {
|
||||
// `name.cpython-313-darwin.so`, `name.abi3.so`, `name.pyd`
|
||||
(file_name.split('.').next().unwrap_or_default(), 2)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if !public_identifier(stem) {
|
||||
continue;
|
||||
}
|
||||
let slot = files.entry(stem.to_owned()).or_default();
|
||||
match kind {
|
||||
0 => slot.0 = Some(path),
|
||||
1 => slot.1 = Some(path),
|
||||
_ => slot.2 = true,
|
||||
}
|
||||
}
|
||||
let qualified = |name: &str| if prefix.is_empty() { name.to_owned() } else { format!("{prefix}.{name}") };
|
||||
for (name, (py, pyi, extension)) in files {
|
||||
if out.len() >= MAX_MODULES {
|
||||
return;
|
||||
}
|
||||
if packages.contains_key(&name) {
|
||||
continue;
|
||||
}
|
||||
let file = pyi.or(py);
|
||||
if file.is_some() || extension {
|
||||
out.push(Source { module: qualified(&name), file, namespace: false });
|
||||
}
|
||||
}
|
||||
for (name, path) in packages {
|
||||
let init = ["__init__.pyi", "__init__.py"].iter().map(|f| path.join(f)).find(|p| p.is_file());
|
||||
let module = qualified(&name);
|
||||
let at = out.len();
|
||||
let package = init.is_some();
|
||||
out.push(Source { module: module.clone(), file: init, namespace: !package });
|
||||
walk(&path, &module, depth + 1, out, cancel);
|
||||
// A folder without `__init__` is a namespace package only when it holds modules.
|
||||
if !package && out.len() == at + 1 {
|
||||
out.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The indexes of every set of `site-packages` folders asked for, shared by all requests.
|
||||
#[derive(Default)]
|
||||
pub struct PythonLibraries {
|
||||
builds: Mutex<HashMap<Vec<PathBuf>, Arc<Build>>>,
|
||||
}
|
||||
|
||||
struct Build {
|
||||
/// Modification times of the folders when the build started.
|
||||
stamp: Vec<Option<SystemTime>>,
|
||||
/// None while building; then the index (None when it failed or was cancelled).
|
||||
result: Mutex<Option<Option<Arc<PythonLibraryIndex>>>>,
|
||||
done: Condvar,
|
||||
cancel: CancellationToken,
|
||||
}
|
||||
|
||||
impl Build {
|
||||
fn finish(&self, index: Option<PythonLibraryIndex>) {
|
||||
*self.result.lock() = Some(index.map(Arc::new));
|
||||
self.done.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks a build finished even when the indexing thread panics.
|
||||
struct Finish(Arc<Build>);
|
||||
|
||||
impl Drop for Finish {
|
||||
fn drop(&mut self) {
|
||||
if self.0.result.lock().is_none() {
|
||||
self.0.finish(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PythonLibraries {
|
||||
/// The index of `roots`. The first request, and the first after a folder changed, starts a
|
||||
/// build on its own thread; a request only waits for it, until `cancel` fires (None then).
|
||||
pub fn index(
|
||||
&self,
|
||||
roots: &[PathBuf],
|
||||
syntax: &Arc<Syntax>,
|
||||
cancel: &CancellationToken,
|
||||
) -> Option<Arc<PythonLibraryIndex>> {
|
||||
if roots.is_empty() {
|
||||
return Some(Arc::default());
|
||||
}
|
||||
let build = self.build(roots, syntax);
|
||||
let mut result = build.result.lock();
|
||||
loop {
|
||||
if let Some(index) = &*result {
|
||||
return index.clone();
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
build.done.wait_for(&mut result, Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
fn build(&self, roots: &[PathBuf], syntax: &Arc<Syntax>) -> Arc<Build> {
|
||||
let stamp = stamp(roots);
|
||||
let mut builds = self.builds.lock();
|
||||
if let Some(build) = builds.get(roots).filter(|b| b.stamp == stamp) {
|
||||
return build.clone();
|
||||
}
|
||||
let build =
|
||||
Arc::new(Build { stamp, result: Mutex::new(None), done: Condvar::new(), cancel: CancellationToken::new() });
|
||||
if let Some(old) = builds.insert(roots.to_vec(), build.clone()) {
|
||||
old.cancel.cancel();
|
||||
}
|
||||
let (job, roots, syntax) = (Finish(build.clone()), roots.to_vec(), syntax.clone());
|
||||
// When the thread cannot start, dropping `job` finishes the build without an index.
|
||||
let _ = std::thread::Builder::new().name("python-library-index".into()).spawn(move || {
|
||||
let index = PythonLibraryIndex::scan(&roots, &syntax, &job.0.cancel);
|
||||
job.0.finish(index);
|
||||
});
|
||||
build
|
||||
}
|
||||
}
|
||||
|
||||
fn stamp(roots: &[PathBuf]) -> Vec<Option<SystemTime>> {
|
||||
roots.iter().map(|r| std::fs::metadata(r).and_then(|m| m.modified()).ok()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn candidates(index: &PythonLibraryIndex, name: &str) -> Vec<String> {
|
||||
index
|
||||
.candidates(name)
|
||||
.into_iter()
|
||||
.map(|c| match c.name {
|
||||
Some(name) => format!("from {} import {name}", c.module),
|
||||
None => format!("import {}", c.module),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The shapes of the report: a name re-exported by a package's `__all__` from a submodule,
|
||||
/// and names defined in a public submodule only.
|
||||
fn site_packages() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(root, "langchain/__init__.py", "");
|
||||
write(
|
||||
root,
|
||||
"langchain/agents/__init__.py",
|
||||
"from langchain.agents.factory import create_agent\n__all__ = ['create_agent']\n",
|
||||
);
|
||||
write(root, "langchain/agents/factory.py", "def create_agent(): pass\ndef _private(): pass\n");
|
||||
write(root, "matplotlib/__init__.py", "def use(): pass\n");
|
||||
write(root, "matplotlib/figure.py", "class Figure: pass\nclass SubFigure: pass\n");
|
||||
write(root, "matplotlib/colors.py", "class Normalize: pass\n");
|
||||
write(root, "matplotlib/pyplot.py", "def figure(): pass\n");
|
||||
write(root, "matplotlib/_private_module.py", "class Hidden: pass\n");
|
||||
write(root, "matplotlib/tests/test_figure.py", "class Figure: pass\n");
|
||||
write(root, "numpy/__init__.pyi", "class ndarray: ...\n");
|
||||
write(root, "numpy/__init__.py", "class ndarray: pass\nclass only_in_source: pass\n");
|
||||
write(root, "six.py", "def add_metaclass(): pass\n");
|
||||
write(root, "_cffi_backend.cpython-313-darwin.so", "");
|
||||
write(root, "orjson.cpython-313-x86_64-linux-gnu.so", "");
|
||||
write(root, "requests-stubs/__init__.pyi", "def get(url: str) -> None: ...\n");
|
||||
write(root, "requests/__init__.py", "def get(url): pass\ndef untyped(): pass\n");
|
||||
write(root, "google/protobuf/__init__.py", "");
|
||||
write(root, "google/protobuf/message.py", "class Message: pass\n");
|
||||
write(root, "langchain-1.0.dist-info/METADATA", "");
|
||||
dir
|
||||
}
|
||||
|
||||
fn scan(roots: &[PathBuf]) -> PythonLibraryIndex {
|
||||
PythonLibraryIndex::scan(roots, &Syntax::new(), &CancellationToken::new()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexes_the_public_names_of_installed_modules() {
|
||||
let dir = site_packages();
|
||||
let index = scan(&[dir.path().to_path_buf()]);
|
||||
assert_eq!(
|
||||
candidates(&index, "create_agent"),
|
||||
["from langchain.agents import create_agent", "from langchain.agents.factory import create_agent"]
|
||||
);
|
||||
assert_eq!(candidates(&index, "Figure"), ["from matplotlib.figure import Figure"]);
|
||||
assert_eq!(candidates(&index, "Normalize"), ["from matplotlib.colors import Normalize"]);
|
||||
assert_eq!(candidates(&index, "pyplot"), ["from matplotlib import pyplot"]);
|
||||
assert_eq!(candidates(&index, "add_metaclass"), ["from six import add_metaclass"]);
|
||||
assert_eq!(candidates(&index, "Message"), ["from google.protobuf.message import Message"]);
|
||||
// Top-level modules and extension modules are imported as a whole.
|
||||
assert_eq!(candidates(&index, "matplotlib"), ["import matplotlib"]);
|
||||
assert_eq!(candidates(&index, "orjson"), ["import orjson"]);
|
||||
assert_eq!(candidates(&index, "six"), ["import six"]);
|
||||
// A namespace package is not offered; its subpackage is.
|
||||
assert_eq!(candidates(&index, "google"), Vec::<String>::new());
|
||||
assert_eq!(candidates(&index, "protobuf"), ["from google import protobuf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_out_private_and_test_modules_and_prefers_stubs() {
|
||||
let dir = site_packages();
|
||||
let index = scan(&[dir.path().to_path_buf()]);
|
||||
for hidden in ["_private", "Hidden", "_cffi_backend", "_private_module", "tests", "only_in_source", "untyped"] {
|
||||
assert_eq!(candidates(&index, hidden), Vec::<String>::new(), "{hidden}");
|
||||
}
|
||||
assert_eq!(candidates(&index, "ndarray"), ["from numpy import ndarray"]);
|
||||
assert_eq!(candidates(&index, "get"), ["from requests import get"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_earlier_folder_shadows_a_package_of_a_later_one() {
|
||||
let (first, second) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
write(first.path(), "pkg/__init__.py", "def new(): pass\n");
|
||||
write(second.path(), "pkg/__init__.py", "def old(): pass\n");
|
||||
write(second.path(), "other.py", "def thing(): pass\n");
|
||||
let index = scan(&[first.path().to_path_buf(), second.path().to_path_buf()]);
|
||||
assert_eq!(candidates(&index, "new"), ["from pkg import new"]);
|
||||
assert_eq!(candidates(&index, "old"), Vec::<String>::new());
|
||||
assert_eq!(candidates(&index, "thing"), ["from other import thing"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_scan_has_no_result() {
|
||||
let dir = site_packages();
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert!(PythonLibraryIndex::scan(&[dir.path().to_path_buf()], &Syntax::new(), &cancel).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_are_shared_and_redone_when_a_folder_changes() {
|
||||
let dir = site_packages();
|
||||
let roots = vec![dir.path().to_path_buf()];
|
||||
let (libraries, syntax, cancel) =
|
||||
(PythonLibraries::default(), Arc::new(Syntax::new()), CancellationToken::new());
|
||||
let first = libraries.index(&roots, &syntax, &cancel).unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &libraries.index(&roots, &syntax, &cancel).unwrap()));
|
||||
assert!(first.candidates("installed_later").is_empty());
|
||||
|
||||
// `pip install`: a new top-level entry changes the folder's modification time.
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
write(dir.path(), "newpkg/__init__.py", "def installed_later(): pass\n");
|
||||
// Coarse file system clocks may not move within the test; push it forward. Windows can't
|
||||
// open a directory as a plain file (it needs backup semantics), and NTFS keeps fine times.
|
||||
#[cfg(unix)]
|
||||
fs::File::open(dir.path()).unwrap().set_modified(SystemTime::now() + Duration::from_secs(5)).ok();
|
||||
let second = libraries.index(&roots, &syntax, &cancel).unwrap();
|
||||
assert!(!Arc::ptr_eq(&first, &second));
|
||||
assert_eq!(candidates(&second, "installed_later"), ["from newpkg import installed_later"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_request_stops_waiting() {
|
||||
let dir = site_packages();
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let libraries = PythonLibraries::default();
|
||||
// Either the build finished first or the request gave up; it never blocks.
|
||||
let _ = libraries.index(&[dir.path().to_path_buf()], &Arc::new(Syntax::new()), &cancel);
|
||||
assert!(libraries.index(&[], &Arc::new(Syntax::new()), &cancel).is_some());
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub(crate) mod lines;
|
||||
mod literals;
|
||||
mod outline;
|
||||
mod php_align;
|
||||
mod python_exports;
|
||||
mod python_facts;
|
||||
mod python_fixtures;
|
||||
mod python_imports;
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
//! The names a Python module offers to `from module import name`, for import suggestions of
|
||||
//! library symbols: its `__all__`, else its public top-level definitions.
|
||||
|
||||
use crate::{LanguageId, Syntax};
|
||||
use tree_sitter::{Node, Tree};
|
||||
|
||||
impl Syntax {
|
||||
/// The public names of a Python module `text`, sorted: the names its `__all__` lists, else its
|
||||
/// top-level functions, classes, assignments and type aliases, and the names it re-exports
|
||||
/// as `import a as a` / `from m import a as a` (the stub convention). Top-level `if` / `try`
|
||||
/// / `with` blocks count as top level. Names with a leading underscore are left out.
|
||||
pub fn python_exports(&self, text: &str) -> Vec<String> {
|
||||
self.analyze(&LanguageId::new("python"), text, |_, tree, text| Some(exports(tree, text))).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Exports {
|
||||
/// The literal names of `__all__`; None when the module has none.
|
||||
all: Option<Vec<String>>,
|
||||
/// `__all__` is also built from something other than literals (`other.__all__ + [...]`).
|
||||
dynamic: bool,
|
||||
defined: Vec<String>,
|
||||
}
|
||||
|
||||
fn exports(tree: &Tree, text: &str) -> Vec<String> {
|
||||
let mut found = Exports::default();
|
||||
found.block(tree.root_node(), text);
|
||||
let mut names = match found.all {
|
||||
Some(all) if found.dynamic => all.into_iter().chain(found.defined).collect(),
|
||||
Some(all) => all,
|
||||
None => found.defined,
|
||||
};
|
||||
names.retain(|n| is_public(n));
|
||||
names.sort();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
|
||||
impl Exports {
|
||||
fn block(&mut self, node: Node, text: &str) {
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
self.statement(child, text);
|
||||
}
|
||||
}
|
||||
|
||||
fn statement(&mut self, node: Node, text: &str) {
|
||||
match node.kind() {
|
||||
"function_definition" | "class_definition" | "type_alias_statement" => {
|
||||
if let Some(name) = node.child_by_field_name("name").filter(|n| n.kind() == "identifier") {
|
||||
self.defined.push(src(name, text).to_owned());
|
||||
} else if let Some(left) = node.child_by_field_name("left") {
|
||||
// `type X = ...`: the alias is the `left` type.
|
||||
self.defined.push(src(left, text).to_owned());
|
||||
}
|
||||
}
|
||||
"decorated_definition" => {
|
||||
if let Some(definition) = node.child_by_field_name("definition") {
|
||||
self.statement(definition, text);
|
||||
}
|
||||
}
|
||||
"expression_statement" => {
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
self.expression(child, text);
|
||||
}
|
||||
}
|
||||
"import_statement" | "import_from_statement" => self.reexports(node, text),
|
||||
"block" => self.block(node, text),
|
||||
"if_statement"
|
||||
| "elif_clause"
|
||||
| "else_clause"
|
||||
| "try_statement"
|
||||
| "except_clause"
|
||||
| "except_group_clause"
|
||||
| "finally_clause"
|
||||
| "with_statement" => {
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
if matches!(
|
||||
child.kind(),
|
||||
"block"
|
||||
| "elif_clause"
|
||||
| "else_clause"
|
||||
| "except_clause"
|
||||
| "except_group_clause"
|
||||
| "finally_clause"
|
||||
) {
|
||||
self.statement(child, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn expression(&mut self, node: Node, text: &str) {
|
||||
match node.kind() {
|
||||
"assignment" => {
|
||||
let (Some(left), right) = (node.child_by_field_name("left"), node.child_by_field_name("right")) else {
|
||||
return;
|
||||
};
|
||||
if src(left, text) == "__all__" {
|
||||
if let Some(right) = right {
|
||||
self.all = Some(Vec::new());
|
||||
self.extend_all(right, text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.targets(left, text);
|
||||
// `a = b = 1`
|
||||
if let Some(right) = right.filter(|r| r.kind() == "assignment") {
|
||||
self.expression(right, text);
|
||||
}
|
||||
}
|
||||
"augmented_assignment" => {
|
||||
let left = node.child_by_field_name("left");
|
||||
if left.is_some_and(|l| src(l, text) == "__all__")
|
||||
&& let Some(right) = node.child_by_field_name("right")
|
||||
{
|
||||
self.extend_all(right, text);
|
||||
}
|
||||
}
|
||||
// `__all__.extend([...])`, `__all__.append("name")`
|
||||
"call" => {
|
||||
let function = node.child_by_field_name("function").map(|f| src(f, text));
|
||||
if !matches!(function, Some("__all__.extend" | "__all__.append")) {
|
||||
return;
|
||||
}
|
||||
let Some(args) = node.child_by_field_name("arguments") else { return };
|
||||
let mut cursor = args.walk();
|
||||
for arg in args.named_children(&mut cursor) {
|
||||
self.extend_all(arg, text);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Names bound by an assignment target: `a`, `a, b`, `(a, b)`, `[a, b]`.
|
||||
fn targets(&mut self, node: Node, text: &str) {
|
||||
match node.kind() {
|
||||
"identifier" => self.defined.push(src(node, text).to_owned()),
|
||||
"pattern_list" | "tuple_pattern" | "list_pattern" => {
|
||||
let mut cursor = node.walk();
|
||||
for child in node.named_children(&mut cursor) {
|
||||
self.targets(child, text);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the string literals of `node` (a list, tuple, string or a `+` of them) to `__all__`.
|
||||
fn extend_all(&mut self, node: Node, text: &str) {
|
||||
let all = self.all.get_or_insert_with(Vec::new);
|
||||
match node.kind() {
|
||||
"string" => match string_value(node, text) {
|
||||
Some(name) => all.push(name),
|
||||
None => self.dynamic = true,
|
||||
},
|
||||
"list" | "tuple" | "parenthesized_expression" | "binary_operator" => {
|
||||
let mut cursor = node.walk();
|
||||
let children: Vec<Node> = node.named_children(&mut cursor).collect();
|
||||
for child in children {
|
||||
self.extend_all(child, text);
|
||||
}
|
||||
}
|
||||
_ => self.dynamic = true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `import a as a` and `from m import a as a`: re-exported in a stub, and by convention in a module.
|
||||
fn reexports(&mut self, node: Node, text: &str) {
|
||||
let mut cursor = node.walk();
|
||||
for item in node.children_by_field_name("name", &mut cursor) {
|
||||
if item.kind() != "aliased_import" {
|
||||
continue;
|
||||
}
|
||||
let (Some(name), Some(alias)) = (item.child_by_field_name("name"), item.child_by_field_name("alias"))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if src(name, text) == src(alias, text) {
|
||||
self.defined.push(src(alias, text).to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The content of a plain string literal; none for f-strings and strings with escapes.
|
||||
fn string_value(node: Node, text: &str) -> Option<String> {
|
||||
let mut cursor = node.walk();
|
||||
let parts: Vec<Node> = node.children(&mut cursor).collect();
|
||||
let start = parts.iter().find(|p| p.kind() == "string_start")?;
|
||||
let end = parts.iter().find(|p| p.kind() == "string_end")?;
|
||||
if src(*start, text).chars().any(|c| matches!(c, 'f' | 'F' | 'b' | 'B'))
|
||||
|| parts.iter().any(|p| matches!(p.kind(), "interpolation" | "escape_sequence"))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
text.get(start.end_byte()..end.start_byte()).map(str::to_owned)
|
||||
}
|
||||
|
||||
fn is_public(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
chars.next().is_some_and(|c| c.is_alphabetic()) && chars.all(|c| c == '_' || c.is_alphanumeric())
|
||||
}
|
||||
|
||||
fn src<'a>(node: Node, text: &'a str) -> &'a str {
|
||||
text.get(node.byte_range()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn exports(text: &str) -> Vec<String> {
|
||||
Syntax::new().python_exports(text)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_all_the_public_top_level_definitions() {
|
||||
let text = "\
|
||||
\"\"\"Docs.
|
||||
|
||||
Example = 1 inside a docstring
|
||||
\"\"\"
|
||||
import os
|
||||
from typing import Any
|
||||
from .colors import Normalize as Normalize
|
||||
import numpy as np
|
||||
|
||||
CONSTANT = 1
|
||||
_private = 2
|
||||
a, (b, _c) = 1, (2, 3)
|
||||
x = y = 0
|
||||
annotated: int = 3
|
||||
type Alias = int
|
||||
|
||||
def function(): pass
|
||||
async def coroutine(): pass
|
||||
|
||||
@decorator
|
||||
class Figure:
|
||||
nested = 1
|
||||
def method(self): pass
|
||||
|
||||
def _helper(): pass
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
def modern(): pass
|
||||
else:
|
||||
def legacy(): pass
|
||||
|
||||
try:
|
||||
from fast import speedup
|
||||
except ImportError:
|
||||
def speedup(): pass
|
||||
";
|
||||
assert_eq!(
|
||||
exports(text),
|
||||
[
|
||||
"Alias",
|
||||
"CONSTANT",
|
||||
"Figure",
|
||||
"Normalize",
|
||||
"a",
|
||||
"annotated",
|
||||
"b",
|
||||
"coroutine",
|
||||
"function",
|
||||
"legacy",
|
||||
"modern",
|
||||
"speedup",
|
||||
"x",
|
||||
"y"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_lists_the_exports() {
|
||||
// `langchain/agents/__init__.py`: the name is defined in a private submodule.
|
||||
let text = "\
|
||||
from langchain.agents.factory import create_agent
|
||||
from langchain.agents.middleware.types import AgentState
|
||||
|
||||
__all__ = [
|
||||
\"AgentState\",
|
||||
\"create_agent\",
|
||||
]
|
||||
def not_exported(): pass
|
||||
";
|
||||
assert_eq!(exports(text), ["AgentState", "create_agent"]);
|
||||
assert_eq!(
|
||||
exports("__all__ = ('a',)\n__all__ += ['b']\n__all__.extend(['c'])\n__all__.append('d')\n"),
|
||||
["a", "b", "c", "d"]
|
||||
);
|
||||
assert_eq!(exports("__all__ = ['a', '_b'] + ['c']\n"), ["a", "c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_computed_all_adds_the_definitions() {
|
||||
let text = "from .core import *\nfrom . import core\n__all__ = core.__all__ + ['extra']\ndef extra(): pass\ndef more(): pass\n";
|
||||
assert_eq!(exports(text), ["extra", "more"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_all_exports_nothing() {
|
||||
assert!(exports("__all__ = []\ndef hidden(): pass\n").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ mod wit_host;
|
||||
pub use actor::{Actor, ActorError, Pending};
|
||||
pub use runtime::{
|
||||
API_VERSION, CANCELLED, CallCancel, CallError, GuestError, HostApi, MAX_CLIPBOARD_BYTES, PluginEngine, Runtime,
|
||||
RuntimeSetup, check_api, component_api, host_api,
|
||||
RuntimeSetup, SettingsTarget, check_api, component_api, host_api,
|
||||
};
|
||||
pub use sandbox::{
|
||||
MAX_READ_BYTES, inside_root, inside_roots, read_text, resolve_in_root, resolve_in_roots, resolve_new_in_root,
|
||||
|
||||
@@ -64,7 +64,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
|
||||
use views_bindings::openidea::plugin::view_types as wit_vt;
|
||||
|
||||
/// The API version of the world above, `major.minor` of [`host_api`].
|
||||
pub const API_VERSION: &str = "1.18";
|
||||
pub const API_VERSION: &str = "1.19";
|
||||
const EPOCH_TICK: Duration = Duration::from_millis(10);
|
||||
pub(crate) const MAX_TEXT: usize = 1 << 20;
|
||||
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
|
||||
@@ -77,6 +77,15 @@ pub const CANCELLED: &str = "was cancelled";
|
||||
/// What plugin code may ask of the IDE, per plugin. Implemented by the host,
|
||||
/// which routes notifications and status items to windows and edits to open
|
||||
/// documents. Capabilities are already checked when these are called.
|
||||
/// Where `settings.open` / `settings.open-permissions` take the user.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum SettingsTarget {
|
||||
/// The plugin's settings node, or the declared sub-page with this id.
|
||||
Page(Option<String>),
|
||||
/// Settings › Plugins with the plugin's permissions in view.
|
||||
Permissions,
|
||||
}
|
||||
|
||||
pub trait HostApi: Send + Sync {
|
||||
/// Creates/replaces this plugin's non-secret project connection settings.
|
||||
fn database_upsert(&self, root: &Path, source: crate::PluginDataSource) -> Result<(), HostError>;
|
||||
@@ -267,6 +276,9 @@ pub trait HostApi: Send + Sync {
|
||||
) -> Result<Option<Vec<String>>, HostError>;
|
||||
/// Brings the plugin's declared view to the front in `client`'s window.
|
||||
fn reveal_view(&self, client: Option<&str>, view: &str) -> Result<(), HostError>;
|
||||
/// Opens Settings in `client`'s window at one of the plugin's own pages
|
||||
/// (`settings.open`, `settings.open-permissions`).
|
||||
fn open_settings(&self, client: Option<&str>, target: SettingsTarget) -> Result<(), HostError>;
|
||||
/// Whether this stable id is a command declared by this plugin.
|
||||
fn owns_command(&self, id: &str) -> bool;
|
||||
/// Executes a stable command in the invoking window and waits for its result.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! types and the implementation of every import. Capabilities are checked
|
||||
//! here; a missing one returns `error::denied` (the plugin can degrade).
|
||||
|
||||
use crate::runtime::{MAX_TITLE, StoreData, clip};
|
||||
use crate::runtime::{MAX_TITLE, SettingsTarget, StoreData, clip};
|
||||
use crate::sandbox;
|
||||
use crate::types::{
|
||||
EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, PickItem, ProcessChunk, ProcessCommand,
|
||||
@@ -2377,6 +2377,24 @@ impl settings::Host for StoreData {
|
||||
let root = if self.invocation.global_settings { None } else { self.invocation.workspace_root.clone() };
|
||||
Ok(self.host.setting(root.as_deref(), &clip(key, 128)))
|
||||
}
|
||||
|
||||
fn open(&mut self, page: Option<String>) -> Fallible<()> {
|
||||
self.open_settings(SettingsTarget::Page(page.map(|p| clip(p, 128))))
|
||||
}
|
||||
|
||||
fn open_permissions(&mut self) -> Fallible<()> {
|
||||
self.open_settings(SettingsTarget::Permissions)
|
||||
}
|
||||
}
|
||||
|
||||
impl StoreData {
|
||||
fn open_settings(&mut self, target: SettingsTarget) -> Fallible<()> {
|
||||
if let Err(e) = self.require_interactive() {
|
||||
return Ok(Err(e));
|
||||
}
|
||||
let client = self.invocation.client.clone();
|
||||
Ok(self.host.open_settings(client.as_deref(), target).map_err(to_wit))
|
||||
}
|
||||
}
|
||||
|
||||
impl views_bindings::openidea::plugin::view_types::Host for StoreData {}
|
||||
|
||||
@@ -98,7 +98,7 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.18.0");
|
||||
let host = v("1.19.0");
|
||||
for ok in [
|
||||
"1.0.0",
|
||||
"1.3.0",
|
||||
@@ -117,15 +117,16 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
"1.16.0",
|
||||
"1.17.0",
|
||||
"1.18.0",
|
||||
"1.19.0",
|
||||
"1.0.0-rc.1",
|
||||
] {
|
||||
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
|
||||
}
|
||||
let newer = check_api(&v("1.19.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.19") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
let newer = check_api(&v("1.20.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.20") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
|
||||
let older = check_api(&v("0.2.0"), &host).unwrap_err();
|
||||
assert!(older.contains("rebuild it with the 1.18 SDK"), "{older}");
|
||||
assert!(older.contains("rebuild it with the 1.19 SDK"), "{older}");
|
||||
// 0.x: every minor is its own API.
|
||||
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
|
||||
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
ba019d950ae83c45845a5cfcb2e890eca25c6f102b78f8cd3090f604c56aaf17
|
||||
1e6a4ba99409620e9bf3ceb51387704018737f186a89037b05bcbcee1e38a967
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
926ca24c9a08166e34fb8a6b2c6dd06a92cf3370dc01ff3054b533356314c84b
|
||||
667622767aa8c75a44c1348f6d07979ecb7a2db7ede9613999b61658a58557f5
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
dd7e4dcc429bf44b839cabe682f36cb3951a3dcf535f500f90cb60ff749e31e6
|
||||
689a9f36b9d13e0b57bd1540321a06da65837510fd9a37225776abd8baccfd7c
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
1acae0035935e9f6e7b52826e9731aeb15dafb5cfcc561a2b98dae10676f53f8
|
||||
0316df8c6f5fd4523f077c1a12d2d8af9592729a66a5a99a155dde42bb331e96
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
d3b940a7899ed3a303b51c529d2771ec9ac20a22d996dbc9760dd118dc10dbc1
|
||||
6732e125bfefcfad1c5712516e05bdaff7ceea4e71994de45109086e252e5f72
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
955e804453e7e8ea37a49ab7b65289d31fef1216eda4f1834e912375196adb17
|
||||
bb6c942f198534adf96354dd670c175f73954782f516762c564d157f5004b744
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
42caf6ccd73e3d622894416b0fd5007b8a1d773d6bf7e81c0ff4d0e97f888e43
|
||||
fa0957c9041bc31f7dc5b58aa912fa83851e6f0058d055e9582950195a1015b4
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
5795a3b4a25a7563c3a43ed0d414d3e520badd09066d5e5d2bcbc23ba4b8e1c8
|
||||
00ac40b08a5a39d4e011e9391732f19c20eb439a6f980b8d96334a5547c28666
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
1e53f7713c294be551fa4641cfda5b2497d7a57a35116ca4dd29783e63a7a9f6
|
||||
82473da5332e96dc9ef3a82947cde59b0a5d6acd49f8baad7c4fcc46ed4284dc
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
650a8e88e4e6999e77159fb25516b5990f6ae7805167e89a8e3193d53fd57822
|
||||
8532a968b8522e9b1b6f0df3aed073191e2a441ab960f96af79d7132fda4090a
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
3f5a85c4e3802a93b74513c1981b4202ad5bc70566a5cfcca7a1be2573a03f24
|
||||
ee0f3be61a8684275dc15acfdfe374b6d1751078d15c92608ba39ccbc6e10c67
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
61f41c0d8ce0bf2243c8cb3b2d2a84037a07958fb18d6ebb016abb08b469a80c
|
||||
4a3602e6024dcbeccb59ef9b324bab3e3254c908a7513c4f08bcbd212e368f9f
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
e5877e2978f8d36c1d8b684e84bfd21f9047b0153bed952e89299a69968029c0
|
||||
bd6aa162f07d96a580a8891433fd042e08a976f0f3ce4aee7694957ad394057c
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
7fe7457184144c93b761b8fa26e45f1b8a55cc6753d91a7353bd67d7a5bd09a9
|
||||
edac72326d401c873394ff0de9a659d5f3642259df136b87fb9b6cfe632e60c5
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
19480e0dd6ae1e36aadabbda9ea49a34ee0aa37d4c7182c297b6d84c9b13991f
|
||||
7454788469a0c0662987a4a774d8fc59b20b0dfec9bbac754e8e4aa0a46a1b43
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
7bd6651b0fd45032847868c341bc815b115ac678dcaaf26e752ae72ac1b0549f
|
||||
268b18f9303602b00f5c0d7254967aeb95c377b5a85011ead539b4ccab5811e2
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
9c99195f1c7efdb27f3715158559218db2f7db03325cc04af455b8f60653da24
|
||||
9e8809f276ef27561fe337f8268b3cf4f06be7ac1707a61e6e41407ec932bbb1
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
875df930f71fa22112dbafddb6de460b9828d0aa10812ee1eeedc4052bc88061
|
||||
c4594d365423395722e7f8e14f6d9c32ad4ff579b2eb42f5e2c5650e7cfa6bdc
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
d10b1225ab4228d3906e88e79ef346302a4db89aa4dd5a82da694cec408e5496
|
||||
91b267d3845bbd199662c0857ee23634a1d1b287204ce81fa148f1ce43eace3b
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
12cb92d4b45279bbdc345dbdd4c8d4827abc5054d0324d35b85b648840d9c556
|
||||
8e5c91ab272fa1678fbef9607f12513f7a589ef3fd293cfd7a52497cf637de3d
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
e8c1116c94c82ea4ed0fd7e33070bc878e88dcfe8f08632cd700bb3418b712cc
|
||||
a2e19194ba5f42e9d02d996c77444e8a5267fecc99bb02933f35aabb22fddadd
|
||||
Loaded 100 of 398 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача