mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-23 08:49:33 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d35a5e7d9 |
No files matched your search
Binary file not shown.
|
Before Width: | Height: | Size: 138 KiB After Width: | Height: | Size: 160 KiB |
@@ -102,44 +102,24 @@ jobs:
|
||||
name: Rust (${{ matrix.os }})
|
||||
needs: changes
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
permissions:
|
||||
contents: read
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-22.04, windows-latest]
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
|
||||
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- uses: taiki-e/install-action@nextest
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
|
||||
Generated
+2
-5
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.3"
|
||||
version = "0.18.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
|
||||
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
|
||||
dependencies = [
|
||||
"time",
|
||||
"version_check",
|
||||
@@ -4253,7 +4253,6 @@ dependencies = [
|
||||
name = "ide-core"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"libc",
|
||||
@@ -4847,7 +4846,6 @@ dependencies = [
|
||||
name = "ide-sdk"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"flate2",
|
||||
@@ -4859,7 +4857,6 @@ dependencies = [
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"specta",
|
||||
"tar",
|
||||
"tempfile",
|
||||
|
||||
+30
-49
@@ -38,7 +38,7 @@ pub use skill_installer::{
|
||||
};
|
||||
|
||||
use conversation::{Conversation, SavedSubagent, Session};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, error::ErrorKind};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use ide_vcs::Repo;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
@@ -95,8 +95,6 @@ const MAX_EMBED: u64 = 256 * 1024;
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// How long deleting a task waits for its agent to exit before removing the worktree.
|
||||
const EXIT_WAIT: Duration = Duration::from_secs(5);
|
||||
/// Change lists can each open several Git pipes; leave room for interactive VCS operations.
|
||||
const MAX_CHANGE_READS: usize = 4;
|
||||
|
||||
/// The agent tasks of one project.
|
||||
pub struct AgentManager {
|
||||
@@ -191,7 +189,6 @@ struct Shared {
|
||||
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
|
||||
workspace_roots: RwLock<Option<WorkspaceRootsHook>>,
|
||||
git_executable: RwLock<Option<GitExecutableHook>>,
|
||||
change_reads: Arc<tokio::sync::Semaphore>,
|
||||
known: Arc<Mutex<HashMap<String, Known>>>,
|
||||
providers: RwLock<Vec<provider::ProviderSpec>>,
|
||||
/// Last probe of each provider.
|
||||
@@ -607,7 +604,6 @@ impl AgentManager {
|
||||
new_task_approvals: RwLock::new(None),
|
||||
workspace_roots: RwLock::new(None),
|
||||
git_executable: RwLock::new(None),
|
||||
change_reads: Arc::new(tokio::sync::Semaphore::new(MAX_CHANGE_READS)),
|
||||
known,
|
||||
providers,
|
||||
probes: Mutex::new(HashMap::new()),
|
||||
@@ -1172,14 +1168,35 @@ impl AgentManager {
|
||||
|
||||
/// Drops a queued message.
|
||||
pub fn unqueue(&self, id: &str, queued: &str) -> IdeResult<AgentQueued> {
|
||||
self.task(id)?.take_queued(queued, false).map(|(item, _)| item)
|
||||
let task = self.task(id)?;
|
||||
let item = {
|
||||
let mut s = task.state.lock();
|
||||
let i =
|
||||
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
|
||||
s.task.queue.remove(i)
|
||||
};
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
Ok(item)
|
||||
}
|
||||
|
||||
/// Sends queued message `queued` now: into the running turn when the agent takes
|
||||
/// messages mid-turn, else next, cancelling the current turn if there is one.
|
||||
pub async fn send_queued_now(&self, id: &str, queued: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
let (item, busy) = task.take_queued(queued, true)?;
|
||||
let (item, busy) = {
|
||||
let mut s = task.state.lock();
|
||||
let i =
|
||||
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
|
||||
let item = s.task.queue.remove(i);
|
||||
let busy = s.busy;
|
||||
if !busy {
|
||||
s.busy = true;
|
||||
}
|
||||
(item, busy)
|
||||
};
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
if !busy {
|
||||
self.shared.runtime.spawn(async move { task.run(item.prompt).await });
|
||||
return Ok(());
|
||||
@@ -1830,7 +1847,7 @@ impl AgentManager {
|
||||
let task = self.task(id)?;
|
||||
let at = task.base();
|
||||
let (before, touched) = task.attribution();
|
||||
read_changes(&self.shared, move || at.changes(&before, touched.as_deref())).await
|
||||
vcs(&self.shared, move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await
|
||||
}
|
||||
|
||||
/// The task's uncommitted changes and, for a worktree task, the commits made since it
|
||||
@@ -1839,7 +1856,7 @@ impl AgentManager {
|
||||
let task = self.task(id)?;
|
||||
let at = task.base();
|
||||
let (before, touched) = task.attribution();
|
||||
read_changes(&self.shared, move || {
|
||||
vcs(&self.shared, move || {
|
||||
let mut grouped = at.grouped_changes(&before)?;
|
||||
grouped.uncommitted = worktree::made_by_task(grouped.uncommitted, touched.as_deref());
|
||||
Ok(grouped)
|
||||
@@ -1852,7 +1869,7 @@ impl AgentManager {
|
||||
pub async fn turn_changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, turn, dir) = self.task(id)?.last_turn();
|
||||
let Some(turn) = turn else { return Ok(Vec::new()) };
|
||||
read_changes(&self.shared, move || {
|
||||
vcs(&self.shared, move || {
|
||||
let changed = match &turn.changed {
|
||||
Some(changed) => changed.clone(),
|
||||
None => worktree::changed_in_turn(&cwd, &turn)?.1,
|
||||
@@ -1909,7 +1926,7 @@ impl AgentManager {
|
||||
let (restamped, restored) = vcs(&self.shared, move || {
|
||||
let (changes, rev) = match view {
|
||||
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
|
||||
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before, None)?, at.rev()?),
|
||||
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?),
|
||||
};
|
||||
let changes = worktree::made_by_task(changes, touched.as_deref());
|
||||
let sources = match rev.as_deref() {
|
||||
@@ -2324,23 +2341,6 @@ impl Task {
|
||||
self.shared.emit(AgentEvent::Task { task: Box::new(task) });
|
||||
}
|
||||
|
||||
/// Takes the item and, for Send now, claims an idle turn under the same lock.
|
||||
fn take_queued(&self, id: &str, for_send: bool) -> IdeResult<(AgentQueued, bool)> {
|
||||
let mut s = self.state.lock();
|
||||
let Some(index) = s.task.queue.iter().position(|item| item.id == id) else {
|
||||
drop(s);
|
||||
self.emit_task();
|
||||
return Err(IdeError::new(ErrorKind::OutOfSync, "Message is no longer queued"));
|
||||
};
|
||||
let item = s.task.queue.remove(index);
|
||||
let was_busy = s.busy;
|
||||
s.busy |= for_send;
|
||||
drop(s);
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
Ok((item, was_busy))
|
||||
}
|
||||
|
||||
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
|
||||
fn set_retry(&self, retry: Option<AgentRetry>) {
|
||||
{
|
||||
@@ -2549,10 +2549,7 @@ impl Task {
|
||||
self.push_entry(AgentEntry::Error { message: "The agent declined to continue.".into() });
|
||||
}
|
||||
match (next, result) {
|
||||
(Some(queued), _) => {
|
||||
self.emit_task();
|
||||
prompt = queued.prompt;
|
||||
}
|
||||
(Some(queued), _) => prompt = queued.prompt,
|
||||
(None, Ok(stop)) => {
|
||||
self.set_status(AgentStatus::Ready, None);
|
||||
if stop != "cancelled" {
|
||||
@@ -4234,11 +4231,8 @@ fn file_uri(path: &Path) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The title of a task: the first line of the prompt that says something. A pasted Markdown
|
||||
/// block opens with a code fence (```` ```text ````), which names no task.
|
||||
fn title_of(prompt: &AgentPrompt) -> String {
|
||||
let is_fence = |l: &str| l.starts_with("```") || l.starts_with("~~~");
|
||||
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty() && !is_fence(l));
|
||||
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty());
|
||||
let line = match line {
|
||||
Some(l) => l.to_owned(),
|
||||
None => prompt.files.first().map(|f| file_name(&f.0)).unwrap_or_else(|| "Image".into()),
|
||||
@@ -4276,19 +4270,6 @@ async fn vcs<T: Send + 'static>(shared: &Shared, f: impl FnOnce() -> IdeResult<T
|
||||
blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await
|
||||
}
|
||||
|
||||
async fn read_changes<T: Send + 'static>(
|
||||
shared: &Shared,
|
||||
f: impl FnOnce() -> IdeResult<T> + Send + 'static,
|
||||
) -> IdeResult<T> {
|
||||
let permit = shared.change_reads.clone().acquire_owned().await.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
vcs(shared, move || {
|
||||
// Dropping the caller doesn't cancel a blocking job. Keep the slot with the work.
|
||||
let _permit = permit;
|
||||
f()
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod replay;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -536,9 +536,6 @@ pub enum AgentEntry {
|
||||
kind: String,
|
||||
status: AgentToolStatus,
|
||||
locations: Vec<IpcPath>,
|
||||
/// Images returned by the tool, kept separately from its truncated text.
|
||||
#[serde(default)]
|
||||
images: Vec<AgentImage>,
|
||||
/// Text the tool reported (command output…), truncated.
|
||||
output: Option<String>,
|
||||
diffs: Vec<AgentToolDiff>,
|
||||
|
||||
@@ -1007,16 +1007,11 @@ impl Session {
|
||||
let mut updates = Vec::new();
|
||||
let mut finished = None;
|
||||
let mut read_title = false;
|
||||
let mut refresh_usage = false;
|
||||
{
|
||||
let mut st = self.st.lock();
|
||||
let st = &mut *st;
|
||||
match kind {
|
||||
"system" => match msg.get("subtype").and_then(Value::as_str) {
|
||||
Some("compact_boundary") => {
|
||||
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
|
||||
updates.extend(st.tr.on_message(&msg));
|
||||
}
|
||||
Some("init") => {
|
||||
st.terminal_only = strings(msg.get("terminal_slash_commands"));
|
||||
}
|
||||
@@ -1120,31 +1115,6 @@ impl Session {
|
||||
if read_title {
|
||||
self.read_title();
|
||||
}
|
||||
if refresh_usage {
|
||||
self.refresh_usage();
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
|
||||
/// counts it (`get_context_usage`); until then the meter would show the count from before.
|
||||
fn refresh_usage(self: &Arc<Self>) {
|
||||
let me = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let Some(proc) = me.st.lock().proc.clone() else { return };
|
||||
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
|
||||
Ok(usage) => usage,
|
||||
Err(e) => {
|
||||
tracing::debug!("reading claude context usage after compaction: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
|
||||
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
|
||||
let update = me.st.lock().tr.on_context_usage(used, size);
|
||||
if let Some(shim) = me.shim() {
|
||||
shim.notify(vec![update]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Sends the session's title once it has one: the one in its transcript, or else one
|
||||
|
||||
@@ -531,38 +531,6 @@ async fn sessions_without_a_title_get_one_generated() {
|
||||
assert_eq!(request["request"]["persist"], true);
|
||||
}
|
||||
|
||||
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
|
||||
/// driver asks Claude Code, and the meter shows that instead of the count from before.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
|
||||
let mut processes = load_fixture("simple");
|
||||
processes[0].extend([
|
||||
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
|
||||
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
|
||||
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
|
||||
"request": {"subtype": "get_context_usage"}})),
|
||||
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
|
||||
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
|
||||
]);
|
||||
let cli = replay_cli(processes);
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let session = h.new_session().await;
|
||||
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
|
||||
let mut usage = Vec::new();
|
||||
for _ in 0..100 {
|
||||
usage = h.updates(&session, "usage_update");
|
||||
if usage.last().is_some_and(|u| u["used"] == 4200) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
|
||||
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_multi_turn() {
|
||||
let r = replay("multi_turn").await;
|
||||
@@ -1130,24 +1098,6 @@ fn streamed_text_is_not_sent_twice() {
|
||||
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compaction_replaces_the_context_usage() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
|
||||
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
|
||||
t.on_message(&assistant);
|
||||
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 950);
|
||||
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
|
||||
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
|
||||
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
|
||||
// The `/compact` turn's result reports what compaction left, not the count from before.
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 120);
|
||||
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
|
||||
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
|
||||
assert!(t.on_result(&result).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limits_and_cost() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), false);
|
||||
|
||||
@@ -144,22 +144,6 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
|
||||
content.push(text(&t));
|
||||
}
|
||||
}
|
||||
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
|
||||
for block in blocks {
|
||||
if block.get("type").and_then(Value::as_str) != Some("image") {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = block.get("source") else { continue };
|
||||
if source.get("type").and_then(Value::as_str) != Some("base64") {
|
||||
continue;
|
||||
}
|
||||
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
|
||||
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
|
||||
if !data.is_empty() && mime.starts_with("image/") {
|
||||
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
|
||||
if !content.is_empty() {
|
||||
out["content"] = Value::Array(content);
|
||||
@@ -246,43 +230,6 @@ mod tests {
|
||||
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_tool_results_keep_text_and_inline_images() {
|
||||
let result = result_fields(
|
||||
"Read",
|
||||
&json!({"file_path": "/w/preview.png"}),
|
||||
&json!({"content": [
|
||||
{"type": "text", "text": "Preview ready"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
None,
|
||||
);
|
||||
assert_eq!(result["status"], "completed");
|
||||
assert_eq!(
|
||||
result["content"],
|
||||
json!([
|
||||
text("Preview ready"),
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_shell_tool_images_keep_fallback_error_text() {
|
||||
let result = result_fields(
|
||||
"Bash",
|
||||
&json!({}),
|
||||
&json!({"is_error": true, "content": [
|
||||
{"type": "text", "text": "Preview command failed"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
Some(&json!({"stdout": "", "stderr": ""})),
|
||||
);
|
||||
assert_eq!(result["status"], "failed");
|
||||
assert_eq!(result["content"][0], text("Preview command failed"));
|
||||
assert_eq!(result["content"][1]["content"]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results() {
|
||||
let input = json!({"file_path": "/w/n.txt", "content": "two"});
|
||||
|
||||
@@ -458,13 +458,6 @@ impl Translator {
|
||||
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
|
||||
self.finish_child(&tool_use, stop, last.or(summary))
|
||||
}
|
||||
// Compaction replaced the conversation with its summary: the context now holds
|
||||
// `post_tokens`. Without it the stale count must not come back with the result;
|
||||
// the driver asks Claude Code instead (`Session::refresh_usage`).
|
||||
Some("compact_boundary") => {
|
||||
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
|
||||
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
|
||||
Some("background_tasks_changed") => {
|
||||
@@ -568,16 +561,6 @@ impl Translator {
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
|
||||
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
|
||||
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
|
||||
self.used = Some(used);
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
if let Some(amount) = self.cost_usd {
|
||||
update["cost"] = json!({ "amount": amount, "currency": "USD" });
|
||||
}
|
||||
Update { session: self.root.clone(), update }
|
||||
}
|
||||
|
||||
fn usage_update(&self) -> Option<Update> {
|
||||
let used = self.used?;
|
||||
let size = self
|
||||
|
||||
@@ -452,57 +452,6 @@ fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
|
||||
manager_at(dir, &dir.join("models.json"), agent)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn change_reads_share_a_budget_until_the_blocking_work_finishes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::default());
|
||||
let submitted = Arc::new(AtomicU32::new(0));
|
||||
mgr.set_git_executable_hook(Arc::new({
|
||||
let submitted = submitted.clone();
|
||||
move || {
|
||||
submitted.fetch_add(1, Ordering::SeqCst);
|
||||
None
|
||||
}
|
||||
}));
|
||||
let (started, mut starts) = tokio::sync::mpsc::unbounded_channel();
|
||||
let (finished, mut finishes) = tokio::sync::mpsc::unbounded_channel();
|
||||
let mut releases = Vec::new();
|
||||
let mut reads = Vec::new();
|
||||
for job in 0..12 {
|
||||
let (release, gate) = tokio::sync::oneshot::channel::<()>();
|
||||
releases.push(release);
|
||||
let (started, finished) = (started.clone(), finished.clone());
|
||||
let mut read = Box::pin(read_changes(&mgr.shared, move || {
|
||||
started.send(()).unwrap();
|
||||
gate.blocking_recv().unwrap();
|
||||
finished.send(()).unwrap();
|
||||
Ok(())
|
||||
}));
|
||||
tokio::select! { biased; _ = &mut read => panic!("read finished before release"), _ = std::future::ready(()) => {} }
|
||||
reads.push(read);
|
||||
if job == 0 {
|
||||
// Cancelling the requester cannot stop the blocking job or free its slot.
|
||||
starts.recv().await.unwrap();
|
||||
drop(reads.pop());
|
||||
}
|
||||
}
|
||||
let admitted = submitted.load(Ordering::SeqCst);
|
||||
for _ in 1..admitted {
|
||||
starts.recv().await.unwrap();
|
||||
}
|
||||
for release in releases {
|
||||
release.send(()).unwrap();
|
||||
}
|
||||
for read in reads {
|
||||
read.await.unwrap();
|
||||
}
|
||||
for _ in 0..12 {
|
||||
finishes.recv().await.unwrap();
|
||||
}
|
||||
eprintln!("change-read fixture: peak active {admitted}; completed 12/12");
|
||||
assert_eq!(admitted, 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn subscribers_do_not_replace_or_close_each_other() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1426,46 +1375,6 @@ async fn steers_through_session_steering() {
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stale_queue_actions_refresh_the_queue_without_starting_another_turn() {
|
||||
use ide_core::error::ErrorKind;
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("ask"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let queued = handle.state.lock().task.queue[0].id.clone();
|
||||
let permission = *handle.permissions.lock().keys().next().unwrap();
|
||||
let (tx, mut updates) = tokio::sync::mpsc::unbounded_channel();
|
||||
let weak = Arc::downgrade(&handle);
|
||||
mgr.subscribe(Arc::new(move |event| {
|
||||
if let AgentEvent::Task { task } = event
|
||||
&& task.queue.is_empty()
|
||||
&& let Some(handle) = weak.upgrade()
|
||||
{
|
||||
let _ = tx.send(handle.turns.load(Ordering::Acquire));
|
||||
}
|
||||
}));
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(updates.try_recv().unwrap(), 1, "publish the dequeue before starting the second turn");
|
||||
while updates.try_recv().is_ok() {}
|
||||
|
||||
for error in
|
||||
[mgr.unqueue(&task.id, &queued).unwrap_err(), mgr.send_queued_now(&task.id, &queued).await.unwrap_err()]
|
||||
{
|
||||
assert_eq!(error.kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(updates.try_recv().unwrap(), 2, "a stale action gets the current queue");
|
||||
}
|
||||
assert!(!handle.state.lock().busy);
|
||||
assert_eq!(mgr.unqueue("missing-task", &queued).unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1731,8 +1640,6 @@ fn prompts_become_acp_content_blocks() {
|
||||
assert_eq!(old["entries"][0]["attachments"], json!([]));
|
||||
assert!(old["entries"][1].get("attachments").is_none());
|
||||
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
|
||||
let pasted = AgentPrompt { text: "```text\n\n ## Fix the tab title\n```".into(), ..AgentPrompt::default() };
|
||||
assert_eq!(title_of(&pasted), "## Fix the tab title");
|
||||
assert!(clean(text(" ")).is_none());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Folds ACP `session/update` notifications into a task's entries.
|
||||
|
||||
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
@@ -84,7 +84,6 @@ impl Timeline {
|
||||
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
|
||||
locations: locations(update.get("locations")),
|
||||
output: None,
|
||||
images: Vec::new(),
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
@@ -151,7 +150,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -174,20 +173,10 @@ impl Timeline {
|
||||
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
let mut new_images = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
let content = item.get("content");
|
||||
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
|
||||
&& let (Some(data), Some(mime)) =
|
||||
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
|
||||
&& !data.is_empty()
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
}
|
||||
if let Some(t) = content_text(content) {
|
||||
if let Some(t) = content_text(item.get("content")) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
@@ -214,9 +203,6 @@ impl Timeline {
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
|
||||
@@ -453,31 +439,6 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
|
||||
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("images");
|
||||
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
|
||||
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
|
||||
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
|
||||
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
|
||||
]});
|
||||
t.apply(&update);
|
||||
t.apply(&update);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
|
||||
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
|
||||
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
let saved = serde_json::to_string(&t.entries[0]).unwrap();
|
||||
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_merge_into_one_message_until_another_entry_comes() {
|
||||
let mut t = Timeline::default();
|
||||
|
||||
@@ -65,7 +65,7 @@ impl TurnRepos {
|
||||
|
||||
/// The innermost repository holding `path`.
|
||||
fn owner(&self, path: &Path) -> Option<&Repo> {
|
||||
owning_repo(&self.repos, path)
|
||||
self.repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
|
||||
}
|
||||
|
||||
/// `repo`'s `HEAD` as the turn `start` began.
|
||||
@@ -78,10 +78,6 @@ fn root_key(root: &Path) -> String {
|
||||
root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn owning_repo<'a>(repos: &'a [Repo], path: &Path) -> Option<&'a Repo> {
|
||||
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
|
||||
}
|
||||
|
||||
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
|
||||
/// one lists it itself; to `repo` its folder is untracked).
|
||||
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
|
||||
@@ -95,25 +91,11 @@ fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Optio
|
||||
}
|
||||
|
||||
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
|
||||
fn nested_changes(base: &Path, repos: &[Repo], touched: Option<&BTreeSet<String>>) -> IdeResult<Vec<AgentChange>> {
|
||||
fn nested_changes(cwd: &Path) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some((base, repos)) = nested_repos(cwd)? else { return Ok(Vec::new()) };
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
// Match deletions too: find the owner by path components, not by opening the file.
|
||||
// Display paths use slash separators and lossy Unicode (see nested_rel). If a checkout's
|
||||
// name cannot round-trip from that representation, keep the full-read fallback.
|
||||
let owners = touched
|
||||
.filter(|_| {
|
||||
roots.iter().all(|root| {
|
||||
root.strip_prefix(base).is_ok_and(|rel| base.join(rel.to_string_lossy().replace('\\', "/")) == *root)
|
||||
})
|
||||
})
|
||||
.map(|paths| {
|
||||
paths.iter().filter_map(|rel| owning_repo(repos, &base.join(rel)).map(Repo::root)).collect::<BTreeSet<_>>()
|
||||
});
|
||||
let mut out: Vec<AgentChange> = Vec::new();
|
||||
for repo in repos {
|
||||
if owners.as_ref().is_some_and(|owners| !owners.contains(repo.root())) {
|
||||
continue;
|
||||
}
|
||||
for repo in &repos {
|
||||
let listed = match repo.head()?.1 {
|
||||
Some(head) => changes(repo.root(), &head)?,
|
||||
None => {
|
||||
@@ -121,7 +103,7 @@ fn nested_changes(base: &Path, repos: &[Repo], touched: Option<&BTreeSet<String>
|
||||
}
|
||||
};
|
||||
for mut c in listed {
|
||||
let Some(rel) = nested_rel(base, repo, &roots, &c.path.0) else { continue };
|
||||
let Some(rel) = nested_rel(&base, repo, &roots, &c.path.0) else { continue };
|
||||
if out.iter().any(|o| o.path == c.path) {
|
||||
continue;
|
||||
}
|
||||
@@ -382,30 +364,13 @@ impl TaskBase {
|
||||
}
|
||||
|
||||
/// The files the task changed, less those changed before it started and untouched since.
|
||||
pub(crate) fn changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
if touched.is_some_and(BTreeSet::is_empty) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(made_by_task(self.read_changes(before, touched)?, touched))
|
||||
}
|
||||
|
||||
fn read_changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
|
||||
Self::Local { cwd, start } => {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(without_untouched(nested_changes(&base, &repos, touched)?, before));
|
||||
}
|
||||
(cwd, start.as_deref())
|
||||
Self::Local { cwd, .. } if spans_repos(cwd) => {
|
||||
return Ok(without_untouched(nested_changes(cwd)?, before));
|
||||
}
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
// What is uncommitted, as the Commit tool window lists it: commits made since the task
|
||||
@@ -464,7 +429,7 @@ impl TaskBase {
|
||||
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
|
||||
let cwd = self.cwd();
|
||||
if spans_repos(cwd) {
|
||||
return Ok(AgentChanges { uncommitted: self.changes(before, None)?, commits: Vec::new() });
|
||||
return Ok(AgentChanges { uncommitted: self.changes(before)?, commits: Vec::new() });
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
|
||||
let head = repo.head()?.1;
|
||||
@@ -1157,57 +1122,6 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn attributed_changes_only_diff_the_owning_checkout() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
for n in 0..15 {
|
||||
let repo = root.join(format!("repo{n:02}"));
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(&repo, &["add", "a.txt"]);
|
||||
git(&repo, &["commit", "-q", "-m", "initial"]);
|
||||
std::fs::write(repo.join("a.txt"), "two\n").unwrap();
|
||||
}
|
||||
// Count real Git diff processes, not walks to discover the topology.
|
||||
let git = tmp.path().join("count-git");
|
||||
let log = tmp.path().join("count-git.log");
|
||||
std::fs::write(
|
||||
&git,
|
||||
"#!/bin/sh\nfor arg do\nif [ \"$arg\" = diff ]; then pwd >> \"$0.log\"; break; fi\ndone\nexec git \"$@\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&git, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let at = TaskBase::Local { cwd: root, start: None };
|
||||
let before = BTreeMap::new();
|
||||
let one = BTreeSet::from(["repo07/a.txt".to_owned()]);
|
||||
let read = |touched: Option<&BTreeSet<String>>| {
|
||||
std::fs::write(&log, "").unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let changes = ide_vcs::with_git_executable(Some(&git), || at.changes(&before, touched).unwrap());
|
||||
let elapsed = start.elapsed();
|
||||
let calls = std::fs::read_to_string(&log).unwrap();
|
||||
eprintln!("change read: touched={:?} elapsed={elapsed:?}", touched.map(BTreeSet::len));
|
||||
(changes, calls.lines().count())
|
||||
};
|
||||
let (all, full_calls) = read(None);
|
||||
let (selected, selected_calls) = read(Some(&one));
|
||||
let (empty, empty_calls) = read(Some(&BTreeSet::new()));
|
||||
assert_eq!(all.len(), 15);
|
||||
assert_eq!(
|
||||
serde_json::to_value(selected).unwrap(),
|
||||
serde_json::to_value(made_by_task(all, Some(&one))).unwrap()
|
||||
);
|
||||
assert!(empty.is_empty());
|
||||
eprintln!("git diff children: full {full_calls}, one touched {selected_calls}, none touched {empty_calls}");
|
||||
assert!(selected_calls > 0);
|
||||
assert_eq!(selected_calls * 15, full_calls);
|
||||
assert_eq!(empty_calls, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1230,7 +1144,7 @@ mod tests {
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
|
||||
let at = TaskBase::Local { cwd: root.clone(), start: None };
|
||||
let changed = at.changes(&before, None).unwrap();
|
||||
let changed = at.changes(&before).unwrap();
|
||||
let listed: Vec<(&str, &Path)> =
|
||||
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
|
||||
assert_eq!(
|
||||
@@ -1254,12 +1168,6 @@ mod tests {
|
||||
}
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert!(root.join("mine.txt").exists(), "the user's own change stays");
|
||||
// A deleted file cannot be canonicalized, but still belongs to its innermost repo.
|
||||
std::fs::remove_file(deeper.join("a.txt")).unwrap();
|
||||
let removed = at.changes(&before, Some(&BTreeSet::from(["libs/validation/pkg/sdk/a.txt".into()]))).unwrap();
|
||||
assert_eq!(removed.len(), 1);
|
||||
assert_eq!(removed[0].repo.as_ref().unwrap().0, deeper);
|
||||
assert_eq!(removed[0].kind, ChangeKind::Deleted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -17,4 +17,6 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
dirs.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -1008,7 +1008,12 @@ pub fn build_for_launches(
|
||||
if plan.system == BuildSystem::Maven
|
||||
&& let Some(m) = &model.maven
|
||||
{
|
||||
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
|
||||
maven_launch_projects(root, m, module, test)
|
||||
.iter()
|
||||
.flat_map(|p| {
|
||||
launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
launch_class_dirs(plan.system, module, test)
|
||||
}
|
||||
@@ -1016,60 +1021,6 @@ pub fn build_for_launches(
|
||||
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect())
|
||||
}
|
||||
|
||||
/// Maven output directories for a launch, including directories that have yet to be created.
|
||||
pub fn maven_launch_output_dirs(root: &Path, model: &maven::MavenModel, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
maven_launch_projects(root, model, module, test)
|
||||
.into_iter()
|
||||
.flat_map(|p| {
|
||||
let dir = subdir(root, &p.dir);
|
||||
maven_output_dirs(&dir, test && dir == module)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The class directories of a Maven launch that must hold classes after its build: those of
|
||||
/// the launch projects with sources in a conventional JVM source root. One that is missing
|
||||
/// or holds no class was caught mid-rewrite, e.g. cleaned by a concurrent `mvn` (#5404).
|
||||
pub fn launch_required_class_dirs(root: &Path, model: &BuildModel, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
fn has_sources(dir: &Path, depth: u32) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|e| {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
depth > 0 && has_sources(&p, depth - 1)
|
||||
} else {
|
||||
// A package-info.java without annotations compiles to nothing.
|
||||
p.file_name() != Some("package-info.java".as_ref())
|
||||
&& p.extension().is_some_and(|x| x == "java" || x == "kt" || x == "groovy" || x == "scala")
|
||||
}
|
||||
})
|
||||
}
|
||||
let compiles = |dir: &Path, set: &str| {
|
||||
["java", "kotlin", "groovy", "scala"].iter().any(|lang| has_sources(&dir.join("src").join(set).join(lang), 32))
|
||||
};
|
||||
let Some(m) = &model.maven else { return Vec::new() };
|
||||
let mut dirs = Vec::new();
|
||||
for p in maven_launch_projects(root, m, module, test) {
|
||||
let dir = subdir(root, &p.dir);
|
||||
if test && dir == module && compiles(&dir, "test") {
|
||||
dirs.push(subdir(&dir, "target/test-classes"));
|
||||
}
|
||||
if compiles(&dir, "main") {
|
||||
dirs.push(subdir(&dir, "target/classes"));
|
||||
}
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
fn maven_output_dirs(module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
if test {
|
||||
dirs.push(subdir(module, "target/test-classes"));
|
||||
}
|
||||
dirs.push(subdir(module, "target/classes"));
|
||||
dirs
|
||||
}
|
||||
|
||||
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
let sets: &[&str] = if test { &["test", "main"] } else { &["main"] };
|
||||
let dirs: Vec<PathBuf> = match system {
|
||||
@@ -1080,7 +1031,8 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
|
||||
.map(|d| subdir(module, &format!("build/{d}/{s}")))
|
||||
})
|
||||
.collect(),
|
||||
BuildSystem::Maven => maven_output_dirs(module, test),
|
||||
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
|
||||
BuildSystem::Maven => vec![subdir(module, "target/classes")],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
dirs.into_iter().filter(|d| d.is_dir()).collect()
|
||||
|
||||
@@ -3,13 +3,7 @@
|
||||
use super::MavenProject;
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
|
||||
const SOURCE_REFRESH_WORKERS: usize = 4;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Artifact {
|
||||
@@ -17,29 +11,6 @@ pub struct Artifact {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub sources: PathBuf,
|
||||
binary: PathBuf,
|
||||
}
|
||||
|
||||
fn valid_part(part: &str) -> bool {
|
||||
!part.is_empty()
|
||||
&& part != "."
|
||||
&& part != ".."
|
||||
&& part.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
|
||||
}
|
||||
|
||||
fn modified_file(path: &Path) -> Option<SystemTime> {
|
||||
let metadata = fs::metadata(path).ok()?;
|
||||
if metadata.is_file() { metadata.modified().ok() } else { None }
|
||||
}
|
||||
|
||||
impl Artifact {
|
||||
fn stale_binary(&self) -> Option<SystemTime> {
|
||||
if !self.version.ends_with("-SNAPSHOT") {
|
||||
return None;
|
||||
}
|
||||
let binary = modified_file(&self.binary)?;
|
||||
(modified_file(&self.sources)? < binary).then_some(binary)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve only jars inside the selected local repository, including custom repositories.
|
||||
@@ -57,14 +28,16 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
}
|
||||
let n = parts.len();
|
||||
let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]);
|
||||
if !parts[..n - 1].iter().all(|s| valid_part(s)) || file != format!("{name}-{version}.jar") {
|
||||
let valid = |s: &str| {
|
||||
!s.is_empty() && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
|
||||
};
|
||||
if !parts[..n - 1].iter().all(|s| valid(s)) || file != format!("{name}-{version}.jar") {
|
||||
return None;
|
||||
}
|
||||
Some(Artifact {
|
||||
group: parts[..n - 3].join("."),
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
binary: jar.to_owned(),
|
||||
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
|
||||
})
|
||||
}
|
||||
@@ -75,58 +48,26 @@ pub fn download(
|
||||
artifact: &Artifact,
|
||||
repository: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
resolve(root, project, artifact, repository, &[], artifact.stale_binary(), cancel)
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
root: &Path,
|
||||
project: &MavenProject,
|
||||
artifact: &Artifact,
|
||||
repository: &Path,
|
||||
profile_args: &[String],
|
||||
stale: Option<SystemTime>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if stale.is_none() && artifact.sources.is_file() {
|
||||
if artifact.sources.is_file() {
|
||||
return Ok(Some(artifact.sources.clone()));
|
||||
}
|
||||
let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()];
|
||||
args.extend(project.options.iter().cloned());
|
||||
args.extend(profile_args.iter().cloned());
|
||||
args.push(format!("-Dmaven.repo.local={}", repository.display()));
|
||||
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
|
||||
let stage = if let Some(binary) = stale {
|
||||
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
|
||||
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
|
||||
let stage =
|
||||
tempfile::Builder::new().prefix(".openidea-sources-").tempdir_in(artifact.sources.parent().unwrap())?;
|
||||
args.extend([
|
||||
"-U".into(),
|
||||
"-Daether.artifactResolver.snapshotNormalization=false".into(),
|
||||
format!("{DEPENDENCY_PLUGIN}:copy"),
|
||||
coordinate,
|
||||
"-Dmdep.useBaseVersion=true".into(),
|
||||
format!("-DoutputDirectory={}", stage.path().display()),
|
||||
]);
|
||||
Some((stage, binary))
|
||||
} else {
|
||||
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
None
|
||||
};
|
||||
args.extend(project.options.clone());
|
||||
args.extend([
|
||||
format!("-Dmaven.repo.local={}", repository.display()),
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(),
|
||||
format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version),
|
||||
"-Dtransitive=false".into(),
|
||||
]);
|
||||
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if let Some((stage, binary)) = stage {
|
||||
let resolved = stage.path().join(artifact.sources.file_name().unwrap());
|
||||
if output.success && resolved.is_file() {
|
||||
return replace_stale_sources(artifact, &resolved, binary, cancel);
|
||||
}
|
||||
} else if artifact.sources.is_file() {
|
||||
if artifact.sources.is_file() {
|
||||
return Ok(Some(artifact.sources.clone()));
|
||||
}
|
||||
let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version);
|
||||
@@ -142,115 +83,6 @@ fn resolve(
|
||||
))
|
||||
}
|
||||
|
||||
fn replace_stale_sources(
|
||||
artifact: &Artifact,
|
||||
resolved: &Path,
|
||||
binary: SystemTime,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
// Maven can fall back to a locally installed snapshot. Keep its timestamp if it returned
|
||||
// the same bytes so a later reload can retry when newer sources are available.
|
||||
let hash = |path| -> std::io::Result<_> { Ok(blake3::Hasher::new().update_reader(File::open(path)?)?.finalize()) };
|
||||
if hash(resolved)? == hash(&artifact.sources)? {
|
||||
return Ok(None);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match artifact.stale_binary() {
|
||||
Some(current) if current == binary => {
|
||||
File::options().write(true).open(resolved)?.set_modified(SystemTime::now().max(binary))?;
|
||||
fs::rename(resolved, &artifact.sources)?;
|
||||
Ok(Some(artifact.sources.clone()))
|
||||
}
|
||||
None if artifact.sources.is_file() => Ok(Some(artifact.sources.clone())),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolved Maven dependencies with an existing attachment. Binaries may still be
|
||||
/// updating during import, so freshness is checked when the refresh runs.
|
||||
pub fn cached_snapshots<'a>(
|
||||
repository: &Path,
|
||||
projects: impl Iterator<Item = (usize, &'a MavenProject)>,
|
||||
) -> Vec<(usize, Artifact)> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut candidates = Vec::new();
|
||||
for (owner, project) in projects {
|
||||
let mut dependencies: Vec<_> = project.dependencies.iter().collect();
|
||||
while let Some(dep) = dependencies.pop() {
|
||||
if !dep.resolved() {
|
||||
continue;
|
||||
}
|
||||
dependencies.extend(&dep.children);
|
||||
let Some(version) = dep.version.as_deref().filter(|v| v.ends_with("-SNAPSHOT") && valid_part(v)) else {
|
||||
continue;
|
||||
};
|
||||
if dep.scope == "system"
|
||||
|| dep.classifier.is_some()
|
||||
|| !matches!(dep.kind.as_str(), "jar" | "bundle" | "maven-plugin" | "ejb")
|
||||
|| !valid_part(&dep.artifact_id)
|
||||
|| !dep.group_id.split('.').all(valid_part)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let name = &dep.artifact_id;
|
||||
let jar = repository
|
||||
.join(dep.group_id.replace('.', "/"))
|
||||
.join(name)
|
||||
.join(version)
|
||||
.join(format!("{name}-{version}.jar"));
|
||||
if let Some(artifact) = artifact(&jar, repository)
|
||||
&& artifact.sources.is_file()
|
||||
&& seen.insert(jar)
|
||||
{
|
||||
candidates.push((owner, artifact));
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
/// Refresh only previously attached snapshots. Maven subprocesses are bounded
|
||||
/// and share the build reload's cancellation token.
|
||||
pub fn refresh_snapshots(
|
||||
root: &Path,
|
||||
projects: &[MavenProject],
|
||||
repository: &Path,
|
||||
candidates: &[(usize, Artifact)],
|
||||
profiles: &[String],
|
||||
cancel: &CancellationToken,
|
||||
) -> Vec<PathBuf> {
|
||||
let profile_args = if profiles.is_empty() { vec![] } else { vec![format!("-P{}", profiles.join(","))] };
|
||||
let profile_args = &profile_args;
|
||||
let stale: Vec<_> = candidates.iter().filter(|(_, artifact)| artifact.stale_binary().is_some()).collect();
|
||||
let batch_size = stale.len().div_ceil(SOURCE_REFRESH_WORKERS).max(1);
|
||||
std::thread::scope(|scope| {
|
||||
let workers: Vec<_> = stale
|
||||
.chunks(batch_size)
|
||||
.map(|batch| {
|
||||
scope.spawn(move || {
|
||||
let mut refreshed = Vec::new();
|
||||
for (owner, artifact) in batch.iter().copied() {
|
||||
if cancel.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let Some(binary) = artifact.stale_binary() else { continue };
|
||||
match resolve(root, &projects[*owner], artifact, repository, profile_args, Some(binary), cancel)
|
||||
{
|
||||
Ok(Some(_)) => refreshed.push(artifact.binary.clone()),
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::debug!(path = %artifact.sources.display(), "Maven sources refresh: {e}"),
|
||||
}
|
||||
}
|
||||
refreshed
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
workers.into_iter().flat_map(|worker| worker.join().expect("Maven sources worker")).collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -289,86 +121,4 @@ mod tests {
|
||||
assert_eq!(artifact(Path::new(path), repository), None, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
|
||||
use crate::maven::{MavenDependency, Omission};
|
||||
|
||||
let repo = tempfile::tempdir().unwrap();
|
||||
let dependency = |name: &str, version: &str, cached: bool| {
|
||||
if cached {
|
||||
let dir = repo.path().join("example").join(name).join(version);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join(format!("{name}-{version}-sources.jar")), b"cached").unwrap();
|
||||
}
|
||||
MavenDependency {
|
||||
group_id: "example".into(),
|
||||
artifact_id: name.into(),
|
||||
version: Some(version.into()),
|
||||
kind: "jar".into(),
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let transitive = dependency("transitive", "1-SNAPSHOT", true);
|
||||
let direct = MavenDependency { children: vec![transitive.clone()], ..dependency("direct", "1-SNAPSHOT", true) };
|
||||
let omitted =
|
||||
MavenDependency { omitted: Some(Omission::Conflict), ..dependency("omitted", "1-SNAPSHOT", true) };
|
||||
let projects = [
|
||||
MavenProject {
|
||||
dependencies: vec![
|
||||
direct,
|
||||
omitted,
|
||||
dependency("missing", "1-SNAPSHOT", false),
|
||||
dependency("release", "1", true),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
MavenProject { dependencies: vec![transitive], ..Default::default() },
|
||||
];
|
||||
let mut found: Vec<_> = cached_snapshots(repo.path(), projects.iter().enumerate())
|
||||
.into_iter()
|
||||
.map(|(owner, artifact)| (owner, artifact.name))
|
||||
.collect();
|
||||
found.sort();
|
||||
assert_eq!(found, [(0, "direct".into()), (0, "transitive".into())]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn downloads_sources_again_when_the_snapshot_binary_is_newer() {
|
||||
use std::fs::FileTimes;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Duration;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repository = dir.path().join("repository");
|
||||
let jar = repository.join("example/lib/1-SNAPSHOT/lib-1-SNAPSHOT.jar");
|
||||
fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
fs::write(&jar, b"new binary").unwrap();
|
||||
let artifact = artifact(&jar, &repository).unwrap();
|
||||
fs::write(&artifact.sources, b"old sources").unwrap();
|
||||
File::open(&artifact.sources)
|
||||
.unwrap()
|
||||
.set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(60)))
|
||||
.unwrap();
|
||||
let launcher = dir.path().join("mvn");
|
||||
fs::write(
|
||||
&launcher,
|
||||
"#!/bin/sh\nfor arg do\n case \"$arg\" in\n -DoutputDirectory=*) out=\"${arg#*=}\" ;;\n esac\ndone\nprintf 'new sources' > \"$out/lib-1-SNAPSHOT-sources.jar\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert!(download(dir.path(), &MavenProject::default(), &artifact, &repository, &cancel).is_err());
|
||||
assert_eq!(fs::read(&artifact.sources).unwrap(), b"old sources");
|
||||
let project = MavenProject { command: launcher.to_string_lossy().into_owned(), ..Default::default() };
|
||||
let cancel = CancellationToken::new();
|
||||
let path = download(dir.path(), &project, &artifact, &repository, &cancel).unwrap().unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"new sources");
|
||||
assert_eq!(
|
||||
download(dir.path(), &MavenProject::default(), &artifact, &repository, &CancellationToken::new()).unwrap(),
|
||||
Some(path)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,21 +24,6 @@ pub(crate) const MAX_LINE_BYTES: usize = 1024 * 1024;
|
||||
/// `Output::text` stops growing past this while the pipes keep draining: a chatty build can
|
||||
/// print far more than is ever parsed back out of the retained copy.
|
||||
pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// Lines the pipe readers may queue ahead of the consumer. A build printing faster than
|
||||
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
|
||||
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
|
||||
const LINE_QUEUE: usize = 64;
|
||||
/// What [`pump_bounded`] reads from a pipe at a time.
|
||||
const PUMP_CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// One line of a child's output, with the stream it came from.
|
||||
type Line = (Stream, String);
|
||||
|
||||
/// The queue from the pipe readers to the consumer: bounded, so the readers wait while the
|
||||
/// consumer is behind.
|
||||
fn line_queue() -> (mpsc::SyncSender<Line>, mpsc::Receiver<Line>) {
|
||||
mpsc::sync_channel(LINE_QUEUE)
|
||||
}
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub success: bool,
|
||||
@@ -48,20 +33,20 @@ pub(crate) struct Output {
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Bounded pump for callers that stream every line and only summarize errors: reads
|
||||
/// [`PUMP_CHUNK`] chunks, splits newline-free runs at a UTF-8 char boundary at the line cap,
|
||||
/// and never grows one line buffer without bound.
|
||||
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::SyncSender<Line>) {
|
||||
/// Bounded pump for callers that stream every line and only summarize errors: reads fixed
|
||||
/// 64 KiB chunks, splits newline-free runs at a UTF-8 char boundary at the line cap, and
|
||||
/// never grows one line buffer without bound.
|
||||
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::Sender<(Stream, String)>) {
|
||||
let mut reader = BufReader::new(stream);
|
||||
// `terminated`: the buffer ends in the stream's newline. A segment cut from a
|
||||
// newline-free run at the line cap must keep a trailing `\r` — it is data.
|
||||
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::SyncSender<Line>| {
|
||||
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::Sender<(Stream, String)>| {
|
||||
let line = ide_core::output_encoding::decode_tool_output(buf);
|
||||
let line = if terminated { line.trim_end_matches(['\n', '\r']).to_owned() } else { line };
|
||||
buf.clear();
|
||||
tx.send((kind, line)).is_ok()
|
||||
};
|
||||
let mut chunk = vec![0u8; PUMP_CHUNK];
|
||||
let mut chunk = vec![0u8; 64 * 1024];
|
||||
let mut line: Vec<u8> = Vec::with_capacity(256);
|
||||
'read: loop {
|
||||
let n = match reader.read(&mut chunk) {
|
||||
@@ -194,8 +179,8 @@ fn run_with_env_capture(
|
||||
}
|
||||
let mut child =
|
||||
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::SyncSender<Line>| {
|
||||
let (tx, rx) = mpsc::channel::<(Stream, String)>();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
|
||||
std::thread::spawn(move || {
|
||||
if bounded {
|
||||
pump_bounded(stream, kind, &tx);
|
||||
@@ -227,8 +212,7 @@ fn run_with_env_capture(
|
||||
// Retained copy of the output: the first half of the cap, then — once output overflows —
|
||||
// a rolling tail instead of the middle. Error summaries read the end of the output, while
|
||||
// listings parsed out of a successful run read from the start. The pipes keep draining
|
||||
// either way: `on_line` still sees every line, and the child waits on its pipe only
|
||||
// while `on_line` is behind, never because the retained copy is full.
|
||||
// either way: `on_line` still sees every line, so the child never blocks on a full pipe.
|
||||
let cap = MAX_TEXT_BYTES / 2;
|
||||
let mut head = String::new();
|
||||
let mut tail: std::collections::VecDeque<Vec<u8>> = Default::default();
|
||||
@@ -311,9 +295,6 @@ fn run_with_env_capture(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
fn a_model_line_over_one_mebibyte_is_kept_whole_for_the_parsers() {
|
||||
@@ -519,124 +500,4 @@ mod tests {
|
||||
assert!(out.text.starts_with("pad\n"));
|
||||
assert!(out.text.ends_with("FATAL: the real error\n"));
|
||||
}
|
||||
|
||||
/// Numbered lines of `LINE_LEN` bytes each, counting the bytes taken: a pipe stand-in that
|
||||
/// reports when it is dropped, which is when the pump owning it ends.
|
||||
const LINE_LEN: usize = 100;
|
||||
|
||||
struct NumberedLines {
|
||||
next: usize,
|
||||
lines: usize,
|
||||
taken: Arc<AtomicUsize>,
|
||||
gone: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
fn numbered(n: usize) -> String {
|
||||
format!("{n:0width$}", width = LINE_LEN - 1)
|
||||
}
|
||||
|
||||
impl Read for NumberedLines {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let mut n = 0;
|
||||
while self.next < self.lines && n + LINE_LEN <= buf.len() {
|
||||
buf[n..n + LINE_LEN - 1].copy_from_slice(numbered(self.next).as_bytes());
|
||||
buf[n + LINE_LEN - 1] = b'\n';
|
||||
self.next += 1;
|
||||
n += LINE_LEN;
|
||||
}
|
||||
self.taken.fetch_add(n, Ordering::SeqCst);
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NumberedLines {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.gone.send(());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_consumer_holds_the_pump_back_instead_of_queueing_every_line() {
|
||||
const LINES: usize = 50_000;
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone, _) = mpsc::channel();
|
||||
let pipe = NumberedLines { next: 0, lines: LINES, taken: taken.clone(), gone };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
let (mut count, mut peak) = (0usize, 0usize);
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok((stream, line)) => {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, numbered(count), "a line arrived out of order or damaged");
|
||||
// Read from the pipe but not yet handed over: the rest of the chunk the pump
|
||||
// is cutting into lines, and the queue.
|
||||
peak = peak.max(taken.load(Ordering::SeqCst) - count * LINE_LEN);
|
||||
count += 1;
|
||||
// A consumer that cannot keep up with the process.
|
||||
if count.is_multiple_of(LINE_QUEUE) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the pump stalled"),
|
||||
}
|
||||
}
|
||||
pump.join().unwrap();
|
||||
assert_eq!(count, LINES);
|
||||
let bound = PUMP_CHUNK + (LINE_QUEUE + 2) * LINE_LEN;
|
||||
assert!(peak <= bound, "{peak} bytes read ahead of the consumer, more than {bound}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pump_blocked_on_a_full_queue_ends_when_the_consumer_is_gone() {
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone_tx, gone) = mpsc::channel();
|
||||
// Far more than the queue and a few chunks hold.
|
||||
let pipe = NumberedLines { next: 0, lines: 100_000, taken: taken.clone(), gone: gone_tx };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
// A consumer that takes nothing: the queue fills, with the pump inside its first chunk.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while taken.load(Ordering::SeqCst) == 0 {
|
||||
assert!(Instant::now() < deadline, "the pump never read");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
// Time for a pump that does not wait to run ahead.
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert!(taken.load(Ordering::SeqCst) <= PUMP_CHUNK, "the pump read past a full queue");
|
||||
assert!(gone.try_recv().is_err(), "the pump ended while its consumer was still there");
|
||||
drop(rx);
|
||||
gone.recv_timeout(Duration::from_secs(30)).expect("the pump stayed blocked after the consumer was gone");
|
||||
pump.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_on_line_still_sees_every_line_in_order_and_the_exit_status() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let args = ["-c".into(), "awk 'BEGIN{for(i=1;i<=300000;i++)print i}'; exit 4".into()];
|
||||
for bounded in [false, true] {
|
||||
let mut next = 1usize;
|
||||
let on_line = |stream: Stream, line: &str| {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, next.to_string());
|
||||
next += 1;
|
||||
if next.is_multiple_of(1000) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let out = if bounded {
|
||||
run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
} else {
|
||||
run("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
}
|
||||
.unwrap();
|
||||
assert!(!out.success);
|
||||
assert_eq!(next, 300_001, "lines were lost");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
dunce.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -95,7 +95,7 @@ pub enum ErrorKind {
|
||||
AlreadyExists,
|
||||
PermissionDenied,
|
||||
InvalidInput,
|
||||
/// The requested state is stale; the UI must use the current snapshot.
|
||||
/// Document version mismatch; the UI must resync the full text.
|
||||
OutOfSync,
|
||||
Cancelled,
|
||||
TimedOut,
|
||||
|
||||
@@ -324,8 +324,6 @@ pub enum LspRefreshKind {
|
||||
InlayHints,
|
||||
SemanticTokens,
|
||||
CodeLens,
|
||||
/// An import or classpath update may have changed inheritance search results.
|
||||
Inheritance,
|
||||
/// The Dart server published a document's Flutter outline.
|
||||
FlutterOutline,
|
||||
}
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
|
||||
//! serializes as a standard padded base64 string and is a plain `string` in the generated
|
||||
//! bindings.
|
||||
//!
|
||||
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
|
||||
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
|
||||
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use serde::de::{self, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::fmt;
|
||||
use std::ops::Deref;
|
||||
|
||||
/// A binary argument or result of an IPC command.
|
||||
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
|
||||
#[specta(transparent)]
|
||||
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
|
||||
|
||||
impl IpcBytes {
|
||||
pub fn into_vec(self) -> Vec<u8> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for IpcBytes {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "IpcBytes({} bytes)", self.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for IpcBytes {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&STANDARD.encode(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for IpcBytes {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct Base64;
|
||||
impl Visitor<'_> for Base64 {
|
||||
type Value = IpcBytes;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("a base64 string")
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
|
||||
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
|
||||
}
|
||||
}
|
||||
d.deserialize_str(Base64)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for IpcBytes {
|
||||
type Target = [u8];
|
||||
fn deref(&self) -> &[u8] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<u8>> for IpcBytes {
|
||||
fn from(bytes: Vec<u8>) -> Self {
|
||||
Self(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn round_trip(bytes: Vec<u8>) {
|
||||
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
|
||||
let text = value.as_str().expect("serializes as a string");
|
||||
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
|
||||
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_empty_every_byte_and_large_input() {
|
||||
round_trip(Vec::new());
|
||||
round_trip((0..=255).collect());
|
||||
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_a_json_document() {
|
||||
let bytes: Vec<u8> = (0..=255).collect();
|
||||
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
|
||||
#[derive(Deserialize)]
|
||||
struct Args {
|
||||
data: IpcBytes,
|
||||
}
|
||||
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
|
||||
}
|
||||
|
||||
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
|
||||
#[test]
|
||||
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
|
||||
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
|
||||
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
|
||||
assert!(json.starts_with('"') && json.ends_with('"'));
|
||||
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
|
||||
let as_array = serde_json::to_string(&bytes).unwrap();
|
||||
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_what_is_not_base64() {
|
||||
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
|
||||
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_does_not_print_the_bytes() {
|
||||
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@ pub mod ids;
|
||||
pub mod ignored;
|
||||
pub mod input;
|
||||
pub mod inspection_settings;
|
||||
pub mod ipc_bytes;
|
||||
pub mod ipc_path;
|
||||
pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
@@ -38,7 +37,6 @@ pub mod wsl;
|
||||
pub use error::{IdeError, IdeResult};
|
||||
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
|
||||
pub use ids::*;
|
||||
pub use ipc_bytes::IpcBytes;
|
||||
pub use ipc_path::IpcPath;
|
||||
pub use text::*;
|
||||
pub use tokio_util::sync::CancellationToken;
|
||||
@@ -1396,9 +1396,6 @@ pub struct PythonSettings {
|
||||
pub hide_other_project_interpreters: bool,
|
||||
/// Show each interpreter's path under its name on the interpreters page.
|
||||
pub show_interpreter_paths: bool,
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1410,7 +1407,6 @@ impl Default for PythonSettings {
|
||||
hidden_interpreters: Vec::new(),
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1752,7 +1752,9 @@ impl DebugManager {
|
||||
let body = session.conn.request_timeout("continue", json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?;
|
||||
// DAP: a response without the flag continued every thread.
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true);
|
||||
session.finish_resume(ticket, thread_id, all);
|
||||
session.suspended.resumed(ticket, thread_id, all);
|
||||
stream_trace::release_done(&session);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1799,7 +1801,9 @@ impl DebugManager {
|
||||
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), 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);
|
||||
session.suspended.resumed(ticket, thread_id, false);
|
||||
stream_trace::release_done(&session);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1909,7 +1913,9 @@ impl DebugManager {
|
||||
.request_timeout("stepIn", json!({ "threadId": thread_id, "targetId": target_id }), REQUEST_TIMEOUT)
|
||||
.await;
|
||||
step_settled(&session, sent)?;
|
||||
session.finish_resume(ticket, thread_id, false);
|
||||
session.suspended.resumed(ticket, thread_id, false);
|
||||
stream_trace::release_done(&session);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+15
-136
@@ -160,36 +160,19 @@ impl Stops {
|
||||
}
|
||||
|
||||
/// Ends the stops taken by ticket `upto` of `thread`, or of every thread.
|
||||
/// Returns whether any stop was removed.
|
||||
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) -> bool {
|
||||
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) {
|
||||
let latest = self.latest();
|
||||
let before = (self.all, self.threads.len());
|
||||
if every || thread.is_none() || self.all.is_some_and(|t| t <= upto) {
|
||||
self.all = self.all.filter(|&t| t > upto);
|
||||
self.threads.retain(|&(_, t)| t > upto);
|
||||
} else {
|
||||
self.threads.retain(|&(id, t)| Some(id) != thread || t > upto);
|
||||
}
|
||||
let changed = (self.all, self.threads.len()) != before;
|
||||
// Back on an earlier thread's stop, as the JDWP link moves to it with a new generation.
|
||||
let now = self.latest();
|
||||
if now.is_some() && now != latest {
|
||||
self.ticket += 1;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Whether a stop taken after `after` would be undone by a synthetic `continued` event for
|
||||
/// `thread` (or for every thread when `every` is set).
|
||||
fn superseded(&self, thread: i64, every: bool, after: u64) -> bool {
|
||||
if self.all.is_some_and(|t| t > after) {
|
||||
return true;
|
||||
}
|
||||
if every {
|
||||
self.threads.iter().any(|&(_, t)| t > after)
|
||||
} else {
|
||||
self.threads.iter().any(|&(id, t)| id == thread && t > after)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,27 +197,12 @@ impl Suspension {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `emit` under the suspension lock so a synthetic `continued` from a resume reply cannot
|
||||
/// be emitted after a `stopped` event once that stop has been recorded.
|
||||
pub fn emit_synced(&self, emit: impl FnOnce()) {
|
||||
let _stops = self.0.lock();
|
||||
emit();
|
||||
}
|
||||
|
||||
/// A `continued` event; `all`: its `allThreadsContinued`. Runs `emit` under the same lock so
|
||||
/// synthetic `continued` events from resume replies stay ordered against it.
|
||||
pub fn continued_and_emit(&self, thread: Option<i64>, all: bool, emit: impl FnOnce()) {
|
||||
let mut stops = self.0.lock();
|
||||
stops.release(thread, all, u64::MAX);
|
||||
emit();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// A `continued` event; `all`: its `allThreadsContinued`.
|
||||
pub fn continued(&self, thread: Option<i64>, all: bool) {
|
||||
self.continued_and_emit(thread, all, || {});
|
||||
self.0.lock().release(thread, all, u64::MAX);
|
||||
}
|
||||
|
||||
/// Take before sending a resume-like request and pass to [`Self::resumed_and_emit`].
|
||||
/// Take before sending a resume-like request and pass to [`Self::resumed`].
|
||||
pub fn ticket(&self) -> u64 {
|
||||
self.0.lock().ticket
|
||||
}
|
||||
@@ -247,19 +215,8 @@ impl Suspension {
|
||||
}
|
||||
|
||||
/// After a successful resume-like request for `thread`; `all`: every thread ran.
|
||||
/// Runs `emit` under the lock only when a prior stop was ended and no newer stop superseded it.
|
||||
pub fn resumed_and_emit(&self, ticket: u64, thread: i64, all: bool, emit: impl FnOnce()) {
|
||||
let mut stops = self.0.lock();
|
||||
let superseded = stops.superseded(thread, all, ticket);
|
||||
let released = stops.release(Some(thread), all, ticket);
|
||||
if released && !superseded {
|
||||
emit();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn resumed(&self, ticket: u64, thread: i64, all: bool) {
|
||||
self.resumed_and_emit(ticket, thread, all, || {});
|
||||
self.0.lock().release(Some(thread), all, ticket);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,16 +316,6 @@ impl Session {
|
||||
self.owner.sink.emit(IdeEvent::Debug { session: self.id, event });
|
||||
}
|
||||
|
||||
/// Completes a successful resume or step reply (`ticket` taken before the request): ends the
|
||||
/// prior stops and emits a synthetic `continued` event unless an adapter event already ended
|
||||
/// them or a newer `stopped` event superseded it.
|
||||
pub(crate) fn finish_resume(&self, ticket: u64, thread_id: i64, all: bool) {
|
||||
self.suspended.resumed_and_emit(ticket, thread_id, all, || {
|
||||
self.emit(DebugEvent::Continued { thread_id, all_threads_continued: all });
|
||||
});
|
||||
crate::stream_trace::release_done(self);
|
||||
}
|
||||
|
||||
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
|
||||
pub fn adapter_path(&self, path: &Path) -> PathBuf {
|
||||
if let Some(path) = self.kotlin_mirror.lock().as_ref().and_then(|m| m.adapter_path(path)) {
|
||||
@@ -842,26 +789,23 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
reason = quirks.stop_reason(reason);
|
||||
}
|
||||
mgr.restore_breakpoints(s).await;
|
||||
s.suspended.emit_synced(|| {
|
||||
s.emit(DebugEvent::Stopped {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
reason,
|
||||
description: str_("description").or_else(|| str_("text")),
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
s.emit(DebugEvent::Stopped {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
reason,
|
||||
description: str_("description").or_else(|| str_("text")),
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
}
|
||||
"continued" => {
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
|
||||
// DAP: an event without the flag continues its thread alone. The UI keeps treating
|
||||
// it as all threads; the suspension, which holds only threads that stopped, need not.
|
||||
s.suspended.continued_and_emit(int("threadId"), all.unwrap_or(false), || {
|
||||
s.emit(DebugEvent::Continued {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
all_threads_continued: all.unwrap_or(true),
|
||||
});
|
||||
});
|
||||
s.suspended.continued(int("threadId"), all.unwrap_or(false));
|
||||
crate::stream_trace::release_done(s);
|
||||
s.emit(DebugEvent::Continued {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
all_threads_continued: all.unwrap_or(true),
|
||||
});
|
||||
}
|
||||
"output" => {
|
||||
let category = str_("category").unwrap_or_else(|| "console".into());
|
||||
@@ -1521,71 +1465,6 @@ mod tests {
|
||||
assert!(!s.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_continued_is_suppressed_when_a_newer_stop_or_continued_already_landed() {
|
||||
let emit_if_resumed = |s: &Suspension, ticket, thread, all| {
|
||||
let mut emitted = false;
|
||||
s.resumed_and_emit(ticket, thread, all, || emitted = true);
|
||||
emitted
|
||||
};
|
||||
|
||||
// Normal step without an adapter `continued` event emits a synthetic one.
|
||||
let s = Suspension::default();
|
||||
s.stopped(Some(1), true);
|
||||
assert!(emit_if_resumed(&s, s.ticket(), 1, false));
|
||||
|
||||
// Next `stopped` (all-threads or single-thread) overtakes the reply: no synthetic `continued`.
|
||||
for next_all in [true, false] {
|
||||
let s = Suspension::default();
|
||||
s.stopped(Some(1), true);
|
||||
let ticket = s.ticket();
|
||||
s.stopped(Some(1), next_all);
|
||||
assert!(!emit_if_resumed(&s, ticket, 1, false), "next_all={next_all}");
|
||||
assert!(s.get());
|
||||
}
|
||||
|
||||
// Adapter's own `continued` event already ended the stop: no duplicate synthetic `continued`.
|
||||
let s = Suspension::default();
|
||||
s.stopped(Some(1), true);
|
||||
let ticket = s.ticket();
|
||||
s.continued(Some(1), true);
|
||||
assert!(!emit_if_resumed(&s, ticket, 1, true));
|
||||
|
||||
// Multi-thread: thread 7 steps while thread 9 stops alone -> thread 7 still emits `continued(all=false)`.
|
||||
let s = two_threads_stopped();
|
||||
let ticket = s.ticket();
|
||||
s.stopped(Some(9), false);
|
||||
assert!(emit_if_resumed(&s, ticket, 7, false));
|
||||
assert!(s.get());
|
||||
|
||||
// Multi-thread: `continue(all=true)` while thread 9 stops alone -> suppressed so thread 9 stays paused.
|
||||
let s = two_threads_stopped();
|
||||
let ticket = s.ticket();
|
||||
s.stopped(Some(9), false);
|
||||
assert!(!emit_if_resumed(&s, ticket, 7, true));
|
||||
assert!(s.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_stop_and_resume_never_emit_continued_after_the_new_stop() {
|
||||
for _ in 0..200 {
|
||||
let s = std::sync::Arc::new(Suspension::default());
|
||||
let log = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<&'static str>::new()));
|
||||
s.stopped(Some(1), true);
|
||||
let ticket = s.ticket();
|
||||
let s2 = s.clone();
|
||||
let log2 = log.clone();
|
||||
let stop = std::thread::spawn(move || {
|
||||
s2.stopped(Some(1), false);
|
||||
s2.emit_synced(|| log2.lock().push("stopped"));
|
||||
});
|
||||
s.resumed_and_emit(ticket, 1, false, || log.lock().push("continued"));
|
||||
stop.join().unwrap();
|
||||
let events = log.lock().clone();
|
||||
assert!(events == ["continued", "stopped"] || events == ["stopped"], "unexpected order: {events:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_launch_starts_attach_listener_first() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -157,11 +157,6 @@ struct Script {
|
||||
breakpoints_after_continue: usize,
|
||||
/// The `reason` of the stop a `next` ends with (`step` when unset; kotlin-lsp says `breakpoint`).
|
||||
step_reason: Option<&'static str>,
|
||||
/// Send `stopped` before answering `next` / `stepIn` / `stepOut` / `continue` (like php-debug
|
||||
/// when Xdebug finishes a step before the DAP reply is handled).
|
||||
stop_before_reply: bool,
|
||||
/// Send `continued` before answering `next` / `continue`.
|
||||
continued_before_reply: bool,
|
||||
/// Refuse `next`, then stop at a breakpoint (one the program hit meanwhile).
|
||||
refuse_next: bool,
|
||||
/// Send `invalidated { areas: ["variables"] }` right after the first `stopped` event.
|
||||
@@ -218,8 +213,6 @@ impl Default for Script {
|
||||
refuse_continue: false,
|
||||
breakpoints_after_continue: 0,
|
||||
step_reason: None,
|
||||
stop_before_reply: false,
|
||||
continued_before_reply: false,
|
||||
refuse_next: false,
|
||||
invalidated_after_stop: false,
|
||||
stop_during_threads: false,
|
||||
@@ -421,19 +414,6 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}}));
|
||||
}
|
||||
"next" if script.stop_before_reply => {
|
||||
let reason = script.step_reason.unwrap_or("step");
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": 1}}));
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
"next" if script.continued_before_reply => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": false}})
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
"next" => {
|
||||
ok!(msg, Value::Null);
|
||||
let reason = script.step_reason.unwrap_or("step");
|
||||
@@ -573,20 +553,6 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
"stepOut" if script.refuse_step_out => send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "stepOut", "success": false, "message": "Thread is not suspended"})
|
||||
),
|
||||
"continue" if script.stop_before_reply => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
}
|
||||
"continue" if script.continued_before_reply => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": true}})
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
}
|
||||
"continue" if script.stop_after_continue => {
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
send!(
|
||||
@@ -609,11 +575,6 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": thread}}));
|
||||
}
|
||||
}
|
||||
"stepIn" | "stepOut" if script.stop_before_reply => {
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "step", "threadId": 1}}));
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
"stepIn" | "stepOut" | "pause" => ok!(msg, Value::Null),
|
||||
"hotReload" => {
|
||||
ok!(msg, Value::Null);
|
||||
@@ -2828,74 +2789,6 @@ async fn step_of_one_thread_keeps_the_others_suspended() {
|
||||
}
|
||||
}
|
||||
|
||||
/// When an adapter emits the next `stopped` event before replying to `next` / `stepIn` / `stepOut`
|
||||
/// / `continue` (as php-debug / Xdebug can on fast steps), no trailing synthetic `continued` may
|
||||
/// overwrite the new stop.
|
||||
#[tokio::test]
|
||||
async fn stop_before_reply_does_not_emit_trailing_continued() {
|
||||
let h = harness(Script { stop_before_reply: true, ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let session = h.manager.session(id).unwrap();
|
||||
|
||||
let run_events = |from: usize| {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.skip(from)
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Debug { event: DebugEvent::Stopped { reason, .. }, .. } => Some(format!("stopped:{reason}")),
|
||||
IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. } => Some("continued".into()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
for (label, expected) in [
|
||||
("over", "stopped:step"),
|
||||
("into", "stopped:step"),
|
||||
("out", "stopped:step"),
|
||||
("target", "stopped:step"),
|
||||
("resume", "stopped:breakpoint"),
|
||||
] {
|
||||
let before = h.events.lock().len();
|
||||
match label {
|
||||
"over" => h.manager.step(id, 1, StepKind::Over).await.unwrap(),
|
||||
"into" => h.manager.step(id, 1, StepKind::Into).await.unwrap(),
|
||||
"out" => h.manager.step(id, 1, StepKind::Out).await.unwrap(),
|
||||
"target" => h.manager.step_in_target(id, 1, 1).await.unwrap(),
|
||||
"resume" => h.manager.resume(id, 1).await.unwrap(),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
assert!(session.suspended.get(), "{label}: session must remain suspended");
|
||||
assert_eq!(run_events(before), [expected], "{label}: must not emit continued after stopped");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn continued_event_before_reply_does_not_emit_duplicate_continued() {
|
||||
for is_resume in [false, true] {
|
||||
let h = harness(Script { continued_before_reply: true, ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
|
||||
let before = h.events.lock().len();
|
||||
if is_resume {
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
} else {
|
||||
h.manager.step(id, 1, StepKind::Over).await.unwrap();
|
||||
}
|
||||
let continued = h
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.skip(before)
|
||||
.filter(|e| matches!(e, IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. }))
|
||||
.count();
|
||||
assert_eq!(continued, 1, "is_resume={is_resume}: adapter continued event already reported it");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lazy_variables_are_resolved_when_the_adapter_declares_them_safe() {
|
||||
let h = harness(Script::default());
|
||||
|
||||
@@ -658,12 +658,7 @@ mod local_tests {
|
||||
let batches = Mutex::new(Vec::<Vec<u32>>::new());
|
||||
let result = batched(Duration::from_millis(30), &|b| batches.lock().unwrap().push(b), |line| {
|
||||
(0..1000).for_each(line);
|
||||
// Wait for the flusher to emit the whole burst rather than assuming a fixed
|
||||
// sleep outlasts its scheduling: a loaded runner can starve the thread
|
||||
// past the quiet spell and fold the trailing line into the burst.
|
||||
while batches.lock().unwrap().iter().map(Vec::len).sum::<usize>() < 1000 {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(80));
|
||||
line(1000);
|
||||
"done"
|
||||
});
|
||||
|
||||
@@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
|
||||
/// (compile errors are added to `errors`). Other configurations are returned as they are.
|
||||
async fn resolve_jvm_application(
|
||||
call: &Call,
|
||||
mut config: RunConfig,
|
||||
config: RunConfig,
|
||||
errors: &mut BuildErrors,
|
||||
) -> IdeResult<Result<RunConfig, String>> {
|
||||
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
|
||||
@@ -544,7 +544,6 @@ async fn resolve_jvm_application(
|
||||
(Some(exec), "java") => exec.clone(),
|
||||
_ => config.command.clone(),
|
||||
};
|
||||
config.extras.module = Some(module);
|
||||
Ok(Ok(RunConfig { command, args, ..config }))
|
||||
}
|
||||
|
||||
|
||||
@@ -43,19 +43,12 @@ pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeRe
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads the ACP registry's install state for every provider from disk, so it runs on the
|
||||
/// blocking pool.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
|
||||
pub fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
let paths = registry_paths(host);
|
||||
host.blocking(move || {
|
||||
let mut providers = agents.providers();
|
||||
ide_agent::registry::mark_updates(&paths, &mut providers);
|
||||
Ok(providers)
|
||||
})
|
||||
.await
|
||||
let mut providers = host.project(window)?.agents.providers();
|
||||
ide_agent::registry::mark_updates(®istry_paths(host), &mut providers);
|
||||
Ok(providers)
|
||||
}
|
||||
|
||||
/// Hermes Agent profiles on this machine (`default` first); empty without Hermes.
|
||||
@@ -256,15 +249,9 @@ pub async fn agent_commands(
|
||||
host.project(window)?.agents.commands(&provider, task.as_deref()).await
|
||||
}
|
||||
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. Async so a long
|
||||
/// conversation is cloned and serialised off the main thread.
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_entries(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<Vec<AgentEntry>> {
|
||||
pub fn agent_entries(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
host.project(window)?.agents.entries(&task, subagent)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Maven / Gradle tool windows (the build model and its background sync) and
|
||||
//! Build › Build Project (compiling with the project's build system).
|
||||
pub(super) mod workspace;
|
||||
mod workspace;
|
||||
|
||||
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
|
||||
use crate::ops::Channel;
|
||||
@@ -9,16 +9,13 @@ use ide_command::command;
|
||||
|
||||
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
|
||||
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
|
||||
use ide_build::maven::sources;
|
||||
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
|
||||
use ide_build::pom_edit::{ArtifactKey, Exclusion};
|
||||
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{
|
||||
CancellationToken, DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -184,7 +181,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
|
||||
|
||||
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
|
||||
/// the tool window do.
|
||||
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
|
||||
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
|
||||
let profiles = ide_build::maven_profiles(cache);
|
||||
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
|
||||
for p in &mut m.projects {
|
||||
@@ -284,35 +281,6 @@ pub async fn gradle_unlink_projects(host: &Host, window: &str, paths: Vec<String
|
||||
set_gradle_projects(host, window, paths, false).await
|
||||
}
|
||||
|
||||
struct MavenSourceRefresh {
|
||||
root: PathBuf,
|
||||
repository: PathBuf,
|
||||
candidates: Vec<(usize, sources::Artifact)>,
|
||||
}
|
||||
|
||||
fn cached_maven_sources(
|
||||
model: &BuildModel,
|
||||
scopes: Vec<workspace::Scope>,
|
||||
window_root: &Path,
|
||||
build_dir: Option<&str>,
|
||||
) -> Vec<MavenSourceRefresh> {
|
||||
let Some(maven) = &model.maven else { return Vec::new() };
|
||||
scopes
|
||||
.into_iter()
|
||||
.filter(|scope| workspace::selected(scope, window_root, BuildTool::Maven, build_dir))
|
||||
.filter_map(|scope| {
|
||||
let repository = ide_sdk::apply::maven_local_repository(&scope.root, &scope.settings)
|
||||
.or_else(ide_build::maven::default_local_repo)?;
|
||||
let projects = maven.projects.iter().enumerate().filter(|(_, project)| {
|
||||
Path::new(project.project_root.as_deref().unwrap_or_default()) == scope.root
|
||||
|| (project.project_root.is_none() && scope.root == window_root)
|
||||
});
|
||||
let candidates = sources::cached_snapshots(&repository, projects);
|
||||
(!candidates.is_empty()).then_some(MavenSourceRefresh { root: scope.root, repository, candidates })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs Maven (`help:effective-pom dependency:tree`) or Gradle (`tasks --all`) in the
|
||||
/// background, reporting progress on `on_progress`; cancellable with `cancel_request(request)`.
|
||||
/// Returns the refreshed model; a failed build is reported in its `syncError`.
|
||||
@@ -409,122 +377,72 @@ pub async fn build_sync(
|
||||
let scopes = workspace::scopes(&p, &config)?;
|
||||
let model = workspace::load_scopes(&p.root, &scopes);
|
||||
let updates = workspace::update_files(&p.root, &scopes, &model, tool);
|
||||
let snapshots = if tool == BuildTool::Maven && !offline {
|
||||
cached_maven_sources(&model, scopes, &p.root, build_dir.as_deref())
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
Ok::<_, IdeError>((model, profiles_changed || offline_changed, updates, snapshots))
|
||||
Ok::<_, IdeError>((model, profiles_changed, offline_changed, updates))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
let result = async {
|
||||
let (mut model, reconfigure, updates, snapshots) = result??;
|
||||
if completion_token.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// A reactor or Gradle build may have changed its external project folders.
|
||||
project.refresh_index_scope();
|
||||
let p = project.clone();
|
||||
tokio::task::spawn_blocking(move || p.refresh_repositories());
|
||||
project.sink.emit(IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
|
||||
if tool == BuildTool::Maven
|
||||
&& model.maven.is_some()
|
||||
&& let Some(bridge) = &project.kotlin_bridge
|
||||
{
|
||||
bridge.configure_maven(offline, bridge_profiles.clone());
|
||||
}
|
||||
let lsp = project.lsp.clone();
|
||||
let documents = project.documents.clone();
|
||||
if snapshots.is_empty() {
|
||||
tokio::spawn(async move {
|
||||
update_java_projects(&lsp, &updates, reconfigure, None).await;
|
||||
refresh_library_archives(&lsp, &documents, &updates, Vec::new()).await;
|
||||
});
|
||||
} else {
|
||||
// JDT LS resolves the binary jars while importing Maven projects.
|
||||
update_java_projects(&lsp, &updates, reconfigure, Some(&completion_token)).await;
|
||||
let cancel = completion_token.clone();
|
||||
let (updated, refreshed) = tokio::task::spawn_blocking(move || {
|
||||
let mut refreshed = Vec::new();
|
||||
if let Some(maven) = &model.maven {
|
||||
for batch in snapshots {
|
||||
if cancel.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
refreshed.extend(sources::refresh_snapshots(
|
||||
&batch.root,
|
||||
&maven.projects,
|
||||
&batch.repository,
|
||||
&batch.candidates,
|
||||
&bridge_profiles,
|
||||
&cancel,
|
||||
));
|
||||
}
|
||||
}
|
||||
(model, refreshed)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?;
|
||||
model = updated;
|
||||
tokio::spawn(async move {
|
||||
refresh_library_archives(&lsp, &documents, &updates, refreshed).await;
|
||||
});
|
||||
}
|
||||
if completion_token.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Ok(model)
|
||||
}
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
let (model, profiles_changed, offline_changed, updates) = result??;
|
||||
if completion_token.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// Gradle may report project folders outside the project (`includeFlat`), and a Maven
|
||||
// reactor may have gained or dropped modules beside it: index and list them.
|
||||
project.refresh_index_scope();
|
||||
let p = project.clone();
|
||||
tokio::task::spawn_blocking(move || p.refresh_repositories());
|
||||
// New source folders and dependency versions: the Project view and External Libraries reload.
|
||||
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
|
||||
if tool == BuildTool::Maven
|
||||
&& model.maven.is_some()
|
||||
&& let Some(bridge) = &project.kotlin_bridge
|
||||
{
|
||||
bridge.configure_maven(offline, bridge_profiles);
|
||||
}
|
||||
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
|
||||
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
|
||||
// to update the project configurations re-resolves them (#436). The same
|
||||
// holds for Gradle: it reuses its cached classpath on restart, so a
|
||||
// dependency added to `build.gradle` stays unresolved until told to sync.
|
||||
let lsp = project.lsp.clone();
|
||||
let documents = project.documents.clone();
|
||||
tokio::spawn(async move {
|
||||
if profiles_changed || offline_changed {
|
||||
// jdtls takes the profiles and offline mode from its Maven settings (see `ide_sdk::maven_profiles`).
|
||||
lsp.reconfigure().await;
|
||||
}
|
||||
let first = updates.first().cloned();
|
||||
for file in updates {
|
||||
let uri = ide_lsp::path_to_uri_string(&file);
|
||||
if let Err(e) = lsp.java_update_project_configs(&file, vec![uri]).await {
|
||||
tracing::debug!("java/projectConfigurationsUpdate: {e}");
|
||||
}
|
||||
}
|
||||
let changed = {
|
||||
let lsp = lsp.clone();
|
||||
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
|
||||
};
|
||||
if let Some(file) = first
|
||||
&& let Err(e) = lsp.java_refresh_archives(&file, &changed).await
|
||||
{
|
||||
tracing::debug!("openidea.java.refreshArchives: {e}");
|
||||
}
|
||||
refresh_library_classes(&lsp, &documents).await;
|
||||
});
|
||||
Ok(model)
|
||||
}
|
||||
|
||||
async fn update_java_projects(
|
||||
lsp: &ide_lsp::LspManager,
|
||||
updates: &[PathBuf],
|
||||
reconfigure: bool,
|
||||
wait: Option<&CancellationToken>,
|
||||
) {
|
||||
if reconfigure {
|
||||
// jdtls takes the profiles and offline mode from its Maven settings.
|
||||
lsp.reconfigure().await;
|
||||
}
|
||||
// JDT LS caches its classpath and re-imports on build-file changes. Ask it to
|
||||
// re-resolve dependencies even when the build files stayed the same (#436).
|
||||
if let Err(e) = lsp.java_update_project_configs(updates, wait).await {
|
||||
tracing::debug!("Updating Java project configurations: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-read open library classes whose binary or attached sources changed in place.
|
||||
async fn refresh_library_archives(
|
||||
lsp: &Arc<ide_lsp::LspManager>,
|
||||
documents: &Arc<ide_workspace::Documents>,
|
||||
updates: &[PathBuf],
|
||||
refreshed: Vec<PathBuf>,
|
||||
) {
|
||||
let changed = {
|
||||
let lsp = lsp.clone();
|
||||
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
|
||||
};
|
||||
let archives: HashSet<_> = changed.into_iter().chain(refreshed).collect();
|
||||
if let Err(e) = lsp.java_refresh_archives(updates, &archives).await {
|
||||
tracing::debug!("openidea.java.refreshArchives: {e}");
|
||||
}
|
||||
/// Open library classes whose jar was replaced in place (a SNAPSHOT installed
|
||||
/// again keeps its path) show the new contents, like a reopened one.
|
||||
async fn refresh_library_classes(lsp: &Arc<ide_lsp::LspManager>, documents: &Arc<ide_workspace::Documents>) {
|
||||
let changed = {
|
||||
let (lsp, documents) = (lsp.clone(), documents.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
lsp.invalidate_library_archives(&archives);
|
||||
documents
|
||||
.open_documents()
|
||||
.into_iter()
|
||||
.filter_map(|doc| Some((doc, documents.virtual_uri(doc).ok().flatten()?)))
|
||||
.filter(|(_, uri)| {
|
||||
lsp.library_class_changed(uri)
|
||||
|| ide_lsp::LspManager::library_archive(uri).is_some_and(|archive| archives.contains(&archive))
|
||||
})
|
||||
.filter(|(_, uri)| lsp.library_class_changed(uri))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.await
|
||||
@@ -1034,18 +952,16 @@ pub async fn build_run(
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
let mut launch_caches = Vec::new();
|
||||
let plan = if let Some(id) = cmake {
|
||||
launch_caches.push(cache.clone());
|
||||
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
|
||||
cmake_plan(&root, kind, &configs, &id)?
|
||||
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
|
||||
let mut combined: Option<compile::BuildPlan> = None;
|
||||
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
|
||||
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
|
||||
let member_cache = workspace::cache_at(&root, &cache, member);
|
||||
let member_cache =
|
||||
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
|
||||
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
|
||||
launch_caches.push(member_cache);
|
||||
let plan = prepare_plan(
|
||||
compile::plan(
|
||||
member,
|
||||
@@ -1069,7 +985,6 @@ pub async fn build_run(
|
||||
plan
|
||||
} else {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
launch_caches.push(cache.clone());
|
||||
match compile::plan(
|
||||
&root,
|
||||
&model,
|
||||
@@ -1092,9 +1007,7 @@ pub async fn build_run(
|
||||
});
|
||||
if kind == BuildKind::Rebuild {
|
||||
// The clean removed outputs that earlier launch snapshots still hold.
|
||||
for cache in launch_caches {
|
||||
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
|
||||
}
|
||||
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
|
||||
}
|
||||
let result = result?;
|
||||
if result.success && single && kind == BuildKind::Build {
|
||||
|
||||
@@ -1,33 +1,12 @@
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(in crate::ops) struct Scope {
|
||||
pub(super) struct Scope {
|
||||
pub root: PathBuf,
|
||||
pub cache: PathBuf,
|
||||
pub settings: Settings,
|
||||
}
|
||||
|
||||
pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult<Scope> {
|
||||
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
|
||||
let root = workspace
|
||||
.as_ref()
|
||||
.and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count()))
|
||||
.unwrap_or(&project.root);
|
||||
Ok(Scope {
|
||||
cache: cache_at(&project.root, &project.build_cache_dir(), root),
|
||||
settings: if root == &project.root {
|
||||
project.settings.effective()
|
||||
} else {
|
||||
project.settings.for_project(root).effective()
|
||||
},
|
||||
root: root.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf {
|
||||
if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) }
|
||||
}
|
||||
|
||||
pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>> {
|
||||
scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective())
|
||||
}
|
||||
@@ -40,7 +19,11 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
|
||||
.into_iter()
|
||||
.filter(|p| p.is_dir())
|
||||
.map(|root| Scope {
|
||||
cache: cache_at(window_root, cache, &root),
|
||||
cache: if root == window_root {
|
||||
cache.to_owned()
|
||||
} else {
|
||||
cache.join(crate::project::project_key(&root))
|
||||
},
|
||||
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
|
||||
root,
|
||||
})
|
||||
|
||||
@@ -44,15 +44,7 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
&& config.request == "launch"
|
||||
&& let Ok(project) = host.project(window)
|
||||
{
|
||||
let python = super::python::debug_python(&config);
|
||||
let paths = super::python::with_user_paths(
|
||||
super::python::paths(&project),
|
||||
&host.config_dir,
|
||||
&project,
|
||||
python.as_deref(),
|
||||
config.cwd.as_deref(),
|
||||
);
|
||||
super::python::prepare_debug(&mut config, &paths)?;
|
||||
super::python::prepare_debug(&mut config, &super::python::paths(&project))?;
|
||||
}
|
||||
let label = window;
|
||||
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::Channel;
|
||||
use crate::{Host, Project};
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, IpcBytes, RequestId};
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_vfs::FileEntry;
|
||||
use ide_workspace::DeletionUndo;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -209,7 +209,7 @@ pub fn fs_create_file(host: &Host, window: &str, path: PathBuf) -> IdeResult<()>
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: IpcBytes) -> IdeResult<()> {
|
||||
pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data: Vec<u8>) -> IdeResult<()> {
|
||||
let project = host.project(window).ok();
|
||||
host.blocking(move || {
|
||||
ide_vfs::create_file_bytes(&path, &data)?;
|
||||
@@ -228,15 +228,6 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
|
||||
ide_vfs::create_dir(&path)
|
||||
}
|
||||
|
||||
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
|
||||
/// keeps its scratches on the server, where its file commands run.
|
||||
#[command(trust = always)]
|
||||
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
|
||||
let dir = host.data_dir.join("scratches");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir.into())
|
||||
}
|
||||
|
||||
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
|
||||
/// state). Returns whether the file is read-only now.
|
||||
#[command(trust = always)]
|
||||
@@ -392,7 +383,6 @@ ide_command::domain!(
|
||||
fs_read_dir,
|
||||
fs_read_text,
|
||||
fs_rename,
|
||||
fs_scratches_dir,
|
||||
fs_set_writable,
|
||||
fs_synchronize_directories,
|
||||
fs_undo_delete,
|
||||
|
||||
@@ -4,7 +4,7 @@ pub(crate) mod cache;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
|
||||
use super::build::{load, with_profiles, workspace};
|
||||
use super::build::load;
|
||||
use ide_build::BuildModel;
|
||||
use ide_build::compile;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -46,44 +46,37 @@ pub(crate) async fn resolve_launch(
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let scope = {
|
||||
let (project, module) = (project.clone(), module.clone());
|
||||
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
};
|
||||
let module = project.root.join(module);
|
||||
if !project.lsp.java_served_by_jdtls(&module) {
|
||||
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
|
||||
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
|
||||
}
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let launches = project.java_launches.for_cache(&scope.cache);
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy);
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
let waiting = project.java_launches_waiting.add(module.clone(), test, policy);
|
||||
let settings = project.settings.effective();
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
let full = policy == BuildPolicy::Rebuild;
|
||||
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, external, mut delegated, is_maven) = {
|
||||
let scope = scope.clone();
|
||||
let launches = launches.clone();
|
||||
let (model, external, mut delegated, prefer_maven, is_maven) = {
|
||||
let project = project.clone();
|
||||
let settings = settings.clone();
|
||||
let module = module.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
launches.snapshots.lock().initialize();
|
||||
let root = &scope.root;
|
||||
let model = load_launch_model(&scope);
|
||||
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
|
||||
let is_maven = is_maven_module(root, &model, &module);
|
||||
project.java_launch_snapshots.lock().initialize();
|
||||
let model = load(&project.root, &project.build_cache_dir(), &settings);
|
||||
let non_java = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test);
|
||||
let is_maven =
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
|
||||
let prefer_maven = settings.languages.java.maven.delegate_build;
|
||||
let delegated = build
|
||||
&& delegates_to_external_build(
|
||||
is_maven,
|
||||
policy,
|
||||
non_java,
|
||||
cache::has_record(root, &scope.cache, &module),
|
||||
cache::has_record(&project.root, &project.build_cache_dir(), &module),
|
||||
prefer_maven,
|
||||
);
|
||||
let external = non_java || delegated;
|
||||
(model, external, delegated, is_maven)
|
||||
(model, external, delegated, prefer_maven, is_maven)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -108,7 +101,7 @@ pub(crate) async fn resolve_launch(
|
||||
}
|
||||
let model = std::sync::Arc::new(model);
|
||||
let members = if delegated {
|
||||
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
|
||||
build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
@@ -117,8 +110,7 @@ pub(crate) async fn resolve_launch(
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _external_build = external_build;
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
|
||||
// Module outputs the launch runs from a snapshot of: the originals must not come back.
|
||||
let mut snapshotted = Vec::new();
|
||||
// The modules of the launches sharing this build also share its classpath probe.
|
||||
@@ -126,8 +118,8 @@ pub(crate) async fn resolve_launch(
|
||||
std::iter::once(module.clone()).chain(members.iter().map(|m| m.module.clone())).collect();
|
||||
let built = if delegated {
|
||||
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
|
||||
let outputs = launches.snapshots.lock().build(
|
||||
root,
|
||||
let outputs = project.java_launch_snapshots.lock().build(
|
||||
&project.root,
|
||||
&model,
|
||||
&module,
|
||||
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
|
||||
@@ -140,7 +132,7 @@ pub(crate) async fn resolve_launch(
|
||||
snapshotted = outputs.originals;
|
||||
copies
|
||||
} else if external {
|
||||
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
|
||||
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
|
||||
if let Some(failure) = built.failure {
|
||||
if policy != BuildPolicy::MakeAndContinueOnErrors {
|
||||
return Err(IdeError::internal(failure));
|
||||
@@ -157,15 +149,24 @@ pub(crate) async fn resolve_launch(
|
||||
// m2e runs inside jdtls on the server JDK and can resolve a different
|
||||
// Maven profile/classifier than the module build. Ask the same Maven
|
||||
// process that built the module for its runtime/test dependencies.
|
||||
let maven_cp = compile::module_classpaths(root, &model, &probed, test, local_repo, cache, &cancel);
|
||||
let maven_cp = compile::module_classpaths(
|
||||
&project.root,
|
||||
&model,
|
||||
&probed,
|
||||
test,
|
||||
local_repo,
|
||||
&project.build_cache_dir(),
|
||||
&cancel,
|
||||
);
|
||||
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
|
||||
} else {
|
||||
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
|
||||
if build && !delegated {
|
||||
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
|
||||
let cache_dir = project.build_cache_dir();
|
||||
match compile::process_launch_resources(&project.root, &model, &cache_dir, &info.class_paths, &cancel) {
|
||||
Ok(tasks) if !tasks.is_empty() => tracing::info!(?tasks, "Processed launch resources with Gradle"),
|
||||
Ok(_) => {}
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
|
||||
@@ -176,7 +177,7 @@ pub(crate) async fn resolve_launch(
|
||||
}
|
||||
}
|
||||
let compile_ms = started.elapsed().as_millis() - lsp_ms;
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -193,36 +194,28 @@ pub(crate) async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
|
||||
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
|
||||
}
|
||||
|
||||
fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
|
||||
}
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
async fn resolve_launch_without_jdtls(
|
||||
host: &Host,
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
module: PathBuf,
|
||||
scope: workspace::Scope,
|
||||
test: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let started = std::time::Instant::now();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let settings = project.settings.effective();
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built) = {
|
||||
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
|
||||
let (root, cache, settings, module, cancel) =
|
||||
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load_launch_model(&scope);
|
||||
let model = load(&root, &cache, &settings);
|
||||
let built = if policy == BuildPolicy::NoBuild {
|
||||
None
|
||||
} else {
|
||||
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
|
||||
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
|
||||
};
|
||||
(model, built)
|
||||
})
|
||||
@@ -256,9 +249,9 @@ async fn resolve_launch_without_jdtls(
|
||||
let build_ms = started.elapsed().as_millis();
|
||||
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let project = project.clone();
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
match from_server {
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
@@ -267,14 +260,26 @@ async fn resolve_launch_without_jdtls(
|
||||
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
|
||||
}
|
||||
None => {
|
||||
if !is_maven_module(root, &model, &module) {
|
||||
let is_maven = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
|
||||
if !is_maven {
|
||||
return Err(IdeError::unavailable(
|
||||
"Cannot resolve the classpath: the Java language server does not report it \
|
||||
(java-analyzer/projectClasspath), and the module is not a Maven project",
|
||||
));
|
||||
}
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
|
||||
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
|
||||
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
|
||||
let classpath = compile::module_classpath(
|
||||
&project.root,
|
||||
&model,
|
||||
&module,
|
||||
test,
|
||||
local_repo,
|
||||
&project.build_cache_dir(),
|
||||
&cancel,
|
||||
)?;
|
||||
append_unique_class_paths(
|
||||
&mut class_paths,
|
||||
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
|
||||
@@ -282,8 +287,8 @@ async fn resolve_launch_without_jdtls(
|
||||
}
|
||||
}
|
||||
info.class_paths = class_paths;
|
||||
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
|
||||
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
@@ -440,10 +445,10 @@ fn apply_library_classpath(
|
||||
/// whether its JDT errors call for a clean rebuild (as its own launch would decide).
|
||||
async fn build_members(
|
||||
project: &std::sync::Arc<crate::Project>,
|
||||
scope: &std::sync::Arc<workspace::Scope>,
|
||||
model: &std::sync::Arc<BuildModel>,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
prefer_maven: bool,
|
||||
waiting: &cache::WaitingGuard,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<cache::Member>> {
|
||||
@@ -451,11 +456,10 @@ async fn build_members(
|
||||
if others.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
let joining = {
|
||||
let (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf());
|
||||
let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven)
|
||||
joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -496,7 +500,8 @@ fn joining_launches(
|
||||
others
|
||||
.into_iter()
|
||||
.filter(|o| {
|
||||
let is_maven = is_maven_module(root, model, &o.module);
|
||||
let is_maven =
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module));
|
||||
o.test == test
|
||||
&& matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make)
|
||||
&& compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor)
|
||||
|
||||
@@ -6,20 +6,14 @@ use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(super) struct Outputs {
|
||||
fingerprint: Option<LaunchFingerprint>,
|
||||
pub snapshot: PathBuf,
|
||||
pub originals: Vec<PathBuf>,
|
||||
/// Live output and snapshot metadata at publication. Older records may hold an
|
||||
/// incomplete copy and are rebuilt once (#5404).
|
||||
#[serde(default)]
|
||||
output_stamps: Option<Vec<OutputStamp>>,
|
||||
#[serde(skip)]
|
||||
pub failure: Option<String>,
|
||||
/// Whether this result replaces jdtls diagnostics with a clean Maven build or a
|
||||
@@ -29,93 +23,12 @@ pub(super) struct Outputs {
|
||||
}
|
||||
|
||||
impl Outputs {
|
||||
fn reusable(
|
||||
&self,
|
||||
fingerprint: &Option<LaunchFingerprint>,
|
||||
snapshots: &Path,
|
||||
output_dirs: impl Iterator<Item = PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
) -> bool {
|
||||
fn reusable(&self, fingerprint: &Option<LaunchFingerprint>, snapshots: &Path) -> bool {
|
||||
fingerprint.is_some()
|
||||
&& self.fingerprint == *fingerprint
|
||||
&& self.snapshot.parent() == Some(snapshots)
|
||||
&& !self.originals.is_empty()
|
||||
&& self.output_stamps.as_ref().is_some_and(|stamps| {
|
||||
stamps.len() == self.originals.len()
|
||||
&& output_dirs.eq(self.originals.iter().cloned())
|
||||
&& self.originals.iter().zip(stamps).enumerate().all(|(i, (dir, stamp))| {
|
||||
Contents::scan(dir, cancel).is_some_and(|live| live.stamp() == stamp.live)
|
||||
&& Contents::scan(&self.snapshot.join(i.to_string()), cancel)
|
||||
.is_some_and(|copy| copy.class_stamp() == stamp.snapshot_classes)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct OutputStamp {
|
||||
live: u64,
|
||||
// A launched app may write non-class files under its snapshot classpath root.
|
||||
snapshot_classes: u64,
|
||||
}
|
||||
|
||||
/// Relative paths, sizes and mtimes are enough to detect ordinary compiler rewrites
|
||||
/// without reading class or resource bytes.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Contents(Vec<(PathBuf, u64, SystemTime)>);
|
||||
|
||||
impl Contents {
|
||||
fn scan(root: &Path, cancel: &CancellationToken) -> Option<Self> {
|
||||
if !fs::metadata(root).ok()?.is_dir() {
|
||||
return None;
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
let mut pending = vec![root.to_path_buf()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
for entry in fs::read_dir(dir).ok()? {
|
||||
let entry = entry.ok()?;
|
||||
let meta = entry.metadata().ok()?;
|
||||
let path = entry.path();
|
||||
if meta.is_dir() {
|
||||
pending.push(path);
|
||||
} else {
|
||||
files.push((path.strip_prefix(root).ok()?.to_path_buf(), meta.len(), meta.modified().ok()?));
|
||||
}
|
||||
}
|
||||
}
|
||||
files.sort_unstable_by(|a, b| a.0.cmp(&b.0));
|
||||
Some(Self(files))
|
||||
}
|
||||
|
||||
fn stamp(&self) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
self.0.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn classes(&self) -> impl Iterator<Item = &(PathBuf, u64, SystemTime)> {
|
||||
self.0.iter().filter(|(path, _, _)| path.extension().is_some_and(|ext| ext == "class"))
|
||||
}
|
||||
|
||||
fn class_stamp(&self) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
for file in self.classes() {
|
||||
file.hash(&mut hasher);
|
||||
}
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn matches_copy(&self, copy: &Self) -> bool {
|
||||
// Copying preserves relative paths and sizes. Each tree has its own mtimes.
|
||||
self.0.len() == copy.0.len()
|
||||
&& self
|
||||
.0
|
||||
.iter()
|
||||
.zip(©.0)
|
||||
.all(|((path, len, _), (copied, copied_len, _))| path == copied && len == copied_len)
|
||||
&& (0..self.originals.len()).all(|i| self.snapshot.join(i.to_string()).is_dir())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,30 +64,6 @@ pub(super) struct Member {
|
||||
pub rebuild_on_jdt_errors: bool,
|
||||
}
|
||||
|
||||
/// Launches share a build only within the same workspace project's cache.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Sessions(Mutex<HashMap<PathBuf, Arc<Launches>>>);
|
||||
|
||||
pub(in crate::ops) struct Launches {
|
||||
pub waiting: Waiting,
|
||||
pub snapshots: Mutex<Session>,
|
||||
}
|
||||
|
||||
impl Sessions {
|
||||
pub(in crate::ops) fn for_cache(&self, cache: &Path) -> Arc<Launches> {
|
||||
self.0
|
||||
.lock()
|
||||
.entry(cache.to_owned())
|
||||
.or_insert_with(|| {
|
||||
Arc::new(Launches {
|
||||
waiting: Waiting::default(),
|
||||
snapshots: Mutex::new(Session::new(cache.to_owned())),
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Java launches from their start until their build: one launch's Maven run also builds
|
||||
/// the modules of launches still waiting (configurations started together, #3971).
|
||||
#[derive(Default)]
|
||||
@@ -367,23 +256,13 @@ impl Session {
|
||||
}
|
||||
if let Some(outputs) = previous.as_ref()
|
||||
&& policy != BuildPolicy::Rebuild
|
||||
&& let Some(maven) = &model.maven
|
||||
&& outputs.reusable(
|
||||
&before,
|
||||
&snapshots,
|
||||
compile::maven_launch_output_dirs(root, maven, module, test).into_iter().filter(|dir| dir.is_dir()),
|
||||
cancel,
|
||||
)
|
||||
&& !cancel.is_cancelled()
|
||||
&& outputs.reusable(&before, &snapshots)
|
||||
{
|
||||
tracing::info!(module = %module.display(), test, "Reusing Maven launch snapshot");
|
||||
let mut outputs = previous.unwrap();
|
||||
outputs.authoritative = true;
|
||||
return Ok(Ok(outputs));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// Retain a non-reusable record even on failure, so removing the final mixed
|
||||
// source still delegates to Maven to clean its old classes on the next launch.
|
||||
fs::create_dir_all(record.parent().unwrap())?;
|
||||
@@ -414,7 +293,6 @@ impl Session {
|
||||
let snapshot = tempfile::Builder::new().prefix("launch-").tempdir_in(&snapshots)?.keep();
|
||||
// Retain every new snapshot even if copying or publishing its record fails.
|
||||
self.unreferenced.push(snapshot.clone());
|
||||
let scanned: Vec<_> = originals.iter().map(|dir| Contents::scan(dir, cancel)).collect();
|
||||
for (i, source) in originals.iter().enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
@@ -425,43 +303,8 @@ impl Session {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// The fingerprint covers build inputs only. Another build (an external `mvn`) can
|
||||
// rewrite the outputs meanwhile without changing them (#5404): record the snapshot
|
||||
// only if the outputs held still through the copy and hold every module's classes.
|
||||
let copied: Option<Vec<Contents>> =
|
||||
(0..originals.len()).map(|i| Contents::scan(&snapshot.join(i.to_string()), cancel)).collect();
|
||||
let output_stamps: Option<Vec<OutputStamp>> = copied.as_ref().and_then(|copied| {
|
||||
originals
|
||||
.iter()
|
||||
.zip(&scanned)
|
||||
.zip(copied)
|
||||
.map(|((dir, before), copy)| {
|
||||
let before = before.as_ref()?;
|
||||
let live = Contents::scan(dir, cancel)?;
|
||||
(live == *before && before.matches_copy(copy))
|
||||
.then(|| OutputStamp { live: live.stamp(), snapshot_classes: copy.class_stamp() })
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let consistent = output_stamps.is_some();
|
||||
let complete = copied.as_ref().is_some_and(|copied| {
|
||||
compile::launch_required_class_dirs(root, model, &pending.module, test).iter().all(|dir| {
|
||||
originals.iter().position(|o| o == dir).is_some_and(|i| copied[i].classes().next().is_some())
|
||||
})
|
||||
});
|
||||
if failure.is_none() && !(consistent && complete) {
|
||||
tracing::warn!(
|
||||
module = %pending.module.display(),
|
||||
consistent,
|
||||
complete,
|
||||
"Maven outputs changed or lacked classes while copying the launch snapshot; it will not be reused"
|
||||
);
|
||||
}
|
||||
let mut outputs = Outputs { fingerprint: None, snapshot, originals, output_stamps, failure, authoritative };
|
||||
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after && consistent && complete {
|
||||
let mut outputs = Outputs { fingerprint: None, snapshot, originals, failure, authoritative };
|
||||
if outputs.failure.is_none() && pending.before.is_some() && pending.before == after {
|
||||
outputs.fingerprint = pending.before;
|
||||
write_record(&pending.record, &outputs)?;
|
||||
self.unreferenced.retain(|path| path != &outputs.snapshot);
|
||||
@@ -855,7 +698,7 @@ mod tests {
|
||||
assert!(reused.authoritative);
|
||||
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
|
||||
|
||||
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
|
||||
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
|
||||
let rebuilt = session
|
||||
.build(
|
||||
root,
|
||||
@@ -868,7 +711,6 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_ne!(rebuilt.snapshot, first.snapshot);
|
||||
assert!(rebuilt.authoritative);
|
||||
assert_eq!(fs::read_to_string(rebuilt.snapshot.join("0/Main.class")).unwrap(), "first");
|
||||
let calls = fs::read_to_string(root.join("calls")).unwrap();
|
||||
assert_eq!(calls.lines().count(), 2);
|
||||
assert!(calls.lines().last().unwrap().contains("clean"));
|
||||
@@ -890,6 +732,8 @@ mod tests {
|
||||
let second = build().unwrap();
|
||||
assert_eq!(snapshot, second.snapshot);
|
||||
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 1);
|
||||
fs::write(root.join("target/classes/Main.class"), "JDT stub").unwrap();
|
||||
assert_eq!(snapshot, build().unwrap().snapshot);
|
||||
assert_eq!(fs::read_to_string(snapshot.join("0/Main.class")).unwrap(), "first");
|
||||
fs::write(root.join("src/main/kotlin/Main.kt"), "updated").unwrap();
|
||||
let updated = build().unwrap();
|
||||
@@ -1025,7 +869,6 @@ mod tests {
|
||||
fingerprint: None,
|
||||
snapshot: retained.clone(),
|
||||
originals: Vec::new(),
|
||||
output_stamps: None,
|
||||
failure: None,
|
||||
authoritative: false,
|
||||
};
|
||||
@@ -1086,132 +929,6 @@ mod tests {
|
||||
drop(session);
|
||||
assert!(!outputs.snapshot.exists());
|
||||
}
|
||||
|
||||
/// An external `mvn` removes a dependency module's classes (`clean`) while this launch
|
||||
/// builds and copies the outputs, and compiles them again only after the copy (#5404).
|
||||
/// The sources never change, so only the copied outputs can tell the snapshot is broken.
|
||||
fn assert_outputs_cleaned_by_an_external_build_are_not_reused(clean: &str) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = reactor_fixture(root);
|
||||
let script = root.join("mvnw");
|
||||
let mut text = fs::read_to_string(&script).unwrap();
|
||||
text.push_str("echo resource > lib/target/classes/app.yml\n");
|
||||
text.push_str(&format!("if [ -f external-build ]; then {clean}; fi\n"));
|
||||
fs::write(&script, text).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(root.join("cache"));
|
||||
let a = root.join("a");
|
||||
fs::write(root.join("external-build"), "").unwrap();
|
||||
let first = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert!(!first.snapshot.join("1/Main.class").exists());
|
||||
// The external build finished: the classes are complete again, sources unchanged.
|
||||
fs::remove_file(root.join("external-build")).unwrap();
|
||||
fs::create_dir_all(root.join("lib/target/classes")).unwrap();
|
||||
fs::write(root.join("lib/target/classes/Main.class"), "lib").unwrap();
|
||||
let second = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_ne!(second.snapshot, first.snapshot, "the incomplete snapshot must not be reused");
|
||||
assert_eq!(fs::read_to_string(second.snapshot.join("1/Main.class")).unwrap(), "lib");
|
||||
assert_eq!(calls(root).len(), 2);
|
||||
let third = session.build(root, &model, &a, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_eq!(third.snapshot, second.snapshot, "a complete snapshot is reused");
|
||||
assert_eq!(calls(root).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_snapshot_of_classes_cleaned_by_an_external_build_is_not_reused() {
|
||||
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm lib/target/classes/Main.class");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_snapshot_missing_an_output_directory_removed_by_an_external_build_is_not_reused() {
|
||||
assert_outputs_cleaned_by_an_external_build_are_not_reused("rm -r lib/target/classes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partially_recompiled_dependency_snapshot_is_not_reused() {
|
||||
assert_outputs_cleaned_by_an_external_build_are_not_reused(
|
||||
"echo other > lib/target/classes/Other.class; rm lib/target/classes/Main.class",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_output_directory_invalidates_a_test_launch_snapshot() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(root.join("cache"));
|
||||
let mut build =
|
||||
|| session.build(root, &model, root, BuildOptions { test: true, ..Default::default() }, None, &cancel);
|
||||
let first = build().unwrap();
|
||||
assert_eq!(first.originals, [root.join("target/classes")]);
|
||||
fs::create_dir_all(root.join("target/test-classes")).unwrap();
|
||||
fs::write(root.join("target/test-classes/GeneratedTest.class"), "test").unwrap();
|
||||
let second = build().unwrap();
|
||||
assert_ne!(first.snapshot, second.snapshot);
|
||||
assert!(second.snapshot.join("0/GeneratedTest.class").is_file());
|
||||
assert_eq!(second.snapshot, build().unwrap().snapshot);
|
||||
assert_eq!(calls(root).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_without_output_stamps_is_rebuilt_once() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let model = fixture(root);
|
||||
let cancel = CancellationToken::new();
|
||||
let mut session = Session::new(root.join("cache"));
|
||||
let first = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
// A count-only record may still hold a partial copy.
|
||||
let record = root.join("cache/java-launch/records/main.json");
|
||||
let mut json: serde_json::Value = serde_json::from_slice(&fs::read(&record).unwrap()).unwrap();
|
||||
json.as_object_mut().unwrap().remove("output_stamps").unwrap();
|
||||
json["contents"] = serde_json::json!([{ "files": 1, "bytes": 5, "classes": 1 }]);
|
||||
fs::write(&record, serde_json::to_vec(&json).unwrap()).unwrap();
|
||||
let rebuilt = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_ne!(rebuilt.snapshot, first.snapshot);
|
||||
let reused = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_eq!(reused.snapshot, rebuilt.snapshot);
|
||||
// A file the launched app wrote under its classpath root keeps the snapshot.
|
||||
fs::write(reused.snapshot.join("0/app.log"), "log").unwrap();
|
||||
let kept = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_eq!(kept.snapshot, reused.snapshot);
|
||||
// A snapshot that lost a class since it was recorded is rebuilt.
|
||||
fs::remove_file(reused.snapshot.join("0/Main.class")).unwrap();
|
||||
let again = session.build(root, &model, root, BuildOptions::default(), None, &cancel).unwrap();
|
||||
assert_ne!(again.snapshot, reused.snapshot);
|
||||
assert_eq!(calls(root).len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contents_tell_a_rewritten_output_from_its_copy() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let classes = dir.path().join("classes");
|
||||
let cancel = CancellationToken::new();
|
||||
let scan = |path: &Path| Contents::scan(path, &cancel);
|
||||
fs::create_dir_all(classes.join("pkg")).unwrap();
|
||||
fs::write(classes.join("pkg/A.class"), "a").unwrap();
|
||||
fs::write(classes.join("app.yml"), "yml").unwrap();
|
||||
let class = fs::File::options().write(true).open(classes.join("pkg/A.class")).unwrap();
|
||||
let resource = fs::File::options().write(true).open(classes.join("app.yml")).unwrap();
|
||||
let before = SystemTime::now();
|
||||
resource.set_modified(before + std::time::Duration::from_secs(10)).unwrap();
|
||||
let contents = scan(&classes).unwrap();
|
||||
ide_vfs::copy(&classes, &dir.path().join("copy")).unwrap();
|
||||
assert!(contents.matches_copy(&scan(&dir.path().join("copy")).unwrap()));
|
||||
// A rewrite can preserve both the class file's size and the tree's newest mtime.
|
||||
class.set_modified(before + std::time::Duration::from_secs(1)).unwrap();
|
||||
let rewritten = scan(&classes).unwrap();
|
||||
assert!(contents.matches_copy(&rewritten));
|
||||
assert_ne!(rewritten.stamp(), contents.stamp());
|
||||
fs::rename(classes.join("pkg/A.class"), classes.join("pkg/B.class")).unwrap();
|
||||
let renamed = scan(&classes).unwrap();
|
||||
assert!(!rewritten.matches_copy(&renamed));
|
||||
assert_ne!(renamed.stamp(), rewritten.stamp());
|
||||
assert!(scan(&dir.path().join("missing")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_last_mixed_source_keeps_maven_delegation_after_failure() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -140,10 +140,7 @@ pub struct WorkspaceMember {
|
||||
}
|
||||
|
||||
/// The workspace projects outside the window's project folder, for Mark Directory as there.
|
||||
/// Each member's `for_project().layer(Project)` re-parses both settings layers and validates the
|
||||
/// merged tree against `Settings`; that stack-hungry work must not run on the IPC (main) thread,
|
||||
/// whose 1 MiB stack overflows on project open (STATUS_STACK_OVERFLOW).
|
||||
#[command(trust = always, desktop_body = spawn)]
|
||||
#[command(trust = always)]
|
||||
pub fn project_workspace_members(host: &Host, window: &str) -> IdeResult<Vec<WorkspaceMember>> {
|
||||
let project = host.project(window)?;
|
||||
Ok(project
|
||||
@@ -159,8 +156,7 @@ pub fn project_workspace_members(host: &Host, window: &str) -> IdeResult<Vec<Wor
|
||||
|
||||
/// Sets a `projectStructure.*` key in the settings of `root`, a project attached to the window's
|
||||
/// project (Mark Directory as there). Every open window holding that project follows.
|
||||
/// Like `project_workspace_members`, its `for_project` settings re-parse runs off the IPC thread.
|
||||
#[command(trust = always, desktop_body = spawn)]
|
||||
#[command(trust = always)]
|
||||
pub fn project_workspace_member_set(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
|
||||
@@ -3,7 +3,7 @@ use ide_core::IdeResult;
|
||||
use ide_dap::LaunchConfig;
|
||||
use ide_workspace::roots::RootKind;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
|
||||
let mut paths = vec![project.root.clone()];
|
||||
@@ -19,39 +19,6 @@ pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
|
||||
paths
|
||||
}
|
||||
|
||||
/// `paths` plus the folders added to the paths of the interpreter a launch uses (All
|
||||
/// Interpreters › Show Paths): `command` when it names a Python executable, else the
|
||||
/// interpreter of the project or workspace member at `near`. Run, Debug and the console
|
||||
/// resolve it the same way, so the same file imports the same modules in each.
|
||||
pub(super) fn with_user_paths(
|
||||
mut paths: Vec<PathBuf>,
|
||||
config_dir: &Path,
|
||||
project: &Project,
|
||||
command: Option<&str>,
|
||||
near: Option<&Path>,
|
||||
) -> Vec<PathBuf> {
|
||||
let named = command
|
||||
.filter(|c| ide_sdk::apply::is_python_command(c))
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_absolute() && p.is_file())
|
||||
.map(|p| ide_core::project_roots::resolve(&project.root, &p));
|
||||
let python = named.or_else(|| super::sdk::effective_python(config_dir, project, near));
|
||||
if let Some(python) = python {
|
||||
for path in ide_sdk::apply::interpreter_user_paths(&python, &project.settings.effective()) {
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
/// The interpreter a debugpy launch names (`"python": "<executable>"`), if it names one.
|
||||
pub(super) fn debug_python(config: &LaunchConfig) -> Option<String> {
|
||||
let extra: serde_json::Value = serde_json::from_str(config.extra_json.as_deref()?).ok()?;
|
||||
extra.get("python")?.as_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
pub(super) fn prepare_debug(config: &mut LaunchConfig, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
// Adapter-specific env takes precedence over the common launch fields in DAP.
|
||||
let mut extra: Option<serde_json::Value> = config.extra_json.as_deref().and_then(|s| serde_json::from_str(s).ok());
|
||||
|
||||
@@ -67,24 +67,20 @@ fn scan_roots(root: &Path, content_roots: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
roots
|
||||
}
|
||||
|
||||
/// Every mapping source of the project, for the request-path index. Walks the whole tree,
|
||||
/// so it runs on the blocking pool.
|
||||
pub async fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
/// Every mapping source of the project, for the request-path index.
|
||||
pub fn spring_route_sources(host: &Host, window: &str) -> IdeResult<Vec<RouteSource>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || {
|
||||
let mut out = Vec::new();
|
||||
for root in scan_roots(&project.root, project.content_roots()) {
|
||||
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
out.dedup_by(|a, b| a.path == b.path);
|
||||
match out.len() {
|
||||
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
|
||||
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
|
||||
}
|
||||
Ok(out)
|
||||
})
|
||||
.await
|
||||
let mut out = Vec::new();
|
||||
for root in scan_roots(&project.root, project.content_roots()) {
|
||||
out.extend(sources_in(&root, &project.search_excludes_in(&root)));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
out.dedup_by(|a, b| a.path == b.path);
|
||||
match out.len() {
|
||||
0 => tracing::warn!("spring routes: no mapping source under {:?}", project.root),
|
||||
n => tracing::info!("spring routes: {n} mapping sources under {:?}", project.root),
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -242,10 +242,7 @@ fn settings_only(
|
||||
.cloned()
|
||||
});
|
||||
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
|
||||
let jvm = matches!(config.kind.as_str(), "application" | "spring-boot");
|
||||
if jvm && member.is_some() && config.cwd.is_none() {
|
||||
config.cwd = Some(owner.into());
|
||||
} else if config.extras.module.is_none() && !jvm {
|
||||
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
|
||||
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
|
||||
}
|
||||
ide_run::scope::rebase(config, &project.root, None);
|
||||
@@ -488,17 +485,14 @@ async fn start_inner(
|
||||
}
|
||||
// A Python configuration pointing at a missing interpreter fails in the depth of
|
||||
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
|
||||
if is_python && Path::new(&config.command).components().count() > 1 {
|
||||
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
|
||||
if !executable.is_file() {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"The configured Python interpreter does not exist: {}\nSelect a working interpreter in Settings › Languages & Frameworks › Python Interpreter.",
|
||||
config.command
|
||||
)));
|
||||
}
|
||||
config.command = ide_core::ipc_path::to_ipc(&executable);
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
|
||||
&& !Path::new(&config.command).is_file()
|
||||
&& Path::new(&config.command).components().count() > 1
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"The configured Python interpreter does not exist: {}\nSelect a working interpreter in Settings › Languages & Frameworks › Python Interpreter.",
|
||||
config.command
|
||||
)));
|
||||
}
|
||||
if config.kind == "tomcat" {
|
||||
if host.processes.list().iter().any(|r| r.running && r.config_id == config.id) {
|
||||
@@ -521,21 +515,10 @@ async fn start_inner(
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
let mut python_paths = if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) };
|
||||
if is_python {
|
||||
let near = ide_run::scope::owner(&project.root, &config);
|
||||
python_paths = super::python::with_user_paths(
|
||||
python_paths,
|
||||
&host.config_dir,
|
||||
&project,
|
||||
Some(&config.command),
|
||||
Some(&near),
|
||||
);
|
||||
}
|
||||
let encoding = settings.console.encoding;
|
||||
let options = StartOptions {
|
||||
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
|
||||
python_paths,
|
||||
python_paths: if *root != project.root { vec![root.clone()] } else { super::python::paths(&project) },
|
||||
ruby_reporter: ruby_reporter_dir(host, &config),
|
||||
};
|
||||
project.require_trust()?;
|
||||
|
||||
@@ -120,49 +120,6 @@ pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) ->
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// `sys.path` of the interpreter `python`, for All Interpreters › Show Paths.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_sys_path(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
python: PathBuf,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let paths = ide_sdk::libraries::python_sys_path(&python, &cancel);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let paths = paths.ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"Cannot read sys.path of {}: the interpreter failed or did not answer in time",
|
||||
python.display()
|
||||
))
|
||||
})?;
|
||||
Ok(paths.iter().map(|p| p.as_path().into()).collect())
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
result?
|
||||
}
|
||||
|
||||
/// For each folder added to an interpreter's paths, why it stays off the import path
|
||||
/// (`None`: it is used). The folders may not be saved yet.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_user_path_problems(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
paths: Vec<String>,
|
||||
) -> IdeResult<Vec<Option<ide_sdk::apply::UserPathProblem>>> {
|
||||
host.require_trust_if_project(window)?;
|
||||
tokio::task::spawn_blocking(move || paths.iter().map(|p| ide_sdk::apply::user_path(p).err()).collect())
|
||||
.await
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// The interpreter of the workspace member `near` belongs to, else the project's.
|
||||
pub(crate) fn effective_python(
|
||||
config_dir: &std::path::Path,
|
||||
@@ -379,9 +336,7 @@ pub async fn sdk_locate_tools(
|
||||
.map_err(join_err)
|
||||
}
|
||||
|
||||
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry` / `pipenv`); output streams through
|
||||
/// `on_output`. `install_packages` also installs what the project's `Pipfile` declares (pipenv).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_create_venv(
|
||||
host: &Host,
|
||||
@@ -389,14 +344,13 @@ pub async fn sdk_python_create_venv(
|
||||
tool: ide_sdk::python::VenvTool,
|
||||
base: PathBuf,
|
||||
location: PathBuf,
|
||||
install_packages: bool,
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<Sdk> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
ide_sdk::python::create_venv(tool, &base, &location, install_packages, &cancel, &|line| {
|
||||
ide_sdk::python::create_venv(tool, &base, &location, &cancel, &|line| {
|
||||
let _ = on_output.send(line);
|
||||
})
|
||||
})
|
||||
@@ -482,77 +436,6 @@ mod tests {
|
||||
python
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_launch_takes_the_user_paths_of_the_interpreter_it_uses() {
|
||||
use crate::ops::python::{debug_python, with_user_paths};
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let (root, bare, own) = (base.join("project"), base.join("bare"), base.join("own"));
|
||||
let (for_main, for_own) = (base.join("for-main"), base.join("for-own"));
|
||||
for dir in [&root, &bare, &own, &for_main, &for_own] {
|
||||
std::fs::create_dir(dir).unwrap();
|
||||
}
|
||||
let (main_python, own_python) = (fake_venv(&root, ".venv"), fake_venv(&own, ".venv"));
|
||||
ide_workspace::workspace::Workspace::attach(&root, "ws", vec![root.clone(), bare.clone(), own.clone()])
|
||||
.unwrap();
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("local"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(|_| {})),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
let project = host.project("main").unwrap();
|
||||
let text = |p: &Path| p.to_string_lossy().into_owned();
|
||||
project
|
||||
.settings
|
||||
.set(
|
||||
ide_workspace::SettingsScope::Global,
|
||||
"languages.python.interpreterPaths",
|
||||
serde_json::json!({ text(&main_python): [text(&for_main)], text(&own_python): [text(&for_own)] }),
|
||||
)
|
||||
.unwrap();
|
||||
let paths = |command: Option<&str>, near: &Path| {
|
||||
with_user_paths(Vec::new(), &host.config_dir, &project, command, Some(near))
|
||||
};
|
||||
|
||||
// A member without a Python of its own runs on the primary project's interpreter;
|
||||
// a member with its own virtualenv on that one.
|
||||
assert_eq!(paths(None, &root), std::slice::from_ref(&for_main));
|
||||
assert_eq!(paths(None, &bare), std::slice::from_ref(&for_main));
|
||||
assert_eq!(paths(None, &own), std::slice::from_ref(&for_own));
|
||||
// The interpreter a launch names wins over where it runs; a manager's command does not name one.
|
||||
assert_eq!(paths(Some(&text(&own_python)), &bare), std::slice::from_ref(&for_own));
|
||||
assert_eq!(paths(Some("uv"), &own), std::slice::from_ref(&for_own));
|
||||
assert_eq!(paths(Some("python3"), &bare), std::slice::from_ref(&for_main));
|
||||
// What is already on the path is neither repeated nor dropped.
|
||||
let kept = with_user_paths(vec![root.clone(), for_main.clone()], &host.config_dir, &project, None, Some(&root));
|
||||
assert_eq!(kept, [root.clone(), for_main]);
|
||||
|
||||
// Debug resolves a relative command against its working directory before sending it.
|
||||
let debug_interpreter = bare.join("..").join(own_python.strip_prefix(&base).unwrap());
|
||||
let mut launch = ide_dap::LaunchConfig {
|
||||
name: "Python".into(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: Some(bare.as_path().into()),
|
||||
env: Default::default(),
|
||||
extra_json: Some(serde_json::json!({ "python": text(&debug_interpreter) }).to_string()),
|
||||
};
|
||||
assert_eq!(debug_python(&launch), Some(text(&debug_interpreter)));
|
||||
assert_eq!(paths(debug_python(&launch).as_deref(), &bare), [for_own]);
|
||||
launch.extra_json = Some(serde_json::json!({ "python": ["uv", "run", "python"] }).to_string());
|
||||
assert_eq!(debug_python(&launch), None);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_hand_picked_venv_is_resolved_like_a_detected_interpreter() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
@@ -666,6 +549,4 @@ ide_command::domain!(
|
||||
sdk_python_packages,
|
||||
sdk_python_pip,
|
||||
sdk_python_project_interpreters,
|
||||
sdk_python_sys_path,
|
||||
sdk_python_user_path_problems,
|
||||
);
|
||||
@@ -111,7 +111,7 @@ pub(crate) fn search_project(
|
||||
};
|
||||
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
let defaults = project.documents.file_defaults();
|
||||
let fallback = |path: &Path| defaults.fallback_for(path).map(str::to_owned);
|
||||
let decode = |path: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, defaults.fallback_for(path));
|
||||
let mut total = SearchSummary::default();
|
||||
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
|
||||
let mut remaining = query.clone();
|
||||
@@ -139,7 +139,7 @@ pub(crate) fn search_project(
|
||||
&remaining,
|
||||
Some(&filter),
|
||||
Some(&literals),
|
||||
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), fallback: &fallback },
|
||||
ide_search::TextSource { overlay: &|p| project.documents.search_text_of(p), decode: &decode },
|
||||
cancel,
|
||||
&|mut file| {
|
||||
if let Some(prefix) = &prefix {
|
||||
@@ -188,11 +188,6 @@ pub(crate) fn rebase_masks(masks: &[String], prefix: &str) -> Vec<String> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn search_leaves_unread_the_texts_the_parser_does_not_take() {
|
||||
assert_eq!(ide_search::MAX_LITERALS_TEXT_BYTES, ide_language::MAX_PARSE_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_follow_the_root_they_search() {
|
||||
let masks = vec![".wt/a/src/**, src/**".into(), "*.rs".into(), "!.wt/a/out/**".into(), "**/build/**".into()];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{Channel, Emit};
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeResult, IpcBytes, TerminalId};
|
||||
use ide_core::{IdeResult, TerminalId};
|
||||
use ide_terminal::{TerminalInfo, TerminalOptions};
|
||||
|
||||
mod images;
|
||||
@@ -9,7 +9,7 @@ mod images;
|
||||
const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn term_store_image(host: &Host, id: TerminalId, data: IpcBytes, mime: String) -> IdeResult<String> {
|
||||
pub async fn term_store_image(host: &Host, id: TerminalId, data: Vec<u8>, mime: String) -> IdeResult<String> {
|
||||
if data.len() > MAX_IMAGE_BYTES {
|
||||
return Err(ide_core::IdeError::invalid("image is too large to paste (limit 20 MB)"));
|
||||
}
|
||||
@@ -201,11 +201,10 @@ mod tests {
|
||||
project_environment: false,
|
||||
});
|
||||
let id = TerminalId::next();
|
||||
let error =
|
||||
term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1].into(), "image/png".into()).await.unwrap_err();
|
||||
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES + 1], "image/png".into()).await.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::InvalidInput);
|
||||
assert_eq!(error.message, "image is too large to paste (limit 20 MB)");
|
||||
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES].into(), "image/png".into()).await.unwrap_err();
|
||||
let error = term_store_image(&host, id, vec![0; MAX_IMAGE_BYTES], "image/png".into()).await.unwrap_err();
|
||||
assert_eq!(error.message, "terminal session not found");
|
||||
assert!(!host.data_dir.join("terminal-images").exists());
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ pub(crate) fn merge(server: Vec<InlayHint>, plugin: Vec<PluginInlayHint>, range:
|
||||
padding_right: h.padding_right,
|
||||
tooltip: h.tooltip,
|
||||
parts: Vec::new(),
|
||||
text_edits: Vec::new(),
|
||||
}));
|
||||
out.sort_by_key(|h| (h.position.line, h.position.col));
|
||||
out
|
||||
@@ -51,7 +50,6 @@ mod tests {
|
||||
padding_right: true,
|
||||
tooltip: None,
|
||||
parts: Vec::new(),
|
||||
text_edits: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,8 +51,10 @@ pub struct Project {
|
||||
pub(crate) member_excludes: MemberExcludes,
|
||||
/// Per-project cache directory (build tool sync results…).
|
||||
pub cache_dir: PathBuf,
|
||||
/// Pending launches and retained snapshots, scoped to each workspace project.
|
||||
pub(crate) java_launches: crate::ops::java::cache::Sessions,
|
||||
/// Superseded launch snapshots retained until this project session ends.
|
||||
pub(crate) java_launch_snapshots: Mutex<crate::ops::java::cache::Session>,
|
||||
/// Java launches waiting for their build, which can share one Maven run.
|
||||
pub(crate) java_launches_waiting: crate::ops::java::cache::Waiting,
|
||||
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
|
||||
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
|
||||
/// Database tool window: data sources and their connections.
|
||||
@@ -200,12 +202,7 @@ impl Host {
|
||||
// resolve imports into them. A container target already supplies its own
|
||||
// `extraPaths` (the site-packages snapshot); don't mix local sources into it.
|
||||
if !container_python {
|
||||
let mut paths = python_dependency_roots(&effective, root);
|
||||
// The folders added to the paths of the interpreter this server analyses with.
|
||||
if let Some(python) = ide_sdk::apply::python_server_interpreter(root, server_root, &effective) {
|
||||
paths.extend(ide_sdk::apply::interpreter_user_paths(&python, &effective));
|
||||
}
|
||||
ide_sdk::apply::configure_python_extra_paths(cfg, &paths);
|
||||
ide_sdk::apply::configure_python_extra_paths(cfg, &python_dependency_roots(&effective, root));
|
||||
}
|
||||
if cfg.name == "jdtls" {
|
||||
// A workspace member keeps its build model under its own key (Build Project).
|
||||
@@ -644,7 +641,10 @@ impl Host {
|
||||
detected_roots,
|
||||
member_excludes,
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launches: Default::default(),
|
||||
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
|
||||
self.local_data_dir.join("cache").join(&project_key).join("build"),
|
||||
)),
|
||||
java_launches_waiting: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
@@ -891,7 +891,10 @@ impl Host {
|
||||
detected_roots: Arc::default(),
|
||||
member_excludes: Arc::default(),
|
||||
cache_dir: self.local_data_dir.join("cache").join(&project_key),
|
||||
java_launches: Default::default(),
|
||||
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
|
||||
self.local_data_dir.join("cache").join(&project_key).join("build"),
|
||||
)),
|
||||
java_launches_waiting: Default::default(),
|
||||
kotlin_debug_notices: Mutex::default(),
|
||||
db,
|
||||
http_history,
|
||||
|
||||
@@ -27,8 +27,7 @@ use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// 3: binary arguments (`IpcBytes`) are base64 strings, not arrays of numbers.
|
||||
pub const PROTOCOL_VERSION: u32 = 3;
|
||||
pub const PROTOCOL_VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -24,8 +24,8 @@ fn remember_codex_modes(data: &Path, root: &Path) {
|
||||
std::fs::write(data.join("agents/models.json"), modes.to_string()).unwrap();
|
||||
}
|
||||
|
||||
async fn codex_mode(host: &Host) -> Option<String> {
|
||||
let providers = ide_host::ops::agent::agent_providers(host, "main").await.unwrap();
|
||||
fn codex_mode(host: &Host) -> Option<String> {
|
||||
let providers = ide_host::ops::agent::agent_providers(host, "main").unwrap();
|
||||
let codex = providers.into_iter().find(|p| p.id == "codex").expect("codex is listed");
|
||||
codex.config.into_iter().find(|o| o.id == "mode").and_then(|o| o.current)
|
||||
}
|
||||
@@ -54,10 +54,10 @@ async fn new_tasks_start_asking_for_approval_when_the_user_chose_so() {
|
||||
}));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
assert_eq!(codex_mode(&host).await.as_deref(), Some("ask"));
|
||||
assert_eq!(codex_mode(&host).as_deref(), Some("ask"));
|
||||
|
||||
// The default keeps starting new tasks without approvals.
|
||||
std::fs::remove_file(config.join("settings.toml")).unwrap();
|
||||
host.project("main").unwrap().settings.reload();
|
||||
assert_eq!(codex_mode(&host).await.as_deref(), Some("full-access"));
|
||||
assert_eq!(codex_mode(&host).as_deref(), Some("full-access"));
|
||||
}
|
||||
@@ -30,8 +30,8 @@ fn open(host: &Host, tmp: &tempfile::TempDir) {
|
||||
host.open_project("main", &root).unwrap();
|
||||
}
|
||||
|
||||
async fn env_of(host: &Host, id: &str) -> BTreeMap<String, String> {
|
||||
let providers = ide_host::ops::agent::agent_providers(host, "main").await.unwrap();
|
||||
fn env_of(host: &Host, id: &str) -> BTreeMap<String, String> {
|
||||
let providers = ide_host::ops::agent::agent_providers(host, "main").unwrap();
|
||||
providers.into_iter().find(|p| p.id == id).unwrap_or_else(|| panic!("{id}")).env
|
||||
}
|
||||
|
||||
@@ -60,8 +60,8 @@ async fn agent_environment_values_stay_out_of_agent_files() {
|
||||
|
||||
let host = self::host(tmp.path());
|
||||
open(&host, &tmp);
|
||||
assert_eq!(env_of(&host, "claude").await, env);
|
||||
assert_eq!(env_of(&host, "mine").await, env);
|
||||
assert_eq!(env_of(&host, "claude"), env);
|
||||
assert_eq!(env_of(&host, "mine"), env);
|
||||
ide_host::ops::agent::remove_custom_agent(&host, "main", "mine".into()).unwrap();
|
||||
ide_host::ops::agent::agent_set_env(&host, "main", "claude".into(), BTreeMap::new()).unwrap();
|
||||
assert_eq!(host.agent_secrets.keys("agent/"), Vec::<String>::new());
|
||||
@@ -81,6 +81,6 @@ async fn values_in_agent_files_move_to_the_credential_store() {
|
||||
let host = host(tmp.path());
|
||||
open(&host, &tmp);
|
||||
assert_eq!(files_containing(tmp.path(), VALUE), Vec::<PathBuf>::new());
|
||||
assert_eq!(env_of(&host, "mine").await, BTreeMap::from([("TOKEN".to_owned(), VALUE.to_owned())]));
|
||||
assert_eq!(env_of(&host, "mine"), BTreeMap::from([("TOKEN".to_owned(), VALUE.to_owned())]));
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
//! Binary command arguments over the remote protocol: base64 strings, not arrays of numbers.
|
||||
|
||||
use ide_core::{IpcBytes, NullSink};
|
||||
use ide_host::rpc::{self, Dispatcher, Invoke};
|
||||
use ide_host::{Host, HostConfig};
|
||||
use ide_jsonrpc::{Handler, Peer};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
struct Client;
|
||||
|
||||
impl Handler for Client {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
|
||||
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect(base: &std::path::Path) -> Peer {
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |window| window,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}));
|
||||
let (client_io, server_io) = tokio::io::duplex(1 << 20);
|
||||
let (sr, sw) = tokio::io::split(server_io);
|
||||
tokio::spawn(rpc::serve(host, Dispatcher::standard(), Arc::new(OnceLock::new()), sr, sw));
|
||||
let (cr, cw) = tokio::io::split(client_io);
|
||||
Peer::connect(cr, cw, Arc::new(Client))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn file_bytes_cross_the_protocol_as_base64() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let peer = connect(tmp.path()).await;
|
||||
let bytes: Vec<u8> = (0..=255).cycle().take(3 * 1024 * 1024 + 1).collect();
|
||||
let path = tmp.path().join("image.bin");
|
||||
|
||||
let args = json!({ "path": path, "data": IpcBytes(bytes.clone()) });
|
||||
assert!(args["data"].is_string());
|
||||
// Measure the envelope separately so the assertion is independent of the temp directory.
|
||||
let envelope = serde_json::to_vec(&json!({ "path": path, "data": "" })).unwrap();
|
||||
let body = serde_json::to_vec(&args).unwrap();
|
||||
assert_eq!(body.len(), envelope.len() + bytes.len().div_ceil(3) * 4);
|
||||
|
||||
let call = Invoke { window: "main".into(), cmd: "fs_create_file_bytes".into(), args };
|
||||
peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply).unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), bytes);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn an_array_of_numbers_is_not_accepted_as_bytes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let peer = connect(tmp.path()).await;
|
||||
let path = tmp.path().join("old.bin");
|
||||
let call = Invoke {
|
||||
window: "main".into(),
|
||||
cmd: "fs_create_file_bytes".into(),
|
||||
args: json!({ "path": path, "data": [1, 2, 3] }),
|
||||
};
|
||||
let error = peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply).unwrap_err();
|
||||
assert!(error.message.contains("argument data"), "{error:?}");
|
||||
assert!(!path.exists());
|
||||
}
|
||||
@@ -71,10 +71,9 @@ async fn external_maven_link_persists_reloads_and_unlink_keeps_files() {
|
||||
}
|
||||
|
||||
/// The language server's Maven import roots once `ready` holds: a settings change refreshes them in
|
||||
/// the background. The deadline is generous because a loaded CI runner can take well over a few
|
||||
/// seconds to re-import.
|
||||
/// the background.
|
||||
async fn import_roots(host: &Host, ready: impl Fn(&[std::path::PathBuf]) -> bool) -> Vec<std::path::PathBuf> {
|
||||
for _ in 0..600 {
|
||||
for _ in 0..200 {
|
||||
let roots = host.project("main").unwrap().lsp.jdtls_import_roots();
|
||||
if ready(&roots) {
|
||||
return roots;
|
||||
|
||||
@@ -74,13 +74,6 @@ async fn serves_projects_files_documents_search_and_runs() {
|
||||
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
|
||||
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
|
||||
|
||||
let scratch_path = base.join("data/scratches");
|
||||
assert!(!scratch_path.exists());
|
||||
let expected = serde_json::to_value(ide_core::IpcPath::from(scratch_path.clone())).unwrap();
|
||||
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
|
||||
assert!(scratch_path.is_dir());
|
||||
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
|
||||
|
||||
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
|
||||
assert_eq!(opened["name"], "demo");
|
||||
assert_eq!(opened["trusted"], false);
|
||||
|
||||
@@ -21,7 +21,7 @@ async fn storage_requires_a_registered_terminal() {
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1].into(), "image/png".into()).await.is_err());
|
||||
assert!(ops::term::term_store_image(&host, TerminalId::next(), vec![1], "image/png".into()).await.is_err());
|
||||
assert!(!data_dir.join("terminal-images").exists());
|
||||
let terminal = host
|
||||
.terminals
|
||||
@@ -41,15 +41,11 @@ async fn storage_requires_a_registered_terminal() {
|
||||
)
|
||||
.unwrap();
|
||||
for mime in ["image/png", "audio/mpeg", "video/mp4"] {
|
||||
let path = ops::term::term_store_image(&host, terminal.id, vec![1, 2, 3].into(), mime.into()).await.unwrap();
|
||||
let path = ops::term::term_store_image(&host, terminal.id, vec![1, 2, 3], mime.into()).await.unwrap();
|
||||
assert_eq!(std::fs::read(path).unwrap(), [1, 2, 3]);
|
||||
}
|
||||
assert!(
|
||||
ops::term::term_store_image(&host, terminal.id, vec![1].into(), "application/octet-stream".into())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(ops::term::term_store_image(&host, terminal.id, vec![1], "application/octet-stream".into()).await.is_err());
|
||||
host.terminals.kill(terminal.id).unwrap();
|
||||
assert!(ops::term::term_store_image(&host, terminal.id, vec![4].into(), "image/png".into()).await.is_err());
|
||||
assert!(ops::term::term_store_image(&host, terminal.id, vec![4], "image/png".into()).await.is_err());
|
||||
assert_eq!(std::fs::read_dir(data_dir.join("terminal-images")).unwrap().count(), 3);
|
||||
}
|
||||
@@ -6,107 +6,6 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn java_launch_builds_the_owning_workspace_reactor() {
|
||||
use ide_run::BuildPolicy;
|
||||
use ide_workspace::{SettingsStore, settings::SettingsScope};
|
||||
use std::{fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let config_dir = base.join("config");
|
||||
let primary = base.join("primary");
|
||||
let sibling = base.join("spring");
|
||||
let nested = primary.join("nested");
|
||||
let roots = [&primary, &sibling, &nested];
|
||||
for (i, root) in roots.into_iter().enumerate() {
|
||||
fs::create_dir_all(root.join("app")).unwrap();
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
format!("<project><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version><packaging>pom</packaging><modules><module>app</module></modules></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("app/pom.xml"),
|
||||
format!("<project><parent><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version></parent><artifactId>app</artifactId></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
let wrapper = root.join("mvnw");
|
||||
fs::write(
|
||||
&wrapper,
|
||||
r#"#!/bin/sh
|
||||
set -eu
|
||||
printf '%s\n' "$*" >> calls
|
||||
mkdir -p app/target/classes
|
||||
case " $* " in *" test-compile "*) mkdir -p app/target/test-classes;; esac
|
||||
scope=runtime
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-Dmdep.includeScope=*) scope="${arg#*=}";;
|
||||
esac
|
||||
done
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-Dmdep.outputFile=*)
|
||||
touch "app/$scope.jar"
|
||||
printf '%s\n' "$PWD/app/$scope.jar" > "app/${arg#*=}";;
|
||||
esac
|
||||
done
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(wrapper, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
SettingsStore::load(&config_dir, Some(root))
|
||||
.set(
|
||||
SettingsScope::Project,
|
||||
"languages.java.maven.activeProfiles",
|
||||
serde_json::json!(format!("member-{i}")),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
// Exercise the build-tool classpath fallback without starting an installed server.
|
||||
let global = SettingsStore::load(&config_dir, None);
|
||||
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
|
||||
global
|
||||
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
|
||||
.unwrap();
|
||||
}
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir,
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
for root in roots {
|
||||
host.trust.decide(root, true, false).unwrap();
|
||||
}
|
||||
host.open_project("main", &primary).unwrap();
|
||||
for root in [&sibling, &nested] {
|
||||
ops::project::attach_workspace(&host, "main", root).unwrap();
|
||||
}
|
||||
for (index, root) in roots.into_iter().enumerate() {
|
||||
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
|
||||
let test = index != 0;
|
||||
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
|
||||
.await
|
||||
.unwrap();
|
||||
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
|
||||
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
|
||||
let calls = fs::read_to_string(root.join("calls")).unwrap();
|
||||
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
|
||||
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
|
||||
assert!(calls.contains("dependency:build-classpath"), "{calls}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_directories() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
use ide_core::{Range, SymbolKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Bit set of the (lower-cased) ASCII letters/digits/punctuation present in a
|
||||
@@ -588,9 +588,6 @@ pub(crate) struct IndexData {
|
||||
free: Vec<u32>,
|
||||
pub file_count: u32,
|
||||
pub symbol_count: u32,
|
||||
/// Full passes over `by_path` made to remove folders.
|
||||
#[cfg(test)]
|
||||
pub key_scans: usize,
|
||||
}
|
||||
|
||||
impl IndexData {
|
||||
@@ -795,15 +792,9 @@ impl IndexData {
|
||||
Some(old)
|
||||
}
|
||||
|
||||
/// Removes every file at or below any of `dirs` in a single pass over the
|
||||
/// indexed paths; returns their paths.
|
||||
pub(crate) fn remove_trees(&mut self, dirs: &HashSet<PathBuf>) -> Vec<PathBuf> {
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.key_scans += 1;
|
||||
}
|
||||
let doomed: Vec<PathBuf> =
|
||||
self.by_path.keys().filter(|p| p.ancestors().any(|a| dirs.contains(a))).cloned().collect();
|
||||
/// Removes every file at or below `dir`; returns their paths.
|
||||
pub(crate) fn remove_tree(&mut self, dir: &Path) -> Vec<PathBuf> {
|
||||
let doomed: Vec<PathBuf> = self.by_path.keys().filter(|p| p.starts_with(dir)).cloned().collect();
|
||||
doomed.into_iter().filter(|p| self.remove(p).is_some()).collect()
|
||||
}
|
||||
|
||||
@@ -876,10 +867,6 @@ mod tests {
|
||||
FileEntry::new(PathBuf::from("/r").join(path), path.to_owned(), record)
|
||||
}
|
||||
|
||||
fn path_set(paths: &[&str]) -> HashSet<PathBuf> {
|
||||
paths.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
fn insert(d: &mut IndexData, path: &str, symbols: usize) {
|
||||
let (e, s) = entry(path, symbols);
|
||||
d.insert(e, s);
|
||||
@@ -957,25 +944,11 @@ mod tests {
|
||||
d.remove(Path::new("/r/a/b/c.rs"));
|
||||
assert!(!d.dirs.contains_key("a/b/"));
|
||||
assert_consistent(&d);
|
||||
d.remove_trees(&path_set(&["/r/a"]));
|
||||
d.remove_tree(Path::new("/r/a"));
|
||||
assert!(d.dirs.is_empty());
|
||||
assert_consistent(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_trees_takes_only_files_below_the_given_folders() {
|
||||
let mut d = IndexData::default();
|
||||
for path in ["a/x.rs", "a/b/y.rs", "ab/z.rs", "c/d/w.rs", "c/keep.rs", "top.rs"] {
|
||||
insert(&mut d, path, 1);
|
||||
}
|
||||
let mut gone = d.remove_trees(&path_set(&["/r/a", "/r/a/b", "/r/c/d", "/r/missing"]));
|
||||
gone.sort();
|
||||
assert_eq!(gone, ["/r/a/b/y.rs", "/r/a/x.rs", "/r/c/d/w.rs"].map(PathBuf::from));
|
||||
assert_eq!(d.file_count, 3);
|
||||
assert!(["/r/ab/z.rs", "/r/c/keep.rs", "/r/top.rs"].iter().all(|p| d.get(Path::new(p)).is_some()));
|
||||
assert_consistent(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_replace_remove_keep_counts() {
|
||||
let mut d = IndexData::default();
|
||||
@@ -991,7 +964,7 @@ mod tests {
|
||||
insert(&mut d, "d.rs", 0);
|
||||
assert_eq!(d.files.len(), 2, "slot reused");
|
||||
assert_consistent(&d);
|
||||
assert_eq!(d.remove_trees(&path_set(&["/r/a"])), vec![PathBuf::from("/r/a/b.rs")]);
|
||||
assert_eq!(d.remove_tree(Path::new("/r/a")), vec![PathBuf::from("/r/a/b.rs")]);
|
||||
assert_eq!((d.file_count, d.symbol_count), (1, 0));
|
||||
let e = d.get(Path::new("/r/d.rs")).unwrap();
|
||||
assert_eq!((e.name(), e.dir()), ("d.rs", ""));
|
||||
@@ -1066,7 +1039,7 @@ mod tests {
|
||||
insert(&mut d, "a/b/two.rs", 3);
|
||||
insert(&mut d, "a/three.rs", 1);
|
||||
insert(&mut d, "elsewhere/four.rs", 1);
|
||||
assert_eq!(d.remove_trees(&path_set(&["/r/a"])).len(), 3);
|
||||
assert_eq!(d.remove_tree(Path::new("/r/a")).len(), 3);
|
||||
assert_consistent(&d);
|
||||
assert_eq!(d.hot.rows.iter().filter(|r| r.live).count(), 1);
|
||||
assert!(d.hot.row(0).is_none(), "removed slots have no live row");
|
||||
|
||||
@@ -900,21 +900,16 @@ impl Shared {
|
||||
|
||||
// Removals first; a path removed then re-created shows up in `changed` too.
|
||||
let mut deletes = Vec::new();
|
||||
// Paths that are not indexed files: removed directories (or files that were never indexed).
|
||||
let mut gone_dirs = HashSet::new();
|
||||
for path in removed {
|
||||
if path.exists() {
|
||||
changed.push(path);
|
||||
continue;
|
||||
}
|
||||
if self.data.write().remove(&path).is_some() {
|
||||
deletes.extend(filter.store_key(&path));
|
||||
} else {
|
||||
gone_dirs.insert(path);
|
||||
}
|
||||
}
|
||||
if !gone_dirs.is_empty() {
|
||||
let gone = self.data.write().remove_trees(&gone_dirs);
|
||||
let mut d = self.data.write();
|
||||
let gone = match d.remove(&path) {
|
||||
Some(_) => vec![path],
|
||||
None => d.remove_tree(&path),
|
||||
};
|
||||
deletes.extend(gone.iter().filter_map(|p| filter.store_key(p)));
|
||||
}
|
||||
if !deletes.is_empty() {
|
||||
@@ -1161,69 +1156,6 @@ mod metric_tests {
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_subtree_costs_one_key_scan_per_batch() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
let mut batch = std::collections::BTreeSet::new();
|
||||
for i in 0..40 {
|
||||
let sub = root.join("gone").join(format!("p{}", i / 10));
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
std::fs::write(sub.join(format!("f{i}.txt")), "x").unwrap();
|
||||
batch.extend([sub.join(format!("f{i}.txt")), sub, root.join("gone")]);
|
||||
}
|
||||
std::fs::write(root.join("keep.txt"), "x").unwrap();
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!(shared.data.read().file_count, 41);
|
||||
|
||||
std::fs::remove_dir_all(root.join("gone")).unwrap();
|
||||
shared.data.write().key_scans = 0;
|
||||
// The watcher's batches are sorted: each directory precedes its children.
|
||||
shared.process(vec![Job::Removed(batch.into_iter().collect())]);
|
||||
|
||||
let data = shared.data.read();
|
||||
assert_eq!(data.file_count, 1);
|
||||
assert!(data.get(&root.join("keep.txt")).is_some());
|
||||
assert!(data.key_scans <= 1, "{} full key scans for one removed subtree", data.key_scans);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_removal_handles_files_dirs_recreated_and_unknown_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
for rel in ["gone/a.txt", "gone/deep/b.txt", "kept/c.txt", "redo/d.txt", "redo/e.txt", "lone.txt", "stay.txt"] {
|
||||
let p = root.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "x").unwrap();
|
||||
}
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!(shared.data.read().file_count, 7);
|
||||
|
||||
std::fs::remove_dir_all(root.join("gone")).unwrap();
|
||||
std::fs::remove_file(root.join("lone.txt")).unwrap();
|
||||
std::fs::remove_file(root.join("redo/e.txt")).unwrap();
|
||||
let outside = root.join("never/indexed/f.txt");
|
||||
let removed = [
|
||||
root.join("gone/deep/b.txt"),
|
||||
root.join("gone"),
|
||||
root.join("gone/deep"),
|
||||
root.join("lone.txt"),
|
||||
root.join("redo"),
|
||||
root.join("redo/e.txt"),
|
||||
root.join("stay.txt"),
|
||||
outside,
|
||||
];
|
||||
shared.process(vec![Job::Removed(removed.to_vec())]);
|
||||
|
||||
let data = shared.data.read();
|
||||
let mut left: Vec<_> = data.paths().map(|p| p.strip_prefix(&root).unwrap().to_owned()).collect();
|
||||
left.sort();
|
||||
// `redo` and `stay.txt` still exist: they are re-read, not dropped.
|
||||
assert_eq!(left, ["kept/c.txt", "redo/d.txt", "stay.txt"].map(PathBuf::from));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_scan_counts_full_batch_and_tail() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -968,7 +968,6 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
|
||||
_ => InlayKind::Other,
|
||||
};
|
||||
let tooltip = h.tooltip.map(tooltip_text);
|
||||
let text_edits = conv.text_edits(path, h.text_edits.unwrap_or_default());
|
||||
InlayHint {
|
||||
position: conv.pos(path, h.position),
|
||||
label,
|
||||
@@ -977,7 +976,6 @@ pub fn inlay_hint(conv: &Conv, path: &Path, h: lsp::InlayHint) -> InlayHint {
|
||||
padding_right: h.padding_right.unwrap_or(false),
|
||||
tooltip,
|
||||
parts,
|
||||
text_edits,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1591,23 +1589,6 @@ mod tests {
|
||||
assert!(h.padding_left && !h.padding_right);
|
||||
assert_eq!(h.parts.len(), 2);
|
||||
assert!(h.parts.iter().all(|p| p.location.is_none()));
|
||||
assert!(h.text_edits.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inlay_text_edits_carry_over() {
|
||||
let conv = Conv::utf16();
|
||||
let h: lsp::InlayHint = serde_json::from_value(json!({
|
||||
"position": {"line": 2, "character": 5}, "label": ": Any", "kind": 1,
|
||||
"textEdits": [
|
||||
{"range": {"start": {"line": 2, "character": 5}, "end": {"line": 2, "character": 5}}, "newText": ": Any"},
|
||||
{"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}}, "newText": "from typing import Any\n"}
|
||||
]
|
||||
}))
|
||||
.unwrap();
|
||||
let h = inlay_hint(&conv, Path::new("/a"), h);
|
||||
let edits: Vec<_> = h.text_edits.iter().map(|e| (e.range.start, e.new_text.as_str())).collect();
|
||||
assert_eq!(edits, [(p(2, 5), ": Any"), (p(0, 0), "from typing import Any\n")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
||||
+28
-62
@@ -8,12 +8,10 @@
|
||||
use crate::LspManager;
|
||||
use crate::server::{Running, Server};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::event::LspRefreshKind;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -648,8 +646,7 @@ impl LspManager {
|
||||
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
|
||||
/// change, a Maven sync, other Maven profiles), but does not check open documents
|
||||
/// again against the new classpath: their errors would stay until the next edit.
|
||||
/// Open editors may have cached empty tokens or inheritance results during the import.
|
||||
/// Attach generated Maven sources before refreshing either, so both see the new classpath.
|
||||
/// Generated Maven sources are attached first, so that recheck sees them.
|
||||
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
|
||||
let uris: Vec<String> = self
|
||||
.docs
|
||||
@@ -666,9 +663,6 @@ impl LspManager {
|
||||
self.runtime.spawn(async move {
|
||||
let Some(run) = server.running_gen(generation) else { return };
|
||||
mgr.sync_generated_sources(&server, &run).await;
|
||||
for kind in [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance] {
|
||||
mgr.sink().emit(ide_core::IdeEvent::LspRefresh { server: server.id, kind });
|
||||
}
|
||||
for uri in uris {
|
||||
let params =
|
||||
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
|
||||
@@ -852,65 +846,37 @@ impl LspManager {
|
||||
}
|
||||
}
|
||||
|
||||
fn running_java_projects<'a>(&self, files: &'a [PathBuf]) -> Vec<(Running, Vec<&'a Path>)> {
|
||||
/// Tells jdtls the build files of `uris` changed (`java/projectConfigurationsUpdate`),
|
||||
/// so it re-imports their projects (e.g. after `~/.m2` gained an artifact it could
|
||||
/// not resolve). Best-effort: skipped while jdtls is not already running.
|
||||
pub async fn java_update_project_configs(&self, path: &Path, uris: Vec<String>) -> IdeResult<()> {
|
||||
if uris.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let java = LanguageId::new("java");
|
||||
let mut targets = HashMap::new();
|
||||
for file in files {
|
||||
if let Some(server) = self.servers_for(&java, file).into_iter().find(|s| s.name == SERVER)
|
||||
&& let Some(run) = server.running()
|
||||
{
|
||||
let (_, paths) = targets.entry(server.id).or_insert_with(|| (run, Vec::new()));
|
||||
paths.push(file.as_path());
|
||||
}
|
||||
}
|
||||
targets.into_values().collect()
|
||||
let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(run) = server.running() else { return Ok(()) };
|
||||
let identifiers: Vec<Value> = uris.iter().map(|u| json!({ "uri": u })).collect();
|
||||
run.peer
|
||||
.notify("java/projectConfigurationsUpdate", json!({ "identifiers": identifiers }))
|
||||
.map_err(|e| crate::rpc_err(&server.name, "java/projectConfigurationsUpdate", e))
|
||||
}
|
||||
|
||||
/// Re-imports projects even when their build files did not change. Wait for
|
||||
/// the Maven configuration job when a source refresh depends on its binaries.
|
||||
pub async fn java_update_project_configs(
|
||||
&self,
|
||||
files: &[PathBuf],
|
||||
wait: Option<&CancellationToken>,
|
||||
) -> IdeResult<()> {
|
||||
const UPDATE: &str = "openidea.java.updateProjectConfigurations";
|
||||
let mut result = Ok(());
|
||||
for (run, paths) in self.running_java_projects(files) {
|
||||
let uris: Vec<_> = paths.iter().map(|path| crate::path_to_uri_string(path)).collect();
|
||||
let supports_wait = run.caps.read().commands().iter().any(|command| command == UPDATE);
|
||||
let updated = match wait.filter(|_| supports_wait) {
|
||||
Some(cancel) => self
|
||||
.jdtls_request(
|
||||
paths[0],
|
||||
"workspace/executeCommand",
|
||||
json!({ "command": UPDATE, "arguments": uris }),
|
||||
BUILD_TIMEOUT,
|
||||
cancel,
|
||||
)
|
||||
.await
|
||||
.map(|_| ()),
|
||||
None => {
|
||||
let identifiers: Vec<_> = uris.into_iter().map(|uri| json!({ "uri": uri })).collect();
|
||||
run.peer
|
||||
.notify("java/projectConfigurationsUpdate", json!({ "identifiers": identifiers }))
|
||||
.map_err(|e| crate::rpc_err(SERVER, "java/projectConfigurationsUpdate", e))
|
||||
}
|
||||
};
|
||||
result = result.and(updated);
|
||||
/// Asks jdtls to re-read library archives replaced in place (`openidea.java.refreshArchives`):
|
||||
/// a SNAPSHOT installed again keeps its path, and JDT would keep showing the classes it read
|
||||
/// from the old archive. Best-effort: skipped while jdtls is not already running.
|
||||
pub async fn java_refresh_archives(&self, path: &Path, archives: &[PathBuf]) -> IdeResult<()> {
|
||||
let java = LanguageId::new("java");
|
||||
let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else {
|
||||
return Ok(());
|
||||
};
|
||||
if server.running().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Asks jdtls to re-read library archives replaced in place.
|
||||
pub async fn java_refresh_archives(&self, files: &[PathBuf], archives: &HashSet<PathBuf>) -> IdeResult<()> {
|
||||
let mut archives: Vec<_> = archives.iter().map(|a| Value::String(a.to_string_lossy().into_owned())).collect();
|
||||
archives.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
|
||||
let mut result = Ok(());
|
||||
for (_, paths) in self.running_java_projects(files) {
|
||||
let refreshed = self.jdtls_command(paths[0], "openidea.java.refreshArchives", archives.clone()).await;
|
||||
result = result.and(refreshed.map(|_| ()));
|
||||
}
|
||||
result
|
||||
let archives = archives.iter().map(|a| Value::String(a.to_string_lossy().into_owned())).collect();
|
||||
self.jdtls_command(path, "openidea.java.refreshArchives", archives).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Pause autobuild before resolving the launch classpath. That query takes the
|
||||
|
||||
@@ -280,7 +280,7 @@ pub struct LspManager {
|
||||
virtual_docs: Mutex<HashMap<String, VirtualDocument>>,
|
||||
/// Modification time of the archive behind a cached library class, so a jar
|
||||
/// replaced in place (a SNAPSHOT installed again) is read again.
|
||||
virtual_stamps: Mutex<HashMap<String, virtual_doc::ArchiveStamp>>,
|
||||
virtual_stamps: Mutex<HashMap<String, std::time::SystemTime>>,
|
||||
injections: injections::State,
|
||||
/// Open notebooks by path. Locked before `docs` when both are.
|
||||
notebooks: Mutex<HashMap<PathBuf, notebook::NotebookState>>,
|
||||
@@ -3631,16 +3631,6 @@ impl LspManager {
|
||||
archives
|
||||
}
|
||||
|
||||
/// Drop cached text after JDT LS reopens the archives. A request could have
|
||||
/// read the old attachment while the binary already had its new timestamp.
|
||||
pub fn invalidate_library_archives(&self, archives: &std::collections::HashSet<PathBuf>) {
|
||||
if !archives.is_empty() {
|
||||
self.virtual_docs
|
||||
.lock()
|
||||
.retain(|uri, _| !virtual_doc::archive(uri).is_some_and(|archive| archives.contains(&archive)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Contents of a virtual document, from the server that owns `uri`:
|
||||
/// `workspace/textDocumentContent` (LSP 3.18) when the server serves the
|
||||
/// scheme, jdtls' `java/classFileContents` for `jdt:` URIs. A `jar:` entry
|
||||
|
||||
@@ -261,8 +261,6 @@ pub struct InlayHint {
|
||||
/// The label's parts when the server split it (empty for a plain label);
|
||||
/// their values concatenate to `label`.
|
||||
pub parts: Vec<InlayLabelPart>,
|
||||
/// The edits that turn the hint into code (an annotation and any import it needs).
|
||||
pub text_edits: Vec<TextEdit>,
|
||||
}
|
||||
|
||||
/// One part of an inlay hint label, e.g. a type name that navigates to its declaration.
|
||||
|
||||
@@ -192,22 +192,9 @@ pub(crate) fn archive(uri: &str) -> Option<std::path::PathBuf> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Timestamps for a library document's archive and its replaceable SNAPSHOT attachment.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ArchiveStamp {
|
||||
archive: std::time::SystemTime,
|
||||
sources: Option<std::time::SystemTime>,
|
||||
}
|
||||
|
||||
pub(crate) fn archive_modified(uri: &str) -> Option<ArchiveStamp> {
|
||||
let modified = |path: &std::path::Path| std::fs::metadata(path).and_then(|m| m.modified()).ok();
|
||||
let archive = archive(uri)?;
|
||||
let sources = archive
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.and_then(|name| name.strip_suffix("-SNAPSHOT.jar"))
|
||||
.and_then(|name| modified(&archive.with_file_name(format!("{name}-SNAPSHOT-sources.jar"))));
|
||||
Some(ArchiveStamp { archive: modified(&archive)?, sources })
|
||||
/// Modification time of the archive a `jar:` or `jdt:` library class comes from.
|
||||
pub(crate) fn archive_modified(uri: &str) -> Option<std::time::SystemTime> {
|
||||
std::fs::metadata(archive(uri)?).and_then(|m| m.modified()).ok()
|
||||
}
|
||||
|
||||
/// Whether `uri` is jdtls' class `package.name`, in any archive.
|
||||
@@ -446,14 +433,9 @@ mod tests {
|
||||
let uri = format!("jar:file://{}!/p/C.class", jar.display());
|
||||
assert_eq!(archive(&uri), Some(jar.clone()));
|
||||
let before = archive_modified(&uri).unwrap();
|
||||
std::fs::write(dir.path().join("lib-1.0-SNAPSHOT-sources.jar"), b"PK").unwrap();
|
||||
let with_sources = archive_modified(&uri).unwrap();
|
||||
assert_eq!(before.archive, with_sources.archive);
|
||||
assert_ne!(with_sources, before);
|
||||
|
||||
let file = std::fs::File::options().write(true).open(&jar).unwrap();
|
||||
file.set_modified(before.archive + std::time::Duration::from_secs(5)).unwrap();
|
||||
assert_ne!(archive_modified(&uri), Some(with_sources));
|
||||
file.set_modified(before + std::time::Duration::from_secs(5)).unwrap();
|
||||
assert_ne!(archive_modified(&uri), Some(before));
|
||||
std::fs::remove_file(&jar).unwrap();
|
||||
assert_eq!(archive_modified(&uri), None);
|
||||
}
|
||||
|
||||
@@ -635,12 +635,11 @@ async fn java_sharing_cancels_a_retiring_initialize_before_starting_its_replacem
|
||||
let old = state.peer();
|
||||
shared.store(true, Ordering::SeqCst);
|
||||
let switched = tokio::time::timeout(Duration::from_secs(2), h.mgr.reconfigure()).await;
|
||||
switched.expect("initialize cancellation must not wait for its response");
|
||||
// The retiring transport closes asynchronously; wait for it before releasing
|
||||
// the initialize response so the ordering check does not race the close.
|
||||
eventually(|| old.is_closed()).await;
|
||||
let closed_before_response = old.is_closed();
|
||||
gate.open();
|
||||
switched.expect("initialize cancellation must not wait for its response");
|
||||
eventually(|| state.requested("initialize").len() == 2).await;
|
||||
assert!(closed_before_response, "the old transport must close before its initialize response is released");
|
||||
assert_eq!(h.mgr.servers().len(), 1);
|
||||
assert_eq!(h.mgr.servers()[0].root.as_ref(), h.root.as_path());
|
||||
h.mgr.shutdown_all().await;
|
||||
@@ -3165,34 +3164,6 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
|
||||
eventually(|| refreshed() == expected).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_update_refreshes_java_tokens_and_inheritance() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let _ = h.open("A.java", "class A { private String name; }");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let state = h.launcher.state("jdtls");
|
||||
let refreshes = || {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::LspRefresh { kind, .. } => Some(*kind),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
state
|
||||
.peer()
|
||||
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
|
||||
.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert!(refreshes().is_empty());
|
||||
|
||||
// A later import may add tokens and implementation targets to open editors.
|
||||
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
|
||||
eventually(|| refreshes() == [LspRefreshKind::SemanticTokens, LspRefreshKind::Inheritance]).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_update_attaches_maven_generated_sources_before_rechecking() {
|
||||
let mut caps = incremental_caps();
|
||||
|
||||
@@ -12,17 +12,11 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, SyncSender};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError, Sender};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const BATCH_INTERVAL: Duration = Duration::from_millis(8);
|
||||
const BATCH_BYTES: usize = 64 * 1024;
|
||||
/// Size of one pipe read, so the most one queued [`Msg::Data`] holds.
|
||||
const READ_BUF: usize = 16 * 1024;
|
||||
/// Chunks the readers may queue ahead of the pump (at most `OUTPUT_QUEUE_CHUNKS * READ_BUF`,
|
||||
/// 2 MiB). A process printing faster than the console takes its output waits on its full
|
||||
/// pipe, as it would on a terminal, instead of piling the flood up in memory here.
|
||||
const OUTPUT_QUEUE_CHUNKS: usize = 128;
|
||||
/// After the main process exits, how long to wait for pipes still held by
|
||||
/// orphaned descendants before reporting the exit.
|
||||
const EXIT_DRAIN: Duration = Duration::from_millis(500);
|
||||
@@ -118,12 +112,6 @@ enum Msg {
|
||||
Exited(Exit),
|
||||
}
|
||||
|
||||
/// The queue from the readers (and the waiter) to the pump: bounded, so the readers wait
|
||||
/// while the pump is behind.
|
||||
fn output_queue() -> (SyncSender<Msg>, mpsc::Receiver<Msg>) {
|
||||
mpsc::sync_channel(OUTPUT_QUEUE_CHUNKS)
|
||||
}
|
||||
|
||||
/// The program and arguments actually executed, plus the echoed command line.
|
||||
pub(crate) struct Invocation {
|
||||
pub program: PathBuf,
|
||||
@@ -496,7 +484,7 @@ impl ProcessManager {
|
||||
|
||||
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
|
||||
let (tx, rx) = output_queue();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let stdout = child.stdout.take();
|
||||
let stderr = child.stderr.take();
|
||||
let result = (|| -> std::io::Result<()> {
|
||||
@@ -643,7 +631,7 @@ impl ProcessManager {
|
||||
self.register(entry.clone());
|
||||
on_output(OutputChunk::System { text: format!("{}\n", inv.display) });
|
||||
|
||||
let (tx, rx) = output_queue();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let result = spawn_reader(
|
||||
id,
|
||||
Stream::Stdout,
|
||||
@@ -836,7 +824,7 @@ fn run_followup(
|
||||
config: &RunConfig,
|
||||
cwd: &Path,
|
||||
entry: &Entry,
|
||||
tx: &SyncSender<Msg>,
|
||||
tx: &Sender<Msg>,
|
||||
) -> std::io::Result<ExitStatus> {
|
||||
let mut pid = entry.pid.lock();
|
||||
if entry.stopping.load(Ordering::Acquire) {
|
||||
@@ -1118,19 +1106,16 @@ fn kill_tree(entry: &Entry, pid: u32, _force: bool) {
|
||||
.status();
|
||||
}
|
||||
|
||||
/// Reads `pipe` into `tx` until EOF. It waits in `send` while the pump is a full queue behind
|
||||
/// (the process then waits on its pipe). The pump dropping its receiver fails the `send`
|
||||
/// and ends the reader, so no reader stays blocked once the pump is gone.
|
||||
fn spawn_reader(
|
||||
id: RunId,
|
||||
stream: Stream,
|
||||
mut pipe: impl Read + Send + 'static,
|
||||
tx: SyncSender<Msg>,
|
||||
tx: Sender<Msg>,
|
||||
#[cfg(unix)] mut wait_readable: Option<Box<dyn FnMut() -> std::io::Result<()> + Send>>,
|
||||
) -> std::io::Result<()> {
|
||||
let label = if stream == Stream::Stdout { "out" } else { "err" };
|
||||
std::thread::Builder::new().name(format!("openidea-run-{label}-{}", id.0)).spawn(move || {
|
||||
let mut buf = vec![0u8; READ_BUF];
|
||||
let mut buf = vec![0u8; 16 * 1024];
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
@@ -1439,7 +1424,6 @@ fn input_writer(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
@@ -1585,111 +1569,4 @@ mod tests {
|
||||
assert_eq!(resolve_program("./gradlew", cwd, &config, true), cwd.join("./gradlew"));
|
||||
assert_eq!(resolve_program(".venv/bin/python", cwd, &config, false), cwd.join(".venv/bin/python"));
|
||||
}
|
||||
|
||||
/// A pipe stand-in that counts the bytes taken from it.
|
||||
#[cfg(unix)]
|
||||
struct Counted<R> {
|
||||
inner: R,
|
||||
taken: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl<R: Read> Read for Counted<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let n = self.inner.read(buf)?;
|
||||
self.taken.fetch_add(n, Ordering::SeqCst);
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_slow_pump_holds_a_flooding_process_back_instead_of_queueing_its_output() {
|
||||
const LINES: usize = 2_000_000;
|
||||
// (Not `seq`: macOS prints large numbers in exponent form.)
|
||||
let mut child = Command::new("awk")
|
||||
.arg(format!("BEGIN{{for(i=1;i<={LINES};i++)print i}}"))
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("awk");
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let pipe = Counted { inner: child.stdout.take().unwrap(), taken: taken.clone() };
|
||||
let (tx, rx) = output_queue();
|
||||
spawn_reader(RunId::next(), Stream::Stdout, pipe, tx, None).unwrap();
|
||||
let (mut received, mut peak, mut all) = (0usize, 0usize, Vec::new());
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok(Msg::Data(stream, bytes)) => {
|
||||
assert!(stream == Stream::Stdout);
|
||||
// Read from the pipe but not yet handled: the queue, plus the chunk the
|
||||
// reader holds while it waits for room, plus the one just received.
|
||||
peak = peak.max(taken.load(Ordering::SeqCst) - received);
|
||||
received += bytes.len();
|
||||
all.extend_from_slice(&bytes);
|
||||
// A console that cannot keep up with the process.
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
Ok(Msg::Exited(_)) => unreachable!("only the waiter sends the exit"),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the reader stalled"),
|
||||
}
|
||||
}
|
||||
assert!(child.wait().unwrap().success());
|
||||
let bound = (OUTPUT_QUEUE_CHUNKS + 2) * READ_BUF;
|
||||
assert!(peak <= bound, "{peak} bytes queued ahead of the pump, more than {bound}");
|
||||
let expected: String = (1..=LINES).map(|n| format!("{n}\n")).collect();
|
||||
assert!(all == expected.as_bytes(), "the output arrived incomplete or out of order");
|
||||
}
|
||||
|
||||
/// Endless output (cut at a size an unbounded queue could still hold in a test) that
|
||||
/// reports when it is dropped, which is when the reader thread owning it ends.
|
||||
struct Endless {
|
||||
served: Arc<AtomicUsize>,
|
||||
gone: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
impl Read for Endless {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
if self.served.load(Ordering::SeqCst) >= 8 * OUTPUT_QUEUE_CHUNKS {
|
||||
return Ok(0);
|
||||
}
|
||||
self.served.fetch_add(1, Ordering::SeqCst);
|
||||
buf.fill(b'x');
|
||||
Ok(buf.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Endless {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.gone.send(());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reader_blocked_on_a_full_queue_ends_when_the_pump_is_gone() {
|
||||
let served = Arc::new(AtomicUsize::new(0));
|
||||
let (gone_tx, gone) = mpsc::channel();
|
||||
let (tx, rx) = output_queue();
|
||||
spawn_reader(
|
||||
RunId::next(),
|
||||
Stream::Stdout,
|
||||
Endless { served: served.clone(), gone: gone_tx },
|
||||
tx,
|
||||
#[cfg(unix)]
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
// A pump that takes nothing: the queue fills and the reader holds one more chunk.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while served.load(Ordering::SeqCst) < OUTPUT_QUEUE_CHUNKS + 1 {
|
||||
assert!(Instant::now() < deadline, "the reader never filled the queue");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
// Time for a reader that does not wait to run ahead.
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert_eq!(served.load(Ordering::SeqCst), OUTPUT_QUEUE_CHUNKS + 1, "the reader ran past the full queue");
|
||||
assert!(gone.try_recv().is_err(), "the reader ended while its pump was still there");
|
||||
drop(rx);
|
||||
gone.recv_timeout(Duration::from_secs(30)).expect("the reader stayed blocked after the pump was gone");
|
||||
}
|
||||
}
|
||||
@@ -278,73 +278,6 @@ fn large_output_is_complete_and_batched() {
|
||||
assert!(chunks.lock().len() < 3000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_console_slower_than_the_process_still_gets_all_output_in_order_and_the_exit() {
|
||||
const LINES: usize = 1_000_000;
|
||||
let h = harness();
|
||||
let chunks: Chunks = Arc::default();
|
||||
let sink = chunks.clone();
|
||||
let info =
|
||||
h.pm.start(
|
||||
h.root.path(),
|
||||
&cfg("t:slow-console", "awk", &[&format!("BEGIN{{for(i=1;i<={LINES};i++)print i}}")]),
|
||||
&StartOptions::default(),
|
||||
h.sink.clone(),
|
||||
Box::new(move |c| {
|
||||
sink.lock().push(c);
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}),
|
||||
)
|
||||
.expect("start");
|
||||
assert_eq!(wait_exit(&h, info.id, Duration::from_secs(120)), Some(0));
|
||||
let expected: String = (1..=LINES).map(|n| format!("{n}\n")).collect();
|
||||
assert!(text(&chunks, stdout) == expected, "the output arrived incomplete or out of order");
|
||||
// The exit is reported after the output, never before the last of it.
|
||||
let all = chunks.lock();
|
||||
assert!(matches!(all.last(), Some(OutputChunk::System { text }) if text.contains("exit code 0")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_ends_a_flooding_run_whose_console_stalled() {
|
||||
let h = harness();
|
||||
let chunks: Chunks = Arc::default();
|
||||
let sink = chunks.clone();
|
||||
let (stalled_tx, stalled) = mpsc::channel();
|
||||
let (resume_tx, resume) = mpsc::channel::<()>();
|
||||
// The first output blocks the console until `resume_tx` is dropped.
|
||||
let resume = Mutex::new(Some(resume));
|
||||
let info =
|
||||
h.pm.start(
|
||||
h.root.path(),
|
||||
&cfg("t:stalled-console", "yes", &[]),
|
||||
&StartOptions::default(),
|
||||
h.sink.clone(),
|
||||
Box::new(move |c| {
|
||||
let output = matches!(c, OutputChunk::Stdout { .. });
|
||||
sink.lock().push(c);
|
||||
if output && let Some(resume) = resume.lock().take() {
|
||||
let _ = stalled_tx.send(());
|
||||
let _ = resume.recv();
|
||||
}
|
||||
}),
|
||||
)
|
||||
.expect("start");
|
||||
stalled.recv_timeout(Duration::from_secs(10)).expect("no output reached the console");
|
||||
// The pipe and the queue behind the stalled console fill up and `yes` waits on its pipe.
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
h.pm.stop(info.id).unwrap();
|
||||
let pid = i32::try_from(info.pid.expect("pid")).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while alive(pid) {
|
||||
assert!(Instant::now() < deadline, "the stalled run survived Stop");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
drop(resume_tx);
|
||||
assert_eq!(wait_exit(&h, info.id, Duration::from_secs(30)), Some(130));
|
||||
let out = text(&chunks, stdout);
|
||||
assert!(!out.is_empty() && out.lines().all(|l| l == "y"), "the output was damaged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_program_resolves_against_cwd() {
|
||||
let h = harness();
|
||||
|
||||
@@ -6,7 +6,6 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
dirs.workspace = true
|
||||
dunce.workspace = true
|
||||
ignore.workspace = true
|
||||
@@ -17,7 +16,6 @@ ide-vfs.workspace = true
|
||||
quick-xml = "0.42"
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2 = "0.10"
|
||||
specta.workspace = true
|
||||
tempfile.workspace = true
|
||||
toml.workspace = true
|
||||
|
||||
+13
-216
@@ -66,10 +66,9 @@ pub fn ruff_configuration(root: &Path, configured: &str) -> IdeResult<Option<Pat
|
||||
|
||||
/// The project interpreter: the configured one, else a project virtualenv
|
||||
/// (`.venv`, `venv`, …) or pixi environment (`.pixi/envs/<env>`) in the project
|
||||
/// root, else the project's Pipenv environment, else the Python the project pins
|
||||
/// for mise / asdf. A configured interpreter whose executable is gone (uninstalled,
|
||||
/// moved) is skipped like PyCharm's "Invalid" SDKs, so runs fall back instead of
|
||||
/// failing on a dead path.
|
||||
/// root, else the Python the project pins for mise / asdf. A configured
|
||||
/// interpreter whose executable is gone (uninstalled, moved) is skipped like
|
||||
/// PyCharm's "Invalid" SDKs, so runs fall back instead of failing on a dead path.
|
||||
/// `None` when the project interpreter is a run target's (see [`crate::container_python`]).
|
||||
pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
if s.languages.python.run_target().is_some() {
|
||||
@@ -81,72 +80,6 @@ pub fn python_interpreter(root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
.or_else(|| pinned::pinned_python(root))
|
||||
}
|
||||
|
||||
/// An absolute or `~/` path from the settings; `None` for anything else.
|
||||
pub fn absolute_setting_path(s: &str) -> Option<PathBuf> {
|
||||
setting_path(Path::new(""), s).filter(|p| p.is_absolute())
|
||||
}
|
||||
|
||||
/// Why a folder added to an interpreter's paths stays off the import path.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum UserPathProblem {
|
||||
/// Not an existing folder.
|
||||
Missing,
|
||||
/// Not absolute or `~/`, or it holds the separator of `PYTHONPATH`.
|
||||
Invalid,
|
||||
}
|
||||
|
||||
/// A folder added to an interpreter's paths (All Interpreters › Show Paths), as it goes on the
|
||||
/// import path.
|
||||
pub fn user_path(s: &str) -> Result<PathBuf, UserPathProblem> {
|
||||
let path = absolute_setting_path(s).ok_or(UserPathProblem::Invalid)?;
|
||||
// `PYTHONPATH` cannot hold a path with its separator in it: joining would fail every launch.
|
||||
if std::env::join_paths([&path]).is_err() {
|
||||
return Err(UserPathProblem::Invalid);
|
||||
}
|
||||
if !path.is_dir() {
|
||||
return Err(UserPathProblem::Missing);
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Whether the settings key `key` names the interpreter `python`. Paths are compared as
|
||||
/// written, not through symlinks: a virtualenv's `python` links to its base interpreter, and
|
||||
/// the two are different interpreters.
|
||||
fn names_interpreter(key: &str, python: &Path) -> bool {
|
||||
let Some(key) = absolute_setting_path(key) else { return false };
|
||||
if cfg!(windows) {
|
||||
let fold = |p: &Path| p.to_string_lossy().replace('\\', "/").to_lowercase();
|
||||
fold(&key) == fold(python)
|
||||
} else {
|
||||
key == python
|
||||
}
|
||||
}
|
||||
|
||||
/// The folders the user added to `python`'s paths that can be imported from.
|
||||
pub fn interpreter_user_paths(python: &Path, s: &Settings) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
for (interpreter, paths) in &s.languages.python.interpreter_paths {
|
||||
if !names_interpreter(interpreter, python) {
|
||||
continue;
|
||||
}
|
||||
for path in paths.iter().filter_map(|p| user_path(p).ok()) {
|
||||
if !out.contains(&path) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The interpreter a Python language server started for `server_root` analyses with: that
|
||||
/// folder's own virtualenv unless an interpreter is configured, else the project interpreter.
|
||||
pub fn python_server_interpreter(root: &Path, server_root: &Path, s: &Settings) -> Option<PathBuf> {
|
||||
project_venv_python(server_root)
|
||||
.filter(|_| non_empty(&s.languages.python.interpreter).is_none())
|
||||
.or_else(|| python_interpreter(root, s))
|
||||
}
|
||||
|
||||
/// An explicit project interpreter wins; otherwise use the closest virtualenv to the file.
|
||||
pub fn python_interpreter_near(root: &Path, near: Option<&Path>, s: &Settings) -> Option<PathBuf> {
|
||||
if s.languages.python.run_target().is_some() {
|
||||
@@ -1227,7 +1160,9 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
let name = name.as_str();
|
||||
|
||||
if PYTHON_SERVERS.contains(&name) {
|
||||
let python = python_server_interpreter(root, server_root, s);
|
||||
let python = project_venv_python(server_root)
|
||||
.filter(|_| non_empty(&s.languages.python.interpreter).is_none())
|
||||
.or_else(|| python_interpreter(root, s));
|
||||
if let Some(python) = python {
|
||||
let p = python.to_string_lossy().into_owned();
|
||||
match name {
|
||||
@@ -1430,15 +1365,8 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
|
||||
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
|
||||
let vue_pkg = vue::server_package(&vue_command, &search_path());
|
||||
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server, whose plugin
|
||||
// host goes away with it. The Vue language server's `@vue/typescript-plugin` loads into
|
||||
// that host, so a Vue project that has the server keeps the vtsls route and its `.vue`
|
||||
// support; elsewhere the native server still wins.
|
||||
// TypeScript 7 serves LSP itself: it replaces the tsserver-based server.
|
||||
if matches!(name, "vtsls" | "typescript-language-server")
|
||||
&& !(name == "vtsls" && vue_pkg.is_some() && (vue::vue_project(server_root) || vue::vue_project(root)))
|
||||
&& let Some(native) = native_tsdk(server_root, s).or_else(|| native_tsdk(root, s))
|
||||
{
|
||||
cfg.command = native.to_string_lossy().into_owned();
|
||||
@@ -1452,8 +1380,10 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
cfg.tsserver_project = false;
|
||||
return;
|
||||
}
|
||||
let vue_command = s.tool_path(vue::SERVER).and_then(|p| setting_path(root, p));
|
||||
let vue_command = vue_command.as_deref().map_or(vue::SERVER.into(), Path::to_string_lossy);
|
||||
if name == "vtsls"
|
||||
&& let Some(vue) = vue_pkg
|
||||
&& let Some(vue) = vue::server_package(&vue_command, &search_path())
|
||||
{
|
||||
let plugin = vue::tsserver_plugin(&vue);
|
||||
merge_init_options(cfg, json!({ "vtsls": { "tsserver": { "globalPlugins": [plugin] } } }));
|
||||
@@ -1753,8 +1683,7 @@ fn configure_angular(cfg: &mut LanguageServerConfig, root: &Path, server_root: &
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `cmd` is a Python executable by its name (`python`, `python3.12`, `python.exe`).
|
||||
pub fn is_python_command(cmd: &str) -> bool {
|
||||
fn is_python_command(cmd: &str) -> bool {
|
||||
let name = Path::new(cmd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let name = name.strip_suffix(".exe").unwrap_or(&name);
|
||||
name == "python"
|
||||
@@ -1967,17 +1896,10 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
|
||||
let mut path_dirs: Vec<PathBuf> = Vec::new();
|
||||
match c.kind.as_str() {
|
||||
"python" | "pytest" | "django-test" => {
|
||||
let command = Path::new(&c.command);
|
||||
let own = !c.detected && command.components().count() > 1 && is_python_command(&c.command);
|
||||
let python = if own {
|
||||
let cwd = root.join(c.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
Some(ide_core::project_roots::resolve(&cwd, command))
|
||||
} else {
|
||||
toolchain("python", &owner)
|
||||
};
|
||||
let python = toolchain("python", &owner);
|
||||
// The member's explicit interpreter, else the inherited one, else the
|
||||
// member's own venv / pin.
|
||||
if !own && let Some(py) = explicit_python.as_ref().or(inherited_python.as_ref()).or(python.as_ref()) {
|
||||
if let Some(py) = explicit_python.as_ref().or(inherited_python.as_ref()).or(python.as_ref()) {
|
||||
let runner = PY_RUNNERS.contains(&c.command.as_str());
|
||||
if (c.kind == "python" || c.kind == "django-test") && (runner || is_python_command(&c.command)) {
|
||||
if runner && c.args.first().map(String::as_str) == Some("run") {
|
||||
@@ -2322,81 +2244,6 @@ fn conda_activation(python: &Path, name: &str, conda_exe: Option<PathBuf>, on_pa
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod python_user_path_tests {
|
||||
use super::*;
|
||||
|
||||
fn venv(dir: &Path) -> PathBuf {
|
||||
let python = dir.join(".venv").join(crate::bin_dir()).join(crate::exe("python"));
|
||||
std::fs::create_dir_all(python.parent().unwrap()).unwrap();
|
||||
std::fs::write(&python, "").unwrap();
|
||||
std::fs::write(dir.join(".venv/pyvenv.cfg"), "").unwrap();
|
||||
python
|
||||
}
|
||||
|
||||
fn text(p: &Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_paths_follow_the_interpreter_and_skip_what_cannot_be_imported() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let (lib, other) = (root.join("shared"), root.join("other"));
|
||||
std::fs::create_dir_all(&lib).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let python = venv(&root);
|
||||
let other_python = root.join("other-python");
|
||||
|
||||
let mut s = Settings::default();
|
||||
s.languages.python.interpreter_paths = [
|
||||
// Gone, duplicated, relative and a file: none of them reach the import path.
|
||||
(text(&python), vec![text(&lib), text(&root.join("gone")), text(&lib), "relative".into(), text(&python)]),
|
||||
(text(&other_python), vec![text(&other)]),
|
||||
]
|
||||
.into();
|
||||
assert_eq!(interpreter_user_paths(&python, &s), std::slice::from_ref(&lib));
|
||||
assert_eq!(interpreter_user_paths(&other_python, &s), [other]);
|
||||
assert!(interpreter_user_paths(&root.join("unknown-python"), &s).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_that_stays_off_the_import_path_says_why() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
assert_eq!(user_path(&text(&root)), Ok(root.clone()));
|
||||
assert_eq!(user_path(&text(&root.join("gone"))), Err(UserPathProblem::Missing));
|
||||
assert_eq!(user_path("relative/dir"), Err(UserPathProblem::Invalid));
|
||||
assert_eq!(user_path(" "), Err(UserPathProblem::Invalid));
|
||||
// One entry with the separator in it would make `PYTHONPATH` impossible to build.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let odd = root.join("libs:v2");
|
||||
std::fs::create_dir(&odd).unwrap();
|
||||
assert_eq!(user_path(&text(&odd)), Err(UserPathProblem::Invalid));
|
||||
let mut s = Settings::default();
|
||||
s.languages.python.interpreter_paths = [("/bin/python".into(), vec![text(&odd), text(&root)])].into();
|
||||
assert_eq!(interpreter_user_paths(Path::new("/bin/python"), &s), [root]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_language_server_takes_the_interpreter_of_its_own_folder() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let sub = root.join("services/api");
|
||||
let (python, sub_python) = (venv(&root), venv(&sub));
|
||||
let mut s = Settings::default();
|
||||
assert_eq!(python_server_interpreter(&root, &root, &s), Some(python.clone()));
|
||||
assert_eq!(python_server_interpreter(&root, &sub, &s), Some(sub_python));
|
||||
// A configured interpreter is the one every server of the project uses.
|
||||
s.languages.python.interpreter = text(&python);
|
||||
assert_eq!(python_server_interpreter(&root, &sub, &s), Some(python));
|
||||
s.languages.python.interpreter = "target:docker".into();
|
||||
assert_eq!(python_server_interpreter(&root, &root, &s), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod java_compiler_tests {
|
||||
use super::*;
|
||||
@@ -2606,56 +2453,6 @@ mod maven_linkage_tests {
|
||||
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typescript_7_keeps_vtsls_when_the_vue_server_is_installed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
// The Vue server, as the hybrid block finds it through the tool's package dir.
|
||||
let bin = root.join("tools/node_modules/.bin/vue-language-server");
|
||||
let pkg = root.join("tools/node_modules/@vue/language-server/package.json");
|
||||
std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
|
||||
std::fs::create_dir_all(pkg.parent().unwrap()).unwrap();
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
std::fs::write(&pkg, "{}").unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.tools
|
||||
.insert(vue::SERVER.into(), ide_core::settings::ToolSettings { path: bin.to_string_lossy().into_owned() });
|
||||
// A Vue project whose TypeScript is 7: the native executable would take over.
|
||||
std::fs::write(root.join("package.json"), r#"{"dependencies":{"vue":"^3.0.0"}}"#).unwrap();
|
||||
let modules = root.join("node_modules");
|
||||
let os = match std::env::consts::OS {
|
||||
"macos" => "darwin",
|
||||
"windows" => "win32",
|
||||
os => os,
|
||||
};
|
||||
let arch = match std::env::consts::ARCH {
|
||||
"aarch64" => "arm64",
|
||||
"x86_64" => "x64",
|
||||
arch => arch,
|
||||
};
|
||||
std::fs::create_dir_all(modules.join("typescript/lib")).unwrap();
|
||||
std::fs::write(modules.join("typescript/package.json"), r#"{"name":"typescript","version":"7.0.2"}"#).unwrap();
|
||||
let native = modules.join(format!("@typescript/typescript-{os}-{arch}/lib")).join(crate::exe("tsc"));
|
||||
std::fs::create_dir_all(native.parent().unwrap()).unwrap();
|
||||
std::fs::write(&native, "").unwrap();
|
||||
s.languages.typescript.version = "workspace".into();
|
||||
|
||||
// vtsls hosts the Vue plugin's tsserver; the native server cannot, so it loses.
|
||||
let mut cfg = crate::tests::server("vtsls");
|
||||
configure_server(&mut cfg, root, root, &s);
|
||||
assert_eq!(cfg.command, "vtsls");
|
||||
assert_eq!(
|
||||
serde_json::to_value(cfg.initialization_options).unwrap().pointer("/vtsls/tsserver/globalPlugins/0/name"),
|
||||
Some(&json!("@vue/typescript-plugin"))
|
||||
);
|
||||
assert_eq!(cfg.tsserver_project_extras.extensions, [vue::EXTENSION.to_string()]);
|
||||
|
||||
// typescript-language-server gets no plugin route: the native server still applies.
|
||||
let mut cfg = crate::tests::server("typescript-language-server");
|
||||
configure_server(&mut cfg, root, root, &s);
|
||||
assert_eq!(Path::new(&cfg.command), native);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hybrid_without_a_config_keeps_type_acquisition_and_plain_vtsls_stays_default() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
use crate::exec::{executables_in, query, search_path, which};
|
||||
use crate::{Sdk, SdkKind, bin_dir, exe, home_dir, pinned, venv_of};
|
||||
use ide_core::process::{host_var_os, host_var_os_in};
|
||||
use ide_core::process::host_var_os;
|
||||
use ide_core::version_managers::{self, Tool};
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -55,7 +55,7 @@ fn tool_of(kind: SdkKind) -> Option<Tool> {
|
||||
fn pinned_first(sdks: &mut Vec<Sdk>, kind: SdkKind, root: &Path) {
|
||||
let Some((dir, _)) = tool_of(kind).and_then(|t| pinned::pinned_install(root, t)) else { return };
|
||||
let Some(i) = sdks.iter().position(|s| s.path.starts_with(&dir)) else { return };
|
||||
let at = sdks.iter().take_while(|s| matches!(s.source.as_str(), "venv" | "pipenv")).count().min(i);
|
||||
let at = sdks.iter().take_while(|s| s.source == "venv").count().min(i);
|
||||
let sdk = sdks.remove(i);
|
||||
sdks.insert(at, sdk);
|
||||
}
|
||||
@@ -81,8 +81,7 @@ fn dedupe_by_real_path(paths: Vec<(PathBuf, &'static str)>) -> Vec<(PathBuf, &'s
|
||||
/// Project-local virtualenv directories checked by auto-detection, in order.
|
||||
pub(crate) const PROJECT_VENVS: [&str; 4] = [".venv", "venv", "env", ".env"];
|
||||
|
||||
/// `<root>/<venv>/bin/python` of the first project virtualenv or pixi environment, else the
|
||||
/// interpreter of the project's Pipenv environment.
|
||||
/// `<root>/<venv>/bin/python` of the first project virtualenv or pixi environment.
|
||||
pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
|
||||
PROJECT_VENVS
|
||||
.iter()
|
||||
@@ -95,101 +94,6 @@ pub(crate) fn project_venv_python(root: &Path) -> Option<PathBuf> {
|
||||
[env.join(exe("python")), env.join("bin").join(exe("python"))].into_iter().find(|p| p.is_file())
|
||||
})
|
||||
})
|
||||
.or_else(|| pipenv_env_python(root))
|
||||
}
|
||||
|
||||
/// Pipenv's active workon home first, followed by the other conventional location.
|
||||
fn workon_homes(home: &Path, env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
|
||||
let var = |key: &str| env(key).filter(|v| !v.is_empty()).map(PathBuf::from);
|
||||
let data = var("XDG_DATA_HOME").unwrap_or_else(|| home.join(".local/share"));
|
||||
let mut defaults = [home.join(".virtualenvs"), data.join("virtualenvs")];
|
||||
if !cfg!(windows) {
|
||||
defaults.swap(0, 1);
|
||||
}
|
||||
var("WORKON_HOME").into_iter().chain(defaults).collect()
|
||||
}
|
||||
|
||||
/// How many folders pipenv searches for a `Pipfile`, the project's own and those above it
|
||||
/// (`PIPENV_MAX_DEPTH`, 10 by default).
|
||||
const PIPFILE_MAX_DEPTH: usize = 10;
|
||||
|
||||
/// The folder of the `Pipfile` pipenv uses for a project opened at `root`: the nearest one in
|
||||
/// `root` or the folders above it, searched as pipenv does.
|
||||
pub(crate) fn pipfile_dir(root: &Path) -> Option<PathBuf> {
|
||||
root.ancestors().take(PIPFILE_MAX_DEPTH).find(|dir| dir.join("Pipfile").is_file()).map(Path::to_path_buf)
|
||||
}
|
||||
|
||||
/// The folder name pipenv gives the environment of the project whose `Pipfile` is in `dir`
|
||||
/// (`venv_locator._get_virtualenv_hash`): the folder's name with shell-special characters
|
||||
/// replaced and cut to 42 characters, `-`, and the URL-safe base64 of the first 6 bytes of
|
||||
/// the SHA-256 of the `Pipfile` path.
|
||||
pub(crate) fn pipenv_env_name(dir: &Path) -> String {
|
||||
use base64::Engine;
|
||||
use sha2::Digest;
|
||||
let name: String = (dir.file_name().unwrap_or_default().to_string_lossy().chars())
|
||||
.map(|c| if " &$`!*@\"()[]\\\r\n\t".contains(c) { '_' } else { c })
|
||||
.take(42)
|
||||
.collect();
|
||||
let digest = sha2::Sha256::digest(dir.join("Pipfile").to_string_lossy().as_bytes());
|
||||
format!("{name}-{}", base64::engine::general_purpose::URL_SAFE.encode(&digest[..6]))
|
||||
}
|
||||
|
||||
/// The project a Pipenv virtualenv belongs to. Pipenv records the project folder in
|
||||
/// `<venv>/.project`; virtualenvwrapper does too, so the environment must also carry the
|
||||
/// name pipenv derives from that project's `Pipfile`, or be the project's own `.venv`.
|
||||
fn pipenv_project(venv: &Path) -> Option<PathBuf> {
|
||||
let project = PathBuf::from(std::fs::read_to_string(venv.join(".project")).ok()?.trim());
|
||||
let named = venv.file_name().is_some_and(|name| *name.to_string_lossy() == pipenv_env_name(&project));
|
||||
(project.is_absolute() && project.join("Pipfile").is_file() && (named || venv == project.join(".venv")))
|
||||
.then_some(project)
|
||||
}
|
||||
|
||||
/// The interpreter of the Pipenv environment `pipenv --venv` names for the project at `root`,
|
||||
/// found without starting pipenv, which takes about a second.
|
||||
fn pipenv_env_python(root: &Path) -> Option<PathBuf> {
|
||||
let dir = pipfile_dir(root)?;
|
||||
let var = |key: &str| host_var_os_in(&dir, key);
|
||||
let homes = home_dir().map(|home| workon_homes(&home, var)).unwrap_or_default();
|
||||
pipenv_env_in(&dir, &homes, var("PIPENV_CUSTOM_VENV_NAME").as_deref())
|
||||
}
|
||||
|
||||
/// A project-local environment, an explicitly selected path or name, or Pipenv's hashed name.
|
||||
fn pipenv_env_in(dir: &Path, homes: &[PathBuf], custom_name: Option<&OsStr>) -> Option<PathBuf> {
|
||||
let dot_venv = dir.join(".venv");
|
||||
let python_in = |env: &Path| {
|
||||
let python = env.join(bin_dir()).join(exe("python"));
|
||||
(env.join("pyvenv.cfg").is_file() && python.is_file()).then_some(python)
|
||||
};
|
||||
if dot_venv.is_file() {
|
||||
let pointer = std::fs::read_to_string(&dot_venv).ok()?;
|
||||
let pointer = pointer.trim();
|
||||
if !pointer.is_empty() {
|
||||
let path = Path::new(pointer);
|
||||
let components = path.components().filter(|part| *part != std::path::Component::CurDir);
|
||||
let home = if components.count() > 1 || pointer.ends_with(std::path::is_separator) {
|
||||
dir.join(path)
|
||||
} else {
|
||||
homes.first()?.join(path)
|
||||
};
|
||||
return python_in(&dunce::canonicalize(home).ok()?);
|
||||
}
|
||||
}
|
||||
if let Some(python) = python_in(&dot_venv) {
|
||||
return Some(python);
|
||||
}
|
||||
if let Some(name) = custom_name.filter(|name| !name.is_empty()) {
|
||||
let path = Path::new(name);
|
||||
return if path.is_absolute() { python_in(path) } else { python_in(&homes.first()?.join(path)) };
|
||||
}
|
||||
|
||||
// Pipenv hashes the path it was started in, which may or may not have its symlinks resolved.
|
||||
let mut names: Vec<String> = [Some(dir.to_path_buf()), dunce::canonicalize(dir).ok()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|d| pipenv_env_name(&d))
|
||||
.collect();
|
||||
names.dedup();
|
||||
homes.iter().flat_map(|home| names.iter().map(move |name| home.join(name))).find_map(|home| python_in(&home))
|
||||
}
|
||||
|
||||
/// `/usr/bin/python3` on macOS is a stub that opens an installer dialog when
|
||||
@@ -319,22 +223,15 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
|
||||
found.push((python, "pixi"));
|
||||
}
|
||||
}
|
||||
if let Some(python) = pipenv_env_python(root) {
|
||||
// The selected Pipenv environment may already be a project-local virtualenv.
|
||||
if let Some((_, source)) = found.iter_mut().find(|(path, _)| *path == python) {
|
||||
*source = "pipenv";
|
||||
} else {
|
||||
found.push((python, "pipenv"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(venv) = std::env::var("VIRTUAL_ENV") {
|
||||
found.push((Path::new(&venv).join(bin_dir()).join(exe("python")), "venv"));
|
||||
}
|
||||
if let Some(home) = home_dir() {
|
||||
// Virtualenvs managed by virtualenvwrapper / pipenv / poetry.
|
||||
let env_dirs = [".virtualenvs", ".local/share/virtualenvs"].map(|d| home.join(d));
|
||||
let var = |key: &str| host_var_os(key);
|
||||
for dir in workon_homes(&home, var).into_iter().chain(poetry_venv_dirs(Host::current(), &home, var)) {
|
||||
for dir in env_dirs.into_iter().chain(poetry_venv_dirs(Host::current(), &home, var)) {
|
||||
for env in subdirs(&dir) {
|
||||
found.push((env.join(bin_dir()).join(exe("python")), "venv"));
|
||||
}
|
||||
@@ -436,11 +333,7 @@ fn python(root: Option<&Path>) -> Vec<Sdk> {
|
||||
seen_real.insert(p.canonicalize().unwrap_or_else(|_| p.clone()))
|
||||
}
|
||||
})
|
||||
.map(
|
||||
|(p, source)| {
|
||||
if venv_of(&p).is_some() && !matches!(source, "conda" | "pipenv") { (p, "venv") } else { (p, source) }
|
||||
},
|
||||
)
|
||||
.map(|(p, source)| if venv_of(&p).is_some() && source != "conda" { (p, "venv") } else { (p, source) })
|
||||
.collect();
|
||||
par_map(&candidates, |(path, source)| python_sdk(path, source, root))
|
||||
}
|
||||
@@ -464,18 +357,7 @@ pub fn python_interpreter_sdk(path: &Path, root: Option<&Path>) -> Option<Sdk> {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let source = if let Some(home) = venv_of(&path) {
|
||||
let pipenv_home = root.and_then(pipenv_env_python).and_then(|p| venv_of(&p));
|
||||
if pipenv_home.is_some_and(|p| dunce::canonicalize(p).is_ok_and(|p| dunce::canonicalize(&home).ok() == Some(p)))
|
||||
{
|
||||
"pipenv"
|
||||
} else {
|
||||
"venv"
|
||||
}
|
||||
} else {
|
||||
"system"
|
||||
};
|
||||
Some(python_sdk_with_version(&path, source, root, version))
|
||||
Some(python_sdk_with_version(&path, if venv_of(&path).is_some() { "venv" } else { "system" }, root, version))
|
||||
}
|
||||
|
||||
pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Option<Sdk> {
|
||||
@@ -488,17 +370,7 @@ pub(crate) fn python_sdk(path: &Path, source: &str, root: Option<&Path>) -> Opti
|
||||
fn python_sdk_with_version(path: &Path, source: &str, root: Option<&Path>, version: String) -> Sdk {
|
||||
let short = version.split('.').take(2).collect::<Vec<_>>().join(".");
|
||||
let venv = venv_of(path);
|
||||
let pipenv = if source == "pipenv" {
|
||||
root.and_then(pipfile_dir)
|
||||
} else {
|
||||
venv.as_deref().filter(|_| source == "venv").and_then(pipenv_project)
|
||||
};
|
||||
let source = if pipenv.is_some() { "pipenv" } else { source };
|
||||
let label = match (&venv, source) {
|
||||
(_, "pipenv") => {
|
||||
let project = pipenv.as_deref().and_then(Path::file_name).unwrap_or_default().to_string_lossy();
|
||||
format!("Python {short} (Pipenv: {project})")
|
||||
}
|
||||
(Some(home), _) => {
|
||||
let dir = home.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
// `.venv` inside a project reads better as the folder that holds it (the project,
|
||||
@@ -561,7 +433,7 @@ fn pixi_env_name(python: &Path) -> Option<String> {
|
||||
pixi_env_home(python)?.file_name().map(|n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn pyvenv_version(python: &Path) -> Option<String> {
|
||||
fn pyvenv_version(python: &Path) -> Option<String> {
|
||||
let cfg = std::fs::read_to_string(venv_of(python)?.join("pyvenv.cfg")).ok()?;
|
||||
cfg.lines().find_map(|l| {
|
||||
let (k, v) = l.split_once('=')?;
|
||||
@@ -1247,106 +1119,6 @@ mod pixi_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pipenv_tests {
|
||||
use super::*;
|
||||
|
||||
fn venv(home: &Path, project: &Path) -> PathBuf {
|
||||
let python = home.join(bin_dir()).join(exe("python"));
|
||||
std::fs::create_dir_all(python.parent().unwrap()).unwrap();
|
||||
std::fs::write(&python, "").unwrap();
|
||||
std::fs::write(home.join("pyvenv.cfg"), "version = 3.12.1\n").unwrap();
|
||||
std::fs::write(home.join(".project"), project.to_string_lossy().as_bytes()).unwrap();
|
||||
python
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environments_are_named_as_pipenv_names_them() {
|
||||
// `sanitize(folder)[:42] + "-" + urlsafe_b64encode(sha256(Pipfile path).digest()[:6])`, from pipenv.
|
||||
assert_eq!(pipenv_env_name(Path::new("/home/me/My Shop (2)")), "My_Shop__2_-6rNTtAUD");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_environment_named_for_the_pipfile_is_the_projects() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tmp = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (shop, blog) = (tmp.join("shop"), tmp.join("blog"));
|
||||
for project in [&shop, &blog] {
|
||||
std::fs::create_dir_all(project.join("src/pkg")).unwrap();
|
||||
std::fs::write(project.join("Pipfile"), "").unwrap();
|
||||
}
|
||||
let homes = [tmp.join("missing"), tmp.join(".virtualenvs"), tmp.join("workon")];
|
||||
// virtualenvwrapper's `mkproject` writes `.project` too: its environment is not pipenv's,
|
||||
// though it comes first and its project has a Pipfile.
|
||||
let wrapper = venv(&homes[1].join("shop"), &shop);
|
||||
let shop_python = venv(&homes[2].join(pipenv_env_name(&shop)), &shop);
|
||||
let blog_python = venv(&homes[2].join(pipenv_env_name(&blog)), &blog);
|
||||
|
||||
assert_eq!(pipenv_env_in(&shop, &homes, None), Some(shop_python.clone()));
|
||||
assert_eq!(pipenv_env_in(&blog, &homes, None), Some(blog_python));
|
||||
// Opened in a sub-folder, the project is the one pipenv finds above it.
|
||||
assert_eq!(pipfile_dir(&shop.join("src/pkg")), Some(shop.clone()));
|
||||
assert_eq!(pipfile_dir(&tmp), None);
|
||||
|
||||
let sdk = python_sdk(&shop_python, "venv", Some(&blog)).unwrap();
|
||||
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Pipenv: shop)", "pipenv"));
|
||||
assert_eq!(
|
||||
sdk.home.as_deref().map(|h| h.to_path_buf()),
|
||||
shop_python.parent().unwrap().parent().map(Into::into)
|
||||
);
|
||||
let sdk = python_sdk(&wrapper, "venv", None).unwrap();
|
||||
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (shop)", "venv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pipenv_environment_inside_the_project_is_named_as_pipenvs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let shop = tmp.path().join("shop");
|
||||
std::fs::create_dir_all(&shop).unwrap();
|
||||
std::fs::write(shop.join("Pipfile"), "").unwrap();
|
||||
let python = venv(&shop.join(".venv"), &shop);
|
||||
assert_eq!(project_venv_python(&shop), Some(python.clone()));
|
||||
assert_eq!(pipenv_env_in(&shop, &[], None), Some(python.clone()));
|
||||
assert_eq!(python_sdk(&python, "venv", Some(&shop)).unwrap().name, "Python 3.12 (Pipenv: shop)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipenv_uses_the_explicit_environment_without_a_project_marker() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tmp = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let shop = tmp.join("shop");
|
||||
let subdir = shop.join("src");
|
||||
std::fs::create_dir_all(&subdir).unwrap();
|
||||
std::fs::write(shop.join("Pipfile"), "").unwrap();
|
||||
let homes = [tmp.join("workon")];
|
||||
venv(&homes[0].join(pipenv_env_name(&shop)), &shop);
|
||||
let named = homes[0].join("named");
|
||||
let named_python = venv(&named, &shop);
|
||||
std::fs::remove_file(named.join(".project")).unwrap();
|
||||
let outside = tmp.join("outside");
|
||||
let external_python = venv(&outside, &shop);
|
||||
std::fs::remove_file(outside.join(".project")).unwrap();
|
||||
let marker = shop.join(".venv");
|
||||
let name = Some(OsStr::new("named"));
|
||||
|
||||
assert_eq!(pipenv_env_in(&shop, &homes, name), Some(named_python.clone()));
|
||||
assert_eq!(pipenv_env_in(&shop, &[], Some(outside.as_os_str())), Some(external_python.clone()));
|
||||
for pointer in ["../outside".into(), outside.to_string_lossy()] {
|
||||
std::fs::write(&marker, format!(" {pointer}\n")).unwrap();
|
||||
assert_eq!(pipenv_env_in(&shop, &homes, name), Some(external_python.clone()));
|
||||
assert_eq!(project_venv_python(&subdir), Some(external_python.clone()));
|
||||
}
|
||||
let sdk = detect(SdkKind::Python, Some(&subdir)).into_iter().next().unwrap();
|
||||
assert_eq!(sdk.path.to_path_buf(), external_python);
|
||||
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Pipenv: shop)", "pipenv"));
|
||||
|
||||
std::fs::write(&marker, "named").unwrap();
|
||||
assert_eq!(pipenv_env_in(&shop, &homes, None), Some(named_python));
|
||||
std::fs::write(&marker, "missing").unwrap();
|
||||
assert_eq!(pipenv_env_in(&shop, &homes, name), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod conda_tests {
|
||||
use super::*;
|
||||
@@ -1489,23 +1261,6 @@ mod env_manager_dir_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workon_homes_follow_pipenv_and_virtualenvwrapper() {
|
||||
let home = Path::new("/home/me");
|
||||
let order = |xdg: PathBuf| {
|
||||
let wrapper = home.join(".virtualenvs");
|
||||
if cfg!(windows) { [wrapper, xdg] } else { [xdg, wrapper] }
|
||||
};
|
||||
let defaults = order(home.join(".local/share/virtualenvs"));
|
||||
assert_eq!(workon_homes(home, env(&[("WORKON_HOME", "")])), defaults);
|
||||
assert_eq!(
|
||||
workon_homes(home, env(&[("WORKON_HOME", "/envs"), ("XDG_DATA_HOME", "/xdg/data")])),
|
||||
std::iter::once(PathBuf::from("/envs"))
|
||||
.chain(order(PathBuf::from("/xdg/data/virtualenvs")))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poetry_overrides_come_first_and_empty_ones_are_ignored() {
|
||||
let home = Path::new("/home/me");
|
||||
|
||||
@@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"java-usages",
|
||||
"1.18.0",
|
||||
"1.17.0",
|
||||
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -384,33 +384,15 @@ fn tool(bin: Option<PathBuf>, name: &str) -> Option<PathBuf> {
|
||||
|
||||
// ------------------------------------------------------------------ python
|
||||
|
||||
fn python_groups(root: &Path, project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
|
||||
fn python_groups(root: &Path, _project: &Path, s: &Settings, cancel: &CancellationToken) -> Vec<LibraryGroup> {
|
||||
let Some(python) = crate::apply::python_interpreter(root, s) else { return Vec::new() };
|
||||
let mut files = vec![python.clone()];
|
||||
files.extend(crate::venv_of(&python).map(|v| v.join("pyvenv.cfg")));
|
||||
let structure = &s.project_structure;
|
||||
let folders: Vec<PathBuf> = [root, project]
|
||||
.into_iter()
|
||||
.map(Path::to_path_buf)
|
||||
.chain(structure.content_roots.iter().chain(&structure.dependencies).map(|p| PathBuf::from(p.trim())))
|
||||
.collect();
|
||||
let user = outside_folders(crate::apply::interpreter_user_paths(&python, s), &folders);
|
||||
let key = std::iter::once(&python).chain(&user).map(|p| p.display().to_string()).collect::<Vec<_>>().join("\n");
|
||||
cached_cancellable(root, "python", key, &files, cancel, || {
|
||||
let mut group = python_libraries(&python, Some(root));
|
||||
if let Some(group) = &mut group {
|
||||
group.roots.extend(library_roots(user));
|
||||
}
|
||||
group.into_iter().collect()
|
||||
cached_cancellable(root, "python", python.display().to_string(), &files, cancel, || {
|
||||
python_libraries(&python, Some(root)).into_iter().collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// `paths` without the ones inside, or around, one of the project's `folders`: a library root
|
||||
/// opens its files read-only, and the project's own code stays editable.
|
||||
fn outside_folders(paths: Vec<PathBuf>, folders: &[PathBuf]) -> Vec<PathBuf> {
|
||||
paths.into_iter().filter(|p| !folders.iter().any(|f| p.starts_with(f) || f.starts_with(p))).collect()
|
||||
}
|
||||
|
||||
/// Standard library and site-packages folders of a Python interpreter.
|
||||
pub fn python_libraries(python: &Path, root: Option<&Path>) -> Option<LibraryGroup> {
|
||||
// In a neutral directory: the working directory comes first on `sys.path` for `-c`.
|
||||
@@ -420,16 +402,6 @@ pub fn python_libraries(python: &Path, root: Option<&Path>) -> Option<LibraryGro
|
||||
group(name, "python", library_roots(parse_python_paths(&out)))
|
||||
}
|
||||
|
||||
/// `sys.path` of `python` started on its own; `None` when it cannot run or was cancelled.
|
||||
pub fn python_sys_path(python: &Path, cancel: &CancellationToken) -> Option<Vec<PathBuf>> {
|
||||
// In a neutral directory and without the IDE's own `PYTHONPATH`: neither belongs to the
|
||||
// interpreter. `-c` puts `''` first for the working directory; a hook may add non-strings.
|
||||
let dir = crate::python::neutral_dir()?;
|
||||
let script = "import json,sys;print(json.dumps([p for p in sys.path if isinstance(p,str) and p]))";
|
||||
let out = query_in_cancellable(python, &["-c", script], dir.path(), &[("PYTHONPATH", "")], QUERY_TIMEOUT, cancel)?;
|
||||
Some(parse_python_paths(&out))
|
||||
}
|
||||
|
||||
pub(crate) fn parse_python_paths(out: &str) -> Vec<PathBuf> {
|
||||
let json = out.lines().rev().find(|l| l.trim_start().starts_with('[')).unwrap_or("[]");
|
||||
serde_json::from_str::<Vec<Option<String>>>(json)
|
||||
@@ -1118,58 +1090,6 @@ fn package_label(dep: &crate::zig::ZonDependency, hash: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod python_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn user_paths_inside_or_around_the_project_are_not_library_roots() {
|
||||
let folders = [PathBuf::from("/work/app"), PathBuf::from("/work/attached")];
|
||||
let paths = ["/work/app/stubs", "/work/app", "/work", "/work/attached/src", "/shared/lib", "/work/apple"];
|
||||
assert_eq!(
|
||||
outside_folders(paths.iter().map(PathBuf::from).collect(), &folders),
|
||||
[PathBuf::from("/shared/lib"), PathBuf::from("/work/apple")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_libraries_list_user_paths_outside_the_project_only() {
|
||||
let Some(python) = crate::exec::which("python3") else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = tmp.path().canonicalize().unwrap();
|
||||
let (root, attached, shared) = (base.join("app"), base.join("attached"), base.join("shared"));
|
||||
for dir in [&root.join("stubs"), &attached.join("src"), &shared] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
}
|
||||
let text = |p: &Path| p.to_string_lossy().into_owned();
|
||||
let mut s = Settings::default();
|
||||
s.languages.python.interpreter = text(&python);
|
||||
s.project_structure.dependencies = vec![text(&attached)];
|
||||
s.languages.python.interpreter_paths =
|
||||
[(text(&python), vec![text(&root.join("stubs")), text(&attached.join("src")), text(&base), text(&shared)])]
|
||||
.into();
|
||||
let groups = python_groups(&root, &root, &s, &CancellationToken::new());
|
||||
let roots: Vec<&Path> = groups.iter().flat_map(|g| &g.roots).map(|r| Path::new(&*r.path)).collect();
|
||||
assert!(roots.contains(&shared.as_path()), "{roots:?}");
|
||||
// The project's own folders stay editable: a library root opens read-only.
|
||||
for inside in [root.join("stubs"), attached.join("src"), base.clone()] {
|
||||
assert!(!roots.contains(&inside.as_path()), "{roots:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sys_path_is_the_interpreters_own_and_can_be_cancelled() {
|
||||
let Some(python) = crate::exec::which("python3") else { return };
|
||||
let paths = python_sys_path(&python, &CancellationToken::new()).unwrap();
|
||||
// Site hooks can add non-filesystem entries for editable packages.
|
||||
assert!(paths.iter().any(|p| p.is_absolute()), "{paths:?}");
|
||||
let cancelled = CancellationToken::new();
|
||||
cancelled.cancel();
|
||||
assert_eq!(python_sys_path(&python, &cancelled), None);
|
||||
assert_eq!(python_sys_path(Path::new("/no/such/python"), &CancellationToken::new()), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod go_cache_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -28,22 +28,18 @@ pub enum VenvTool {
|
||||
Poetry,
|
||||
/// `conda create -n <name> -y` for a bare name, else `-p <location>` (conda must be on PATH).
|
||||
Conda,
|
||||
/// `pipenv --python <base>` in the project (pipenv must be on PATH).
|
||||
Pipenv,
|
||||
}
|
||||
|
||||
/// Creates a virtualenv at `location` with `tool` and returns its interpreter.
|
||||
/// `base` is the interpreter uv / venv build on, or the one poetry's / pipenv's env uses.
|
||||
/// `install` also installs the packages the project declares, for the tool that reads them (pipenv).
|
||||
/// `base` is the interpreter uv / venv build on, or the one poetry's env uses.
|
||||
pub fn create_venv(
|
||||
tool: VenvTool,
|
||||
base: &Path,
|
||||
location: &Path,
|
||||
install: bool,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &dyn Fn(String),
|
||||
) -> IdeResult<Sdk> {
|
||||
create_venv_with(tool, base, location, install, which, cancel, on_line)
|
||||
create_venv_with(tool, base, location, which, cancel, on_line)
|
||||
}
|
||||
|
||||
/// [`create_venv`] with the tool lookup injectable (tests fake `uv` / `poetry`).
|
||||
@@ -51,7 +47,6 @@ pub(crate) fn create_venv_with(
|
||||
tool: VenvTool,
|
||||
base: &Path,
|
||||
location: &Path,
|
||||
install: bool,
|
||||
which: impl Fn(&str) -> Option<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &dyn Fn(String),
|
||||
@@ -91,7 +86,6 @@ pub(crate) fn create_venv_with(
|
||||
}
|
||||
VenvTool::Poetry => create_poetry_env(base, location, &which, cancel, on_line),
|
||||
VenvTool::Conda => create_conda_env(base, location, &which, cancel, on_line),
|
||||
VenvTool::Pipenv => create_pipenv_env(base, location, install, &which, cancel, on_line),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,79 +117,6 @@ fn create_poetry_env(
|
||||
.map(PathBuf::from)
|
||||
.ok_or_else(|| IdeError::internal("poetry created no environment".to_owned()))?;
|
||||
let python = home.join(bin_dir()).join(exe("python"));
|
||||
crate::discover::python_sdk(&python, "pipenv", Some(project))
|
||||
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
|
||||
}
|
||||
|
||||
/// An environment that already exists is reused rather than rebuilt: the tools replace one
|
||||
/// built on another Python without asking, losing its packages. If `base` is another Python
|
||||
/// version than the environment's, nothing is changed and the error says how to go on.
|
||||
fn reuse_existing_env(home: &Path, base: &Path, remove: &str) -> IdeResult<()> {
|
||||
let short = |version: &str| version.split('.').take(2).collect::<Vec<_>>().join(".");
|
||||
let existing = crate::discover::pyvenv_version(&home.join(bin_dir()).join(exe("python")));
|
||||
let wanted = query_in(base, &["--version"], None, &[], Duration::from_secs(15))
|
||||
.and_then(|v| v.strip_prefix("Python ").map(str::to_owned));
|
||||
match (existing.as_deref().map(short), wanted.as_deref().map(short)) {
|
||||
(Some(existing), Some(wanted)) if existing != wanted => Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::AlreadyExists,
|
||||
format!(
|
||||
"{} already holds a Python {existing} environment, not Python {wanted} like the base interpreter. \
|
||||
Select it under Existing environment, or remove it first with `{remove}`.",
|
||||
home.display()
|
||||
),
|
||||
)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pipenv's environment for the project (`location` is a hint inside it, as for Poetry: pipenv
|
||||
/// keeps its envs under `WORKON_HOME`). `pipenv --python <base>` creates it when `pipenv --venv`
|
||||
/// finds none, writing a `Pipfile` (from `requirements.txt` if there is one) when the project
|
||||
/// has none. `install` then runs `pipenv install --dev` for the packages of the `Pipfile`.
|
||||
fn create_pipenv_env(
|
||||
base: &Path,
|
||||
location: &Path,
|
||||
install: bool,
|
||||
which: &dyn Fn(&str) -> Option<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &dyn Fn(String),
|
||||
) -> IdeResult<Sdk> {
|
||||
let pipenv = which("pipenv")
|
||||
.ok_or_else(|| IdeError::unavailable("Pipenv is not installed (install it from https://pipenv.pypa.io)"))?;
|
||||
let project = location
|
||||
.parent()
|
||||
.filter(|p| p.is_dir())
|
||||
.ok_or_else(|| IdeError::invalid("Pipenv environments need an open project directory"))?;
|
||||
// No prompts or spinner, and the project's own environment even when the IDE was
|
||||
// started from inside another virtualenv.
|
||||
const ENV: [(&str, &str); 3] = [("PIPENV_YES", "1"), ("PIPENV_NOSPIN", "1"), ("PIPENV_IGNORE_VIRTUALENVS", "1")];
|
||||
let env = ENV.map(|(k, v)| (k.to_owned(), v.to_owned()));
|
||||
let venv = || {
|
||||
query_in_cancellable(&pipenv, &["--venv"], project, &ENV, Duration::from_secs(30), cancel)
|
||||
.map(PathBuf::from)
|
||||
.filter(|home| home.join("pyvenv.cfg").is_file())
|
||||
};
|
||||
match venv() {
|
||||
Some(home) => reuse_existing_env(&home, base, "pipenv --rm")?,
|
||||
None => {
|
||||
let args = ["--python".to_owned(), base.to_string_lossy().into_owned()];
|
||||
stream(&pipenv, &args, Some(project), &env, cancel, on_line)?;
|
||||
}
|
||||
}
|
||||
// Decided after creation: pipenv may just have written the `Pipfile`, or found one above the project.
|
||||
let pipfile_dir = crate::discover::pipfile_dir(project);
|
||||
if install && pipfile_dir.is_some() {
|
||||
stream(&pipenv, &["install".to_owned(), "--dev".to_owned()], Some(project), &env, cancel, on_line)?;
|
||||
}
|
||||
let home = venv().ok_or_else(|| IdeError::internal("pipenv created no environment".to_owned()))?;
|
||||
// Pipenv records the project only when it creates the environment: one it reuses after an
|
||||
// interrupted creation has no `.project`, and detection would not know whose it is.
|
||||
let record = home.join(".project");
|
||||
if !record.exists() {
|
||||
let owner = pipfile_dir.as_deref().unwrap_or(project);
|
||||
let _ = std::fs::write(record, owner.to_string_lossy().as_bytes());
|
||||
}
|
||||
let python = home.join(bin_dir()).join(exe("python"));
|
||||
crate::discover::python_sdk(&python, "venv", Some(project))
|
||||
.ok_or_else(|| IdeError::internal(format!("{} was not created", python.display())))
|
||||
}
|
||||
|
||||
@@ -578,31 +578,6 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
assert_eq!(configs[6].args, ["manage.py", "test", "polls"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_python_configs_keep_their_explicit_interpreter() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let default = fake_venv(root, ".venv");
|
||||
let override_python = fake_venv(&root.join("member"), ".override");
|
||||
let relative_python = override_python.strip_prefix(root.join("member")).unwrap();
|
||||
let mut settings = Settings::default();
|
||||
settings.languages.python.interpreter = default.to_string_lossy().into_owned();
|
||||
|
||||
for command in [&override_python, relative_python] {
|
||||
for kind in ["python", "pytest", "django-test"] {
|
||||
let command = command.to_string_lossy();
|
||||
let mut config = run(kind, &command, &["main.py"]);
|
||||
config.detected = false;
|
||||
config.cwd = Some(Path::new("member").into());
|
||||
apply_to_run_configs(std::slice::from_mut(&mut config), root, &settings);
|
||||
assert_eq!(config.command, command);
|
||||
assert_eq!(config.env["VIRTUAL_ENV"], root.join("member/.override").to_string_lossy());
|
||||
let saved = without_derived(&config, root, &settings);
|
||||
assert_eq!(saved.command, command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn npm_config_runs_on_its_own_node_interpreter() {
|
||||
if cfg!(windows) {
|
||||
@@ -1510,7 +1485,6 @@ fn env_tools_are_reported_missing_before_they_run() {
|
||||
crate::python::VenvTool::Uv,
|
||||
&base,
|
||||
&location,
|
||||
false,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
@@ -1521,7 +1495,6 @@ fn env_tools_are_reported_missing_before_they_run() {
|
||||
crate::python::VenvTool::Poetry,
|
||||
&base,
|
||||
&location,
|
||||
false,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
@@ -1532,24 +1505,12 @@ fn env_tools_are_reported_missing_before_they_run() {
|
||||
crate::python::VenvTool::Conda,
|
||||
&base,
|
||||
&location,
|
||||
false,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(conda.message.contains("conda is not installed"), "{}", conda.message);
|
||||
let pipenv = crate::python::create_venv_with(
|
||||
crate::python::VenvTool::Pipenv,
|
||||
&base,
|
||||
&location,
|
||||
true,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(pipenv.message.contains("Pipenv is not installed"), "{}", pipenv.message);
|
||||
// An existing environment is refused before any tool runs.
|
||||
std::fs::create_dir_all(&location).unwrap();
|
||||
std::fs::write(location.join("pyvenv.cfg"), "home = /python").unwrap();
|
||||
@@ -1557,7 +1518,6 @@ fn env_tools_are_reported_missing_before_they_run() {
|
||||
crate::python::VenvTool::Uv,
|
||||
&base,
|
||||
&location,
|
||||
false,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
@@ -1580,7 +1540,6 @@ fn an_existing_conda_environment_is_not_recreated() {
|
||||
crate::python::VenvTool::Conda,
|
||||
&base,
|
||||
&location,
|
||||
false,
|
||||
none,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
@@ -1631,7 +1590,6 @@ fn a_named_conda_environment_is_found_where_conda_put_it() {
|
||||
crate::python::VenvTool::Conda,
|
||||
&base,
|
||||
Path::new("ds"),
|
||||
false,
|
||||
which,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
@@ -1643,65 +1601,6 @@ fn a_named_conda_environment_is_found_where_conda_put_it() {
|
||||
assert!(again.message.contains("named ds already exists"), "{}", again.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn pipenv_creates_the_projects_environment_and_never_replaces_one() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tmp = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let project = tmp.join("shop");
|
||||
let home = tmp.join("workon").join(crate::discover::pipenv_env_name(&project));
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
let python = tmp.join("python");
|
||||
std::fs::write(&python, "#!/bin/sh\necho 'Python 3.12.1'\n").unwrap();
|
||||
std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
// `--venv` fails until the environment exists; `--python` creates it outside the project,
|
||||
// records the project in `.project` and writes a Pipfile.
|
||||
let pipenv = tmp.join("pipenv");
|
||||
std::fs::write(
|
||||
&pipenv,
|
||||
format!(
|
||||
"#!/bin/sh\nhome='{home}'\nif [ \"$1\" = --venv ]; then [ -f \"$home/pyvenv.cfg\" ] || exit 1; echo \"$home\"; exit 0; fi\n\
|
||||
[ \"$PIPENV_YES\" = 1 ] || exit 3\necho \"$@\" >> calls\n[ \"$1\" = --python ] || exit 0\n\
|
||||
mkdir -p \"$home/bin\"\ncp '{python}' \"$home/bin/python\"\necho 'version = 3.12.1' > \"$home/pyvenv.cfg\"\n\
|
||||
touch Pipfile\npwd -P > \"$home/.project\"\n",
|
||||
home = home.display(),
|
||||
python = python.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&pipenv, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let which = |tool: &str| (tool == "pipenv").then(|| pipenv.clone());
|
||||
let create = |install: bool| {
|
||||
crate::python::create_venv_with(
|
||||
crate::python::VenvTool::Pipenv,
|
||||
&python,
|
||||
&project.join(".venv"),
|
||||
install,
|
||||
which,
|
||||
&Default::default(),
|
||||
&|_| {},
|
||||
)
|
||||
};
|
||||
let calls = || std::fs::read_to_string(project.join("calls")).unwrap_or_default();
|
||||
// The project had no Pipfile: the one pipenv writes is installed from, as asked.
|
||||
let sdk = create(true).unwrap();
|
||||
assert_eq!(&*sdk.path, home.join("bin/python").as_path());
|
||||
assert_eq!((sdk.name.as_str(), sdk.source.as_str()), ("Python 3.12 (Pipenv: shop)", "pipenv"));
|
||||
assert_eq!(calls(), format!("--python {}\ninstall --dev\n", python.display()));
|
||||
// An existing environment is reused, never created again with `--python` (which replaces one
|
||||
// of another version); one pipenv left without `.project` is still the project's.
|
||||
std::fs::remove_file(home.join(".project")).unwrap();
|
||||
assert_eq!(create(false).unwrap().source, "pipenv");
|
||||
assert_eq!(calls().lines().count(), 2);
|
||||
// On another Python than the base, nothing runs and the error says what to do.
|
||||
std::fs::write(home.join("pyvenv.cfg"), "version = 3.11.4\n").unwrap();
|
||||
let err = create(true).unwrap_err();
|
||||
assert!(err.message.contains("Python 3.11 environment, not Python 3.12"), "{}", err.message);
|
||||
assert!(err.message.contains("pipenv --rm"), "{}", err.message);
|
||||
assert_eq!(calls().lines().count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_dir_is_fresh_and_empty() {
|
||||
let a = crate::python::neutral_dir().unwrap();
|
||||
|
||||
@@ -42,16 +42,6 @@ pub(crate) fn server_package(command: &str, path: &OsStr) -> Option<PathBuf> {
|
||||
package_dir(&find_command(command, path)?, PACKAGE)
|
||||
}
|
||||
|
||||
/// Whether `root`'s manifest depends on Vue or `@vue/cli-service`, i.e. it is a Vue project.
|
||||
/// The tsserver plugin host that `vtsls` carries cannot be loaded into the native TS7
|
||||
/// server, so this decides whether the tsserver route stays for a Vue project.
|
||||
pub(crate) fn vue_project(root: &Path) -> bool {
|
||||
let Ok(manifest) = std::fs::read_to_string(root.join("package.json")) else {
|
||||
return false;
|
||||
};
|
||||
package_dependencies(&manifest).iter().any(|d| d == "vue" || d == CLI_SERVICE)
|
||||
}
|
||||
|
||||
/// vtsls `globalPlugins` entry loading the Vue plugin shipped with `package`.
|
||||
pub(crate) fn tsserver_plugin(package: &Path) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
|
||||
@@ -24,11 +24,6 @@ const CANCEL_CHECK_LINES: u32 = 256;
|
||||
/// How many matches a file keeps before claiming them from the shared budget: each file
|
||||
/// searched in parallel holds about this many unclaimed matches at most, not up to the whole budget.
|
||||
const CLAIM_BATCH: u32 = 64;
|
||||
/// Bytes at the start of a text that the searcher checks for binary content up front.
|
||||
const BINARY_HEAD_LEN: usize = 64 * 1024;
|
||||
/// Files longer than this hold no text the parser takes, whatever their encoding (UTF-16 halves
|
||||
/// the bytes of ASCII text, nothing else comes close): their comments and strings are not looked for.
|
||||
const MAX_LITERALS_FILE_BYTES: u64 = 2 * crate::MAX_LITERALS_TEXT_BYTES as u64;
|
||||
|
||||
pub(crate) struct Request<'a> {
|
||||
pub root: &'a Path,
|
||||
@@ -68,11 +63,9 @@ impl Control<'_> {
|
||||
|
||||
/// Also polls the cancellation token (which takes a lock).
|
||||
fn should_stop(&self) -> bool {
|
||||
self.stopped() || self.cancel_requested()
|
||||
}
|
||||
|
||||
/// Polls the cancellation token only: a search stopped by its match limit is not cancelled.
|
||||
fn cancel_requested(&self) -> bool {
|
||||
if self.stopped() {
|
||||
return true;
|
||||
}
|
||||
if self.cancel.is_cancelled() {
|
||||
self.cancelled.store(true, Relaxed);
|
||||
self.stop.store(true, Relaxed);
|
||||
@@ -309,37 +302,22 @@ impl Ctx<'_> {
|
||||
{
|
||||
return;
|
||||
}
|
||||
// The search context needs the whole text to find comments and string literals. A file
|
||||
// whose text is past the longest the parser takes has none, so it is not read for them.
|
||||
// The search context needs the whole text to find comments and string literals.
|
||||
let in_context = match self.literals {
|
||||
Some(literals) => 'context: {
|
||||
Some(literals) => {
|
||||
let text = match (self.text.overlay)(path) {
|
||||
Some(text) => text,
|
||||
None => {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) if meta.len() > MAX_LITERALS_FILE_BYTES => {
|
||||
if self.context.needs_literals() {
|
||||
return;
|
||||
}
|
||||
break 'context None;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(_) => return,
|
||||
}
|
||||
match std::fs::read(path) {
|
||||
Ok(bytes) => match String::from_utf8(bytes) {
|
||||
Ok(text) => text,
|
||||
// Binary content has nothing to classify.
|
||||
Err(e) => {
|
||||
match ide_vfs::decode_text(e.as_bytes(), (self.text.fallback)(path).as_deref()) {
|
||||
Some(text) => text,
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
None => match std::fs::read(path) {
|
||||
Ok(bytes) => match String::from_utf8(bytes) {
|
||||
Ok(text) => text,
|
||||
// Binary content has nothing to classify.
|
||||
Err(e) => match (self.text.decode)(path, e.as_bytes()) {
|
||||
Some(text) => text,
|
||||
None => return,
|
||||
},
|
||||
Err(_) => return,
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(_) => return,
|
||||
},
|
||||
};
|
||||
let ranges = literals(path, &text);
|
||||
if ranges.is_none() && self.context.needs_literals() {
|
||||
@@ -376,8 +354,7 @@ impl Ctx<'_> {
|
||||
}
|
||||
|
||||
/// Streams the file's bytes; a file that turns out not to be UTF-8 (GBK,
|
||||
/// UTF-16 …) is searched again in its text decoded as the editor opens it,
|
||||
/// which is decoded as it is read.
|
||||
/// UTF-16 …) is searched again in the text `decode` gives it.
|
||||
fn search_disk<'s>(
|
||||
&'s self,
|
||||
path: &Path,
|
||||
@@ -385,7 +362,7 @@ impl Ctx<'_> {
|
||||
searcher: &mut Searcher,
|
||||
sink: &mut FileSink<'s>,
|
||||
) -> io::Result<()> {
|
||||
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: true });
|
||||
let mut reader = Utf8Probe::new(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl });
|
||||
let result = searcher.search_reader(matcher, &mut reader, &mut *sink);
|
||||
// NUL bytes in the head of UTF-16 text stop the byte search; later ones mark binary.
|
||||
let decode = if sink.binary {
|
||||
@@ -397,29 +374,14 @@ impl Ctx<'_> {
|
||||
if !decode || (self.ctl.stopped() && sink.claimed == 0) {
|
||||
return result;
|
||||
}
|
||||
// Only cancellation ends the reading: a search that hit the match limit still fills its claim.
|
||||
let open = || Ok(StopReader { inner: std::fs::File::open(path)?, ctl: &self.ctl, hard: false });
|
||||
let Some(text) = ide_vfs::decode_stream(open, (self.text.fallback)(path).as_deref())? else {
|
||||
let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else {
|
||||
sink.binary = true;
|
||||
return Ok(());
|
||||
};
|
||||
let mut text = text;
|
||||
// Text held whole gets the searcher's binary check only on its first 64 KiB and on the
|
||||
// lines that match; this keeps that for the text read piece by piece.
|
||||
let mut head = Vec::with_capacity(BINARY_HEAD_LEN);
|
||||
(&mut text).take(BINARY_HEAD_LEN as u64).read_to_end(&mut head)?;
|
||||
if head.contains(&0) {
|
||||
sink.binary = true;
|
||||
return Ok(());
|
||||
}
|
||||
let claimed = sink.claimed;
|
||||
*sink = FileSink::new(matcher, &self.ctl, None);
|
||||
sink.claimed = claimed;
|
||||
sink.binary_in_matches = true;
|
||||
searcher.set_binary_detection(BinaryDetection::none());
|
||||
let result = searcher.search_reader(matcher, io::Cursor::new(head).chain(text), sink);
|
||||
searcher.set_binary_detection(BinaryDetection::quit(0));
|
||||
result
|
||||
searcher.search_slice(matcher, text.as_bytes(), sink)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -442,8 +404,6 @@ struct FileSink<'a> {
|
||||
/// file is searched again under the claim of its byte search.
|
||||
claimed: u32,
|
||||
binary: bool,
|
||||
/// A NUL byte in a matching line marks the file binary (the searcher's own check is off).
|
||||
binary_in_matches: bool,
|
||||
ticks: u32,
|
||||
/// Scratch buffers reused across lines.
|
||||
found: Vec<(usize, usize)>,
|
||||
@@ -465,7 +425,6 @@ impl<'a> FileSink<'a> {
|
||||
count: 0,
|
||||
claimed: 0,
|
||||
binary: false,
|
||||
binary_in_matches: false,
|
||||
ticks: 0,
|
||||
found: Vec::new(),
|
||||
ranges: Vec::new(),
|
||||
@@ -508,10 +467,6 @@ impl Sink for FileSink<'_> {
|
||||
type Error = io::Error;
|
||||
|
||||
fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result<bool, io::Error> {
|
||||
if self.binary_in_matches && memchr::memchr(0, m.bytes()).is_some() {
|
||||
self.binary = true;
|
||||
return Ok(false);
|
||||
}
|
||||
self.ticks += 1;
|
||||
let stop = self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop());
|
||||
// Unless cancelled, a decoded file still fills the claim its byte search took.
|
||||
@@ -579,17 +534,15 @@ impl Sink for FileSink<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Aborts disk reads once the search is cancelled, or with `hard` once it is stopped.
|
||||
/// Aborts disk reads once the search is stopped or cancelled.
|
||||
struct StopReader<'a, R> {
|
||||
inner: R,
|
||||
ctl: &'a Control<'a>,
|
||||
hard: bool,
|
||||
}
|
||||
|
||||
impl<R: Read> Read for StopReader<'_, R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let stop = if self.hard { self.ctl.should_stop() } else { self.ctl.cancel_requested() };
|
||||
if stop {
|
||||
if self.ctl.should_stop() {
|
||||
return Err(io::Error::other("search stopped"));
|
||||
}
|
||||
self.inner.read(buf)
|
||||
|
||||
@@ -112,14 +112,8 @@ impl SearchContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// The longest file text, in bytes, that is searched for comments and string literals: the
|
||||
/// parser's limit (`ide_language::MAX_PARSE_BYTES`), above which a [`Literals`] finds none.
|
||||
/// The search leaves a longer text unread by it.
|
||||
pub const MAX_LITERALS_TEXT_BYTES: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// Comments and string literals of a file's text (sorted, non-overlapping),
|
||||
/// or `None` when its language has no syntax tree or the text is longer than
|
||||
/// [`MAX_LITERALS_TEXT_BYTES`].
|
||||
/// or `None` when its language has no syntax tree.
|
||||
pub type Literals<'a> = &'a (dyn Fn(&Path, &str) -> Option<Vec<LiteralRange>> + Sync);
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -204,23 +198,21 @@ pub struct SearchSummary {
|
||||
/// Text of unsaved open documents takes precedence over disk content.
|
||||
pub type Overlay<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
|
||||
|
||||
/// The encoding to read a file with when it is not UTF-8 and the encoding detected for it is not
|
||||
/// trusted to be right (GBK, UTF-16 …): its label, or `None` to go by what is detected.
|
||||
pub type FallbackEncoding<'a> = &'a (dyn Fn(&Path) -> Option<String> + Sync);
|
||||
/// Text of a file whose bytes are not UTF-8 (GBK, UTF-16 …); `None` for binary content.
|
||||
pub type Decode<'a> = &'a (dyn Fn(&Path, &[u8]) -> Option<String> + Sync);
|
||||
|
||||
/// Where a search reads file text from: the open document when `overlay` has
|
||||
/// it, else the file on disk, decoded as the editor opens it when it is not UTF-8
|
||||
/// (`fallback` picks the encoding that [`ide_vfs::decode_text`] takes).
|
||||
/// it, else the file on disk, decoded by `decode` when it is not UTF-8.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct TextSource<'a> {
|
||||
pub overlay: Overlay<'a>,
|
||||
pub fallback: FallbackEncoding<'a>,
|
||||
pub decode: Decode<'a>,
|
||||
}
|
||||
|
||||
impl<'a> TextSource<'a> {
|
||||
/// Non-UTF-8 files decode as detected, without a configured fallback encoding.
|
||||
pub fn detected(overlay: Overlay<'a>) -> Self {
|
||||
Self { overlay, fallback: &|_| None }
|
||||
Self { overlay, decode: &|_, bytes| ide_vfs::decode_text(bytes, None) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
//! Searching a big file holds a bounded amount of it in memory, whatever its encoding and the
|
||||
//! search context. Allocations of the whole process are counted, so this is one test with
|
||||
//! sequential scenarios.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_search::{
|
||||
FileMatches, Literals, SearchContext, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context,
|
||||
};
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
|
||||
|
||||
struct Counting;
|
||||
|
||||
static LIVE: AtomicUsize = AtomicUsize::new(0);
|
||||
static PEAK: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
fn grow(by: usize) {
|
||||
let live = LIVE.fetch_add(by, Relaxed) + by;
|
||||
PEAK.fetch_max(live, Relaxed);
|
||||
}
|
||||
|
||||
unsafe impl GlobalAlloc for Counting {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
grow(layout.size());
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
|
||||
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
|
||||
grow(layout.size());
|
||||
unsafe { System.alloc_zeroed(layout) }
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
LIVE.fetch_sub(layout.size(), Relaxed);
|
||||
unsafe { System.dealloc(ptr, layout) }
|
||||
}
|
||||
|
||||
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
|
||||
if new_size >= layout.size() {
|
||||
grow(new_size - layout.size());
|
||||
} else {
|
||||
LIVE.fetch_sub(layout.size() - new_size, Relaxed);
|
||||
}
|
||||
unsafe { System.realloc(ptr, layout, new_size) }
|
||||
}
|
||||
}
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOC: Counting = Counting;
|
||||
|
||||
const MIB: usize = 1024 * 1024;
|
||||
/// What a search may hold at once: a few buffers of the reader and the decoder. The files are
|
||||
/// 16 to 40 MiB, so a search that reads one whole (or decodes it whole) is far over.
|
||||
const BOUND: usize = 4 * MIB;
|
||||
|
||||
fn query(context: SearchContext) -> SearchQuery {
|
||||
SearchQuery {
|
||||
pattern: "needle".into(),
|
||||
is_regex: false,
|
||||
case_sensitive: true,
|
||||
whole_word: false,
|
||||
include: vec![],
|
||||
exclude: vec![],
|
||||
scope: SearchScope::Project,
|
||||
max_matches: 1_000_000,
|
||||
context,
|
||||
include_excluded: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a search and returns its result with the most memory it held over what was live before.
|
||||
fn measured(
|
||||
root: &Path,
|
||||
context: SearchContext,
|
||||
literals: Option<Literals<'_>>,
|
||||
) -> (Vec<FileMatches>, SearchSummary, usize) {
|
||||
let out = Mutex::new(Vec::new());
|
||||
let before = LIVE.load(Relaxed);
|
||||
PEAK.store(before, Relaxed);
|
||||
let summary = search_in_context(
|
||||
root,
|
||||
&query(context),
|
||||
None,
|
||||
literals,
|
||||
TextSource::detected(&|_| None),
|
||||
&CancellationToken::new(),
|
||||
&|f| out.lock().unwrap().push(f),
|
||||
)
|
||||
.unwrap();
|
||||
let held = PEAK.load(Relaxed).saturating_sub(before);
|
||||
// The results are in `out` and count against the search; they are small.
|
||||
(out.into_inner().unwrap(), summary, held)
|
||||
}
|
||||
|
||||
fn write_repeated(path: &Path, bom: &[u8], block: &[u8], size: usize) {
|
||||
use std::io::Write;
|
||||
let mut file = std::io::BufWriter::new(std::fs::File::create(path).unwrap());
|
||||
file.write_all(bom).unwrap();
|
||||
for _ in 0..size / block.len() + 1 {
|
||||
file.write_all(block).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn utf16le(text: &str) -> Vec<u8> {
|
||||
text.encode_utf16().flat_map(u16::to_le_bytes).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searching_a_big_file_holds_a_bounded_part_of_it() {
|
||||
let block = "2026-11-22 13:00:01 INFO caf\u{e9} \u{4e2d}\u{6587} request ok\n".repeat(50)
|
||||
+ "2026-11-22 13:00:02 ERROR needle marker found\n";
|
||||
let latin_text = block.replace(['\u{4e2d}', '\u{6587}'], "x");
|
||||
let (latin1, _, _) = encoding_rs::WINDOWS_1252.encode(&latin_text);
|
||||
let (gbk, _, _) = encoding_rs::GBK.encode(&block);
|
||||
let parsed = Mutex::new(Vec::new());
|
||||
let literals = |path: &Path, _: &str| {
|
||||
parsed.lock().unwrap().push(path.file_name().unwrap().to_string_lossy().into_owned());
|
||||
None
|
||||
};
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut expected = Vec::new();
|
||||
for (name, bom, bytes, size) in [
|
||||
("latin1.log", &b""[..], &latin1[..], 16 * MIB),
|
||||
("gbk.log", &b""[..], &gbk[..], 16 * MIB),
|
||||
("utf16.log", &[0xFF, 0xFE][..], &utf16le(&block)[..], 24 * MIB),
|
||||
("utf8.log", &b""[..], block.as_bytes(), 40 * MIB),
|
||||
] {
|
||||
let one = tempfile::tempdir_in(dir.path()).unwrap();
|
||||
write_repeated(&one.path().join(name), bom, bytes, size);
|
||||
// Plain search: the byte search, then the decoded search of a non-UTF-8 file.
|
||||
let (files, summary, held) = measured(one.path(), SearchContext::Any, None);
|
||||
assert_eq!(files.len(), 1, "{name}");
|
||||
assert!(summary.matches > 100, "{name}");
|
||||
assert!(held < BOUND, "{name}: plain search held {} MiB", held / MIB);
|
||||
expected.push((name, summary.matches, one));
|
||||
}
|
||||
|
||||
// Searching with a context reads a file whole only to find its comments and strings, and
|
||||
// past the parser's limit it has none: the file is searched as it is read.
|
||||
for (name, matches, one) in &expected {
|
||||
for context in [SearchContext::ExceptComments, SearchContext::ExceptCommentsAndStringLiterals] {
|
||||
let (files, summary, held) = measured(one.path(), context, Some(&literals));
|
||||
if *name == "utf8.log" {
|
||||
assert_eq!(summary.matches, *matches, "{name} {context:?}");
|
||||
assert_eq!(files.len(), 1);
|
||||
assert!(held < BOUND, "{name}: {context:?} held {} MiB", held / MIB);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (_, only_in, held) = measured(expected[3].2.path(), SearchContext::InComments, Some(&literals));
|
||||
assert_eq!(only_in.matches, 0, "a file without comments has no match in them");
|
||||
assert!(held < BOUND, "held {} MiB", held / MIB);
|
||||
let parsed = parsed.into_inner().unwrap();
|
||||
assert!(parsed.iter().any(|name| name == "gbk.log"), "files within the limit are still analysed");
|
||||
assert!(!parsed.iter().any(|name| name == "utf8.log"), "a 40 MiB text is never handed to the parser");
|
||||
}
|
||||
@@ -890,7 +890,8 @@ fn non_utf8_files_use_the_given_decoder() {
|
||||
// Text too short to detect reliably decodes with the configured encoding.
|
||||
let p = project(&[("a.txt", &gbk("中文\n"))]);
|
||||
let out = Mutex::new(Vec::new());
|
||||
let source = TextSource { overlay: &|_| None, fallback: &|_| Some("gbk".into()) };
|
||||
let decode = |_: &Path, bytes: &[u8]| ide_vfs::decode_text(bytes, Some("gbk"));
|
||||
let source = TextSource { overlay: &|_| None, decode: &decode };
|
||||
ide_search::search_in_context(p.path(), &query("中文"), None, None, source, &CancellationToken::new(), &|f| {
|
||||
out.lock().unwrap().push(f)
|
||||
})
|
||||
|
||||
@@ -1,200 +0,0 @@
|
||||
//! Files that are not UTF-8 are decoded while they are searched. Searching the text decoded whole
|
||||
//! (what an unsaved editor buffer of the file is) is the reference: the matches must be the same.
|
||||
|
||||
use ide_core::CancellationToken;
|
||||
use ide_search::{FileMatches, SearchQuery, SearchScope, SearchSummary, TextSource, search_in_context};
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
fn query(pattern: &str, is_regex: bool) -> SearchQuery {
|
||||
SearchQuery {
|
||||
pattern: pattern.into(),
|
||||
is_regex,
|
||||
case_sensitive: false,
|
||||
whole_word: false,
|
||||
include: vec![],
|
||||
exclude: vec![],
|
||||
scope: SearchScope::Project,
|
||||
max_matches: 1_000_000,
|
||||
context: Default::default(),
|
||||
include_excluded: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(root: &Path, q: &SearchQuery, source: TextSource<'_>) -> (Vec<FileMatches>, SearchSummary) {
|
||||
let out = Mutex::new(Vec::new());
|
||||
let summary =
|
||||
search_in_context(root, q, None, None, source, &CancellationToken::new(), &|f| out.lock().unwrap().push(f))
|
||||
.unwrap();
|
||||
let mut files = out.into_inner().unwrap();
|
||||
files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
|
||||
(files, summary)
|
||||
}
|
||||
|
||||
/// The matches of every file in `root`, read from disk and from its whole decoded text.
|
||||
fn both_ways(root: &Path, q: &SearchQuery, fallback: Option<&str>) -> (String, String) {
|
||||
let streamed = run(root, q, TextSource { overlay: &|_| None, fallback: &|_| fallback.map(str::to_owned) });
|
||||
let whole = run(
|
||||
root,
|
||||
q,
|
||||
TextSource {
|
||||
overlay: &|path| ide_vfs::decode_text(&std::fs::read(path).unwrap(), fallback),
|
||||
fallback: &|_| None,
|
||||
},
|
||||
);
|
||||
let show = |(files, summary): (Vec<FileMatches>, SearchSummary)| {
|
||||
format!("{:#?}\nmatches {} limit {}", files, summary.matches, summary.limit_hit)
|
||||
};
|
||||
(show(streamed), show(whole))
|
||||
}
|
||||
|
||||
fn first_difference(a: &str, b: &str) -> String {
|
||||
let (a, b): (Vec<_>, Vec<_>) = (a.lines().collect(), b.lines().collect());
|
||||
let at = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
|
||||
format!(
|
||||
"line {at}:\nstreamed {:?}\nwhole {:?}",
|
||||
&a[at.saturating_sub(3)..a.len().min(at + 3)],
|
||||
&b[at.saturating_sub(3)..b.len().min(at + 3)]
|
||||
)
|
||||
}
|
||||
|
||||
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
|
||||
let mut bytes = if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
|
||||
for unit in text.encode_utf16() {
|
||||
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Lines of mixed width: ASCII, accents, CJK, astral characters (surrogate pairs), CRLF.
|
||||
fn lines(count: usize) -> String {
|
||||
let mut text = String::new();
|
||||
for i in 0..count {
|
||||
match i % 6 {
|
||||
0 => text.push_str(&format!("{i} needle in plain ascii\n")),
|
||||
1 => text.push_str(&format!("{i} caf\u{e9} needle cr\u{e8}me\n")),
|
||||
2 => text.push_str(&format!("{i} \u{4e2d}\u{6587} needle \u{6d4b}\u{8bd5}\n")),
|
||||
3 => text.push_str(&format!("{i} \u{1f600} needle \u{1f4a9}\n")),
|
||||
4 => text.push_str(&format!("{i} crlf needle\r\n")),
|
||||
_ => text.push_str(&format!("{i} nothing here\n")),
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn write(dir: &Path, name: &str, bytes: &[u8]) {
|
||||
std::fs::write(dir.join(name), bytes).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_files_give_the_matches_of_their_whole_text() {
|
||||
let wide = lines(12_000);
|
||||
let gbk_text = wide.replace(['\u{1f600}', '\u{1f4a9}', '\u{e9}', '\u{e8}'], "");
|
||||
let latin_text = wide.replace(|c: char| c as u32 > 0xff, "");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// (BOM-less UTF-16 is not searched in decoded text, and not covered here: only the byte search sees it.)
|
||||
// Each file is well past the sizes the decoder reads at a time (64 KiB).
|
||||
assert!(wide.len() > 250_000);
|
||||
write(dir.path(), "utf16le_bom.txt", &utf16(&wide, true, false));
|
||||
write(dir.path(), "utf16be_bom.txt", &utf16(&wide, true, true));
|
||||
write(dir.path(), "gbk.txt", &encoding_rs::GBK.encode(&gbk_text).0);
|
||||
write(dir.path(), "latin1.txt", &encoding_rs::WINDOWS_1252.encode(&latin_text).0);
|
||||
write(dir.path(), "utf8.txt", wide.as_bytes());
|
||||
|
||||
let queries = [
|
||||
query("needle", false),
|
||||
query("caf\u{e9}", false),
|
||||
query("\u{1f600}", false),
|
||||
query("\u{4e2d}\u{6587} needle", false),
|
||||
query(r"\d+ \S+ needle", true),
|
||||
query(r"needle\r?$", true),
|
||||
// A multi-line pattern reads the whole text, however it arrives.
|
||||
query("needle in plain ascii\n1 caf", false),
|
||||
SearchQuery { case_sensitive: true, whole_word: true, ..query("needle", false) },
|
||||
];
|
||||
for q in &queries {
|
||||
for fallback in [None, Some("gbk"), Some("windows-1252")] {
|
||||
let (streamed, whole) = both_ways(dir.path(), q, fallback);
|
||||
assert!(
|
||||
streamed == whole,
|
||||
"{:?} fallback {fallback:?}\n{}",
|
||||
q.pattern,
|
||||
first_difference(&streamed, &whole)
|
||||
);
|
||||
assert!(streamed.len() > 100, "{:?} found nothing", q.pattern);
|
||||
}
|
||||
}
|
||||
// The match limit keeps the first matches of a file, and files take their share in any order:
|
||||
// one file at a time.
|
||||
for name in ["utf16le_bom.txt", "utf16be_bom.txt", "gbk.txt", "latin1.txt"] {
|
||||
for max_matches in [7, 64, 65, 5_000] {
|
||||
let q = SearchQuery { max_matches, include: vec![name.into()], ..query("needle", false) };
|
||||
let (streamed, whole) = both_ways(dir.path(), &q, None);
|
||||
assert!(streamed == whole, "{name} limit {max_matches}\n{}", first_difference(&streamed, &whole));
|
||||
assert!(streamed.contains(&format!("matches {max_matches} limit true")), "{name} {max_matches}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_files_keep_their_multibyte_characters_across_every_read_boundary() {
|
||||
// A character sits on each of the 64 KiB read boundaries, at all alignments.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for pad in 0..8usize {
|
||||
let mut gbk = "x".repeat(64 * 1024 - 5 + pad);
|
||||
let mut utf16_text = gbk.clone();
|
||||
for i in 0..40 {
|
||||
gbk.push_str("\u{4e2d}\u{6587}");
|
||||
utf16_text.push_str(if i % 2 == 0 { "\u{1f600}" } else { "\u{4e2d}" });
|
||||
gbk.push_str(&"y".repeat(i % 3));
|
||||
utf16_text.push_str(&"y".repeat(i % 3));
|
||||
}
|
||||
gbk.push_str("yy needle\n");
|
||||
utf16_text.push_str("yy needle\n");
|
||||
write(dir.path(), &format!("gbk{pad}.txt"), &encoding_rs::GBK.encode(&gbk).0);
|
||||
write(dir.path(), &format!("utf16_{pad}.txt"), &utf16(&utf16_text, true, pad % 2 == 0));
|
||||
write(
|
||||
dir.path(),
|
||||
&format!("latin{pad}.txt"),
|
||||
&[gbk.as_bytes()[..64 * 1024 - 7 + pad].to_vec(), b"\xe9\xe8 needle\n".to_vec()].concat(),
|
||||
);
|
||||
}
|
||||
for pattern in ["needle", "y+ needle", "\u{4e2d}\u{6587}"] {
|
||||
let q = query(pattern, pattern.contains('+'));
|
||||
let (streamed, whole) = both_ways(dir.path(), &q, None);
|
||||
assert!(streamed == whole, "{pattern}\n{}", first_difference(&streamed, &whole));
|
||||
assert!(streamed.len() > 100, "{pattern} found nothing");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nul_characters_in_decoded_text_mark_it_binary_as_in_the_whole_text() {
|
||||
// Text held whole is binary when a NUL is in its first 64 KiB or in a line that matches,
|
||||
// which is not the same as a NUL anywhere.
|
||||
let text = lines(20_000);
|
||||
let with_nul = |at: &str| text.replacen(at, &format!("\0{at}"), 1);
|
||||
let cases = [
|
||||
("early", with_nul("5 nothing here"), false),
|
||||
("late in a line that does not match", with_nul("19997 nothing here"), true),
|
||||
("late in a line that matches", with_nul("19998 needle"), false),
|
||||
];
|
||||
for (name, text, found) in cases {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write(dir.path(), "a.txt", &utf16(&text, true, false));
|
||||
let (streamed, whole) = both_ways(dir.path(), &query("needle", false), None);
|
||||
assert!(streamed == whole, "{name}\n{}", first_difference(&streamed, &whole));
|
||||
assert_eq!(streamed.contains("a.txt"), found, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_is_decoded_when_its_search_reaches_the_byte_that_is_not_utf8() {
|
||||
// Valid UTF-8 up to the last line: the whole file is read as the detected Windows-1252.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write(dir.path(), "late.txt", &[lines(1500).as_bytes(), b"caf\xe9 needle\n"].concat());
|
||||
for q in [query("needle", false), query("caf", false)] {
|
||||
let (streamed, whole) = both_ways(dir.path(), &q, None);
|
||||
assert!(streamed == whole, "{}", first_difference(&streamed, &whole));
|
||||
assert!(streamed.contains("café"), "decoded as Windows-1252");
|
||||
}
|
||||
}
|
||||
@@ -81,12 +81,6 @@ fn npm_package(tool: &str) -> &str {
|
||||
}
|
||||
|
||||
impl Tools {
|
||||
/// The IDE's own installation of `tool` outside `node_modules` (Ruff's private virtualenv).
|
||||
fn managed_executable(&self, tool: &str) -> Option<PathBuf> {
|
||||
let spec = crate::registry::find(tool)?;
|
||||
self.exe_in(&crate::managed_bin_dir(&self.root, spec, self.platform)?, spec.commands[0])
|
||||
}
|
||||
|
||||
/// Explicit executable/script, then the nearest project package, then managed tools and PATH.
|
||||
pub fn formatter_command(&self, tool: &str, file: &Path, custom: Option<&Path>) -> IdeResult<Command> {
|
||||
self.resolve_formatter_command(tool, file, custom).map_err(|e| e.with_tool(tool))
|
||||
@@ -106,8 +100,6 @@ impl Tools {
|
||||
(package_bin(manifest.parent().unwrap(), tool)?, true)
|
||||
} else if self.root.join(&manifest).is_file() {
|
||||
(package_bin(&self.root.join(&package), tool)?, true)
|
||||
} else if let Some(path) = self.managed_executable(tool) {
|
||||
(path, false)
|
||||
} else {
|
||||
(self.which(tool).ok_or_else(|| IdeError::missing_tool(tool))?, false)
|
||||
};
|
||||
@@ -249,20 +241,6 @@ mod tests {
|
||||
assert_eq!(failure.data, Some(ErrorData::Tool { tool: "prettier".into(), missing: false }));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_formatter_the_ide_installed_in_its_virtualenv_is_found() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tools = Tools::with_paths(dir.path().join("tools"), OsString::new(), crate::platform::Platform::current());
|
||||
let file = dir.path().join("main.py");
|
||||
assert!(tools.formatter_command("ruff", &file, None).is_err());
|
||||
let bin = dir.path().join("tools/ruff/venv/bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
std::fs::write(bin.join("ruff"), "").unwrap();
|
||||
let command = tools.formatter_command("ruff", &file, None).unwrap();
|
||||
assert_eq!(Path::new(command.get_program()), bin.join("ruff"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn stderr_is_preserved_verbatim_even_when_longer_than_four_thousand_characters() {
|
||||
|
||||
+1
-105
@@ -13,8 +13,6 @@ use std::time::{Duration, Instant};
|
||||
/// How long a cancelled git's process group (remote helpers, `ssh`, credential helpers) gets
|
||||
/// to exit on `SIGTERM` before `SIGKILL`: git removes its `index.lock` on `SIGTERM`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
/// Longest the wait for a captured child sleeps before it looks at cancellation again.
|
||||
const POLL: Duration = Duration::from_millis(20);
|
||||
|
||||
/// A throwaway index file in the repository's Git directory.
|
||||
pub(crate) struct TempIndex(PathBuf);
|
||||
@@ -655,13 +653,9 @@ pub(crate) fn capture_command(
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// When both readers finish, their senders disconnect the channel and wake the child wait.
|
||||
let (closed_tx, closed) = mpsc::channel::<()>();
|
||||
let capture = |mut pipe: Box<dyn Read + Send>| {
|
||||
let overflow = overflow.clone();
|
||||
let closed_tx = closed_tx.clone();
|
||||
std::thread::spawn(move || {
|
||||
let _closed_tx = closed_tx;
|
||||
let mut bytes = Vec::new();
|
||||
(&mut pipe).take(max.saturating_add(1) as u64).read_to_end(&mut bytes)?;
|
||||
if bytes.len() > max {
|
||||
@@ -673,9 +667,6 @@ pub(crate) fn capture_command(
|
||||
};
|
||||
let stdout = capture(Box::new(child.stdout.take().expect("piped stdout")));
|
||||
let stderr = capture(Box::new(child.stderr.take().expect("piped stderr")));
|
||||
drop(closed_tx);
|
||||
let mut pipes_open = true;
|
||||
let mut backoff = Duration::from_micros(100);
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() || overflow.load(std::sync::atomic::Ordering::Acquire) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
@@ -693,15 +684,7 @@ pub(crate) fn capture_command(
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if pipes_open {
|
||||
// Cancellation and overflow are only noticed between wake-ups, so wait at most one
|
||||
// `POLL` for them; the pipes closing ends the wait at once.
|
||||
pipes_open = !matches!(closed.recv_timeout(POLL), Err(mpsc::RecvTimeoutError::Disconnected));
|
||||
} else {
|
||||
// Reap promptly after EOF, but back off if the child keeps running without its pipes.
|
||||
std::thread::sleep(backoff);
|
||||
backoff = (backoff * 2).min(POLL);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
if let Some(w) = writer {
|
||||
let _ = w.join();
|
||||
@@ -1262,90 +1245,3 @@ mod index_lock_tests {
|
||||
assert!(!retryable_index_conflict(&["reset"], &out));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod capture_tests {
|
||||
use super::*;
|
||||
|
||||
fn sh(script: &str) -> Command {
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", script]);
|
||||
cmd
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_capture_kills_a_long_running_child() {
|
||||
let cancel = CancellationToken::new();
|
||||
let trigger = cancel.clone();
|
||||
let canceller = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
trigger.cancel();
|
||||
});
|
||||
let start = Instant::now();
|
||||
let error = capture_command(sh("sleep 60"), None, &cancel, usize::MAX, "sh").err().unwrap();
|
||||
canceller.join().unwrap();
|
||||
assert_eq!(error.to_string(), IdeError::cancelled().to_string());
|
||||
assert!(start.elapsed() < Duration::from_secs(30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_before_the_start_spawns_nothing() {
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let marker = dir.path().join("ran");
|
||||
let mut cmd = sh(r#"touch "$1""#);
|
||||
cmd.arg("sh").arg(&marker);
|
||||
assert!(capture_command(cmd, None, &cancel, usize::MAX, "sh").is_err());
|
||||
assert!(!marker.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn megabytes_on_both_streams_are_captured_whole() {
|
||||
// Both pipes fill at once: a wait that stopped draining one while blocked on the other,
|
||||
// or on the exit, would deadlock here.
|
||||
const SIZE: usize = 6_000_000;
|
||||
let script = format!("(yes e | head -c {SIZE} >&2) & yes o | head -c {SIZE}; wait; exit 3");
|
||||
let out = capture_command(sh(&script), None, &CancellationToken::new(), usize::MAX, "sh").unwrap();
|
||||
assert_eq!((out.stdout.len(), out.stderr.len()), (SIZE, SIZE));
|
||||
assert!(out.stdout.chunks(2).all(|c| c.starts_with(b"o")));
|
||||
assert!(out.stderr.chunks(2).all(|c| c.starts_with(b"e")));
|
||||
assert_eq!(out.code, Some(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_status_and_both_streams_are_preserved() {
|
||||
let out = capture_command(sh("echo out; echo err >&2; exit 7"), None, &CancellationToken::new(), 1 << 20, "sh")
|
||||
.unwrap();
|
||||
assert_eq!((out.stdout, out.stderr, out.code), (b"out\n".to_vec(), b"err\n".to_vec(), Some(7)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_reaches_the_child() {
|
||||
let out = capture_command(sh("cat"), Some(b"piped"), &CancellationToken::new(), 1 << 20, "sh").unwrap();
|
||||
assert_eq!(out.stdout, b"piped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_over_the_limit_stops_the_child() {
|
||||
let start = Instant::now();
|
||||
let error = capture_command(sh("yes"), None, &CancellationToken::new(), 1000, "sh").err().unwrap();
|
||||
assert!(error.to_string().contains("exceeds 1000 bytes"), "{error}");
|
||||
assert!(start.elapsed() < Duration::from_secs(30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_that_closes_its_pipes_but_keeps_running_is_still_cancellable() {
|
||||
let cancel = CancellationToken::new();
|
||||
let trigger = cancel.clone();
|
||||
let canceller = std::thread::spawn(move || {
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
trigger.cancel();
|
||||
});
|
||||
let start = Instant::now();
|
||||
let error = capture_command(sh("exec >&- 2>&-; sleep 60"), None, &cancel, usize::MAX, "sh").err().unwrap();
|
||||
canceller.join().unwrap();
|
||||
assert_eq!(error.to_string(), IdeError::cancelled().to_string());
|
||||
assert!(start.elapsed() < Duration::from_secs(30));
|
||||
}
|
||||
}
|
||||
@@ -478,11 +478,12 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
|
||||
all.request = None;
|
||||
all.stop_at = None;
|
||||
let repo = r.gix()?;
|
||||
let (decorations, generation) = r.ref_decorations(&repo)?;
|
||||
let decorations = decorations(&repo)?;
|
||||
let shallow_vec =
|
||||
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
|
||||
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
|
||||
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
|
||||
let refs = r.log_refs()?;
|
||||
let key = format!("{}:{refs:?}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
|
||||
let cached = index.views.get(&key).cloned();
|
||||
let view = if let Some(cached) = cached {
|
||||
cached
|
||||
@@ -645,7 +646,7 @@ fn log_indexed(
|
||||
let repo = r.gix()?;
|
||||
let shallow: HashSet<ObjectId> =
|
||||
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect()).unwrap_or_default();
|
||||
let (decorations, _) = r.ref_decorations(&repo)?;
|
||||
let decorations = decorations(&repo)?;
|
||||
let range = q.range.as_deref().map(str::trim).filter(|s| !s.is_empty());
|
||||
let revs: Vec<&str> = q.branch.iter().chain(&q.branches).map(|b| b.trim()).filter(|b| !b.is_empty()).collect();
|
||||
let ranges: Vec<_> = q.ranges.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect();
|
||||
@@ -740,7 +741,7 @@ fn log_indexed_rows(
|
||||
if tips.is_empty() && range.is_none() && ranges.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let (decorations, _) = r.ref_decorations(&repo)?;
|
||||
let decorations = decorations(&repo)?;
|
||||
let paths: Vec<String> = q
|
||||
.path
|
||||
.iter()
|
||||
@@ -1405,19 +1406,8 @@ fn tips(repo: &gix::Repository, revs: &[&str]) -> IdeResult<Vec<ObjectId>> {
|
||||
Ok(tips)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local!(static DECORATION_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) });
|
||||
|
||||
/// How many times this thread listed all refs.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn decorations_scans() -> usize {
|
||||
DECORATION_SCANS.get()
|
||||
}
|
||||
|
||||
/// Commit id → decoration labels.
|
||||
pub(crate) fn decorations(repo: &gix::Repository) -> IdeResult<HashMap<ObjectId, Vec<String>>> {
|
||||
#[cfg(test)]
|
||||
DECORATION_SCANS.set(DECORATION_SCANS.get() + 1);
|
||||
let mut map: HashMap<ObjectId, Vec<String>> = HashMap::new();
|
||||
if let Ok(id) = repo.head_id() {
|
||||
map.entry(id.detach()).or_default().push("HEAD".to_string());
|
||||
|
||||
@@ -939,7 +939,6 @@ mod preserve;
|
||||
mod push_preview;
|
||||
mod push_report;
|
||||
mod rebase_editor;
|
||||
mod ref_decorations;
|
||||
mod worktree_config;
|
||||
pub use ops::UNSTAGED_CHANGES_PREVENT_REBASE;
|
||||
mod incoming;
|
||||
@@ -1079,7 +1078,6 @@ pub struct Repo {
|
||||
cli_status: std::sync::atomic::AtomicBool,
|
||||
automatic_shelf: std::sync::RwLock<Option<shelf::AutomaticShelf>>,
|
||||
log_index: std::sync::Mutex<log_index::LogIndex>,
|
||||
ref_decorations: std::sync::Mutex<ref_decorations::RefDecorations>,
|
||||
log_signatures: std::sync::Mutex<history::LogSignatureCache>,
|
||||
conflict_mutation: std::sync::Mutex<()>,
|
||||
amend_recovery: std::sync::Mutex<Option<commit_rewrite::PendingAmend>>,
|
||||
@@ -1139,9 +1137,11 @@ impl Repo {
|
||||
/// dirty-scope refresh after a watcher batch. An empty list is the full status.
|
||||
pub fn status_paths(&self, paths: &[PathBuf]) -> IdeResult<Vec<FileStatus>> {
|
||||
let _scope = self.execution_scope();
|
||||
// Restricted Mode reads this through git too: `cli::command` strips what the repository's
|
||||
// config could run, and the status call empties its clean/process filters. The full
|
||||
// gitoxide status it used to answer with walked the whole tree for one changed file.
|
||||
// Restricted Mode starts no program of the repository, and the scoped read is `git status`
|
||||
// with a pathspec: answer with the full gitoxide status instead.
|
||||
if !self.execution_allowed.load(std::sync::atomic::Ordering::Acquire) {
|
||||
return status::status(self);
|
||||
}
|
||||
if paths.is_empty() {
|
||||
return status::status_paths(self, &[]);
|
||||
}
|
||||
|
||||
@@ -1,264 +0,0 @@
|
||||
//! Ref decorations of the history, reused while git's ref storage has not changed.
|
||||
//!
|
||||
//! Listing and peeling every ref costs about 25 µs each, which a history page paid in full
|
||||
//! even for a one-row page. A page now stats `HEAD`, `packed-refs` and the directories under
|
||||
//! `refs/` instead: git replaces a loose ref by renaming a lock file over it, which changes
|
||||
//! the modification time of the ref's directory, and rewrites `packed-refs` the same way.
|
||||
|
||||
use crate::Repo;
|
||||
use crate::repo::absolute;
|
||||
use gix::ObjectId;
|
||||
use ide_core::IdeResult;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
/// A timestamp this close to the time it was read cannot tell two writes apart: a later write
|
||||
/// may leave the same value (coarse file systems, FAT's 2 s). Such a snapshot is never reused.
|
||||
const RACY_WINDOW: Duration = Duration::from_secs(2);
|
||||
|
||||
type Stat = Option<(SystemTime, u64)>;
|
||||
pub(crate) type Decorations = Arc<HashMap<ObjectId, Vec<String>>>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct RefDecorations {
|
||||
snapshot: Option<Snapshot>,
|
||||
/// Changes when the decorations do, so cached views of them can be keyed by it.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
struct Snapshot {
|
||||
map: Decorations,
|
||||
stamp: Vec<(PathBuf, Stat)>,
|
||||
reusable: bool,
|
||||
}
|
||||
|
||||
fn stat(path: &Path) -> Stat {
|
||||
let metadata = std::fs::metadata(path).ok()?;
|
||||
Some((metadata.modified().ok()?, metadata.len()))
|
||||
}
|
||||
|
||||
/// `HEAD`, `packed-refs` and every directory under `refs/`.
|
||||
fn stamp(git_dir: &Path, common_dir: &Path) -> Vec<(PathBuf, Stat)> {
|
||||
let mut paths = vec![git_dir.join("HEAD"), common_dir.join("packed-refs")];
|
||||
let mut pending = vec![common_dir.join("refs")];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if let Ok(entries) = std::fs::read_dir(&dir) {
|
||||
pending.extend(entries.flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir())).map(|e| e.path()));
|
||||
}
|
||||
paths.push(dir);
|
||||
}
|
||||
paths.into_iter().map(|path| (path.clone(), stat(&path))).collect()
|
||||
}
|
||||
|
||||
impl RefDecorations {
|
||||
fn get(&mut self, repo: &gix::Repository, git_dir: &Path, common_dir: &Path) -> IdeResult<(Decorations, u64)> {
|
||||
if let Some(snapshot) = &self.snapshot
|
||||
&& snapshot.reusable
|
||||
&& snapshot.stamp.iter().all(|(path, before)| stat(path) == *before)
|
||||
{
|
||||
return Ok((snapshot.map.clone(), self.generation));
|
||||
}
|
||||
// Stamped before the refs are read, so a write after the stamp shows in the next one.
|
||||
let taken = SystemTime::now();
|
||||
let stamp = stamp(git_dir, common_dir);
|
||||
let map = crate::history::decorations(repo)?;
|
||||
let reusable = stamp.iter().all(|(_, stat)| stat.is_none_or(|(modified, _)| modified + RACY_WINDOW <= taken));
|
||||
let unchanged = self.snapshot.as_ref().is_some_and(|old| *old.map == map);
|
||||
let map = match &self.snapshot {
|
||||
Some(old) if unchanged => old.map.clone(),
|
||||
_ => {
|
||||
self.generation += 1;
|
||||
Arc::new(map)
|
||||
}
|
||||
};
|
||||
self.snapshot = Some(Snapshot { map: map.clone(), stamp, reusable });
|
||||
Ok((map, self.generation))
|
||||
}
|
||||
}
|
||||
|
||||
impl Repo {
|
||||
/// Commit id → decoration labels, and a number that changes whenever they do.
|
||||
pub(crate) fn ref_decorations(&self, repo: &gix::Repository) -> IdeResult<(Decorations, u64)> {
|
||||
let common_dir = absolute(repo.common_dir())?;
|
||||
self.ref_decorations.lock().unwrap_or_else(|p| p.into_inner()).get(repo, &self.git_dir, &common_dir)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::history::decorations_scans;
|
||||
use crate::{LogOrder, LogQuery, Repo};
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let out = std::process::Command::new("git")
|
||||
.current_dir(dir)
|
||||
.args(["-c", "init.defaultBranch=main", "-c", "user.name=T", "-c", "[email protected]"])
|
||||
.args(["-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
fn commit(dir: &Path, message: &str) -> String {
|
||||
std::fs::write(dir.join("f"), message).unwrap();
|
||||
git(dir, &["add", "-A"]);
|
||||
git(dir, &["commit", "-qm", message]);
|
||||
git(dir, &["rev-parse", "HEAD"])
|
||||
}
|
||||
|
||||
/// Sets the modification time of `HEAD`, `packed-refs` and every directory under `refs/`.
|
||||
fn set_ref_times(repo: &Repo, time: SystemTime) {
|
||||
let git = repo.git_dir.clone();
|
||||
let mut paths = vec![git.join("HEAD"), git.join("packed-refs")];
|
||||
let mut pending = vec![git.join("refs")];
|
||||
while let Some(dir) = pending.pop() {
|
||||
pending.extend(std::fs::read_dir(&dir).unwrap().flatten().filter(|e| e.path().is_dir()).map(|e| e.path()));
|
||||
paths.push(dir);
|
||||
}
|
||||
let mut options = std::fs::File::options();
|
||||
options.read(true);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
const FILE_WRITE_ATTRIBUTES: u32 = 0x100;
|
||||
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
|
||||
options.access_mode(FILE_WRITE_ATTRIBUTES).custom_flags(FILE_FLAG_BACKUP_SEMANTICS);
|
||||
}
|
||||
for path in paths.into_iter().filter(|p| p.exists()) {
|
||||
options.open(path).unwrap().set_modified(time).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// As if the refs were written long ago, then reads the history once so the decorations
|
||||
/// are cached; a second read must not list the refs again.
|
||||
fn settle(repo: &Repo) {
|
||||
set_ref_times(repo, SystemTime::now() - Duration::from_secs(3600));
|
||||
page(repo, 0, 1);
|
||||
let scans = decorations_scans();
|
||||
page(repo, 0, 1);
|
||||
assert_eq!(decorations_scans(), scans, "the decorations were not reusable");
|
||||
}
|
||||
|
||||
fn page(repo: &Repo, skip: u32, limit: u32) -> Vec<crate::Commit> {
|
||||
repo.log(&LogQuery { skip, limit, summary_only: true, order: LogOrder::Topo, ..Default::default() }).unwrap()
|
||||
}
|
||||
|
||||
fn labels(repo: &Repo, id: &str) -> Vec<String> {
|
||||
let all = page(repo, 0, 0);
|
||||
all.into_iter().find(|c| c.id == id).unwrap().refs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_pages_do_not_list_the_refs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
for i in 0..30 {
|
||||
commit(dir, &format!("c{i}"));
|
||||
}
|
||||
for i in 0..20 {
|
||||
git(dir, &["branch", &format!("b{i}")]);
|
||||
}
|
||||
let repo = Repo::discover(dir).unwrap().unwrap();
|
||||
settle(&repo);
|
||||
let after_first = decorations_scans();
|
||||
for skip in [10, 20, 0, 5] {
|
||||
assert_eq!(page(&repo, skip, 1).len(), 1);
|
||||
assert_eq!(page(&repo, skip, 10).len(), 10);
|
||||
}
|
||||
assert_eq!(decorations_scans(), after_first, "a warm page listed the refs again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_ref_timestamps_are_not_trusted() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
let first = commit(dir, "first");
|
||||
let repo = Repo::discover(dir).unwrap().unwrap();
|
||||
set_ref_times(&repo, SystemTime::now());
|
||||
page(&repo, 0, 10);
|
||||
let scans = decorations_scans();
|
||||
// A write within the timestamp's resolution would leave it unchanged: rescan every time.
|
||||
page(&repo, 0, 10);
|
||||
assert!(decorations_scans() > scans);
|
||||
assert!(labels(&repo, &first).contains(&"main".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decorations_follow_every_kind_of_ref_change() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
let first = commit(dir, "first");
|
||||
let repo = Repo::discover(dir).unwrap().unwrap();
|
||||
settle(&repo);
|
||||
let first_labels = labels(&repo, &first);
|
||||
assert!(first_labels.contains(&"HEAD".to_string()) && first_labels.contains(&"main".to_string()));
|
||||
|
||||
// A new commit moves HEAD and the branch.
|
||||
settle(&repo);
|
||||
let second = commit(dir, "second");
|
||||
assert_eq!(labels(&repo, &first), Vec::<String>::new());
|
||||
assert!(labels(&repo, &second).contains(&"main".to_string()));
|
||||
|
||||
// A new tag, then an annotated one, in a directory that did not exist before.
|
||||
settle(&repo);
|
||||
git(dir, &["tag", "v1", &first]);
|
||||
assert_eq!(labels(&repo, &first), ["tag: v1"]);
|
||||
settle(&repo);
|
||||
git(dir, &["tag", "-a", "-m", "m", "rel/v2", &first]);
|
||||
assert_eq!(labels(&repo, &first), ["tag: rel/v2", "tag: v1"]);
|
||||
|
||||
// A new branch, one moved to another commit, and one deleted.
|
||||
settle(&repo);
|
||||
git(dir, &["branch", "side", &first]);
|
||||
assert!(labels(&repo, &first).contains(&"side".to_string()));
|
||||
settle(&repo);
|
||||
git(dir, &["branch", "-f", "side", &second]);
|
||||
assert!(!labels(&repo, &first).contains(&"side".to_string()));
|
||||
assert!(labels(&repo, &second).contains(&"side".to_string()));
|
||||
settle(&repo);
|
||||
git(dir, &["branch", "-D", "side"]);
|
||||
assert!(!labels(&repo, &second).contains(&"side".to_string()));
|
||||
|
||||
// Refs in packed-refs: packing changes nothing visible, deleting one rewrites the file.
|
||||
git(dir, &["branch", "packed", &first]);
|
||||
git(dir, &["pack-refs", "--all"]);
|
||||
settle(&repo);
|
||||
assert!(labels(&repo, &first).contains(&"packed".to_string()));
|
||||
git(dir, &["branch", "-D", "packed"]);
|
||||
assert!(!labels(&repo, &first).contains(&"packed".to_string()));
|
||||
|
||||
// A detached HEAD and a tag deleted again.
|
||||
settle(&repo);
|
||||
git(dir, &["checkout", "-q", "--detach", &first]);
|
||||
assert!(labels(&repo, &first).contains(&"HEAD".to_string()));
|
||||
assert!(!labels(&repo, &second).contains(&"HEAD".to_string()));
|
||||
settle(&repo);
|
||||
git(dir, &["tag", "-d", "v1"]);
|
||||
assert_eq!(labels(&repo, &first), ["HEAD", "tag: rel/v2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ref_change_between_pages_replaces_the_cached_view() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
git(dir, &["init", "-q"]);
|
||||
let first = commit(dir, "first");
|
||||
commit(dir, "second");
|
||||
let repo = Repo::discover(dir).unwrap().unwrap();
|
||||
settle(&repo);
|
||||
page(&repo, 0, 10);
|
||||
settle(&repo);
|
||||
git(dir, &["tag", "v1", &first]);
|
||||
let rows = page(&repo, 0, 10);
|
||||
assert_eq!(rows.iter().find(|c| c.id == first).unwrap().refs, ["tag: v1"]);
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,6 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
cli_status: Default::default(),
|
||||
automatic_shelf: Default::default(),
|
||||
log_index: Default::default(),
|
||||
ref_decorations: Default::default(),
|
||||
log_signatures: Default::default(),
|
||||
conflict_mutation: Default::default(),
|
||||
amend_recovery: Default::default(),
|
||||
|
||||
@@ -583,60 +583,4 @@ mod tests {
|
||||
cli_status(&repo, &IgnoredNames::default()).unwrap();
|
||||
assert!(marker.exists(), "control: git status did not run the filter");
|
||||
}
|
||||
|
||||
fn committed_repo(dir: &Path) {
|
||||
git(dir, &["init", "-q"]);
|
||||
git(dir, &["config", "user.name", "Test User"]);
|
||||
git(dir, &["config", "user.email", "[email protected]"]);
|
||||
git(dir, &["config", "commit.gpgsign", "false"]);
|
||||
std::fs::write(dir.join("a.txt"), "same\n").unwrap();
|
||||
std::fs::write(dir.join("b.txt"), "same\n").unwrap();
|
||||
commit_all(dir, "base");
|
||||
}
|
||||
|
||||
/// The dirty-scope refresh in Restricted Mode reads the named paths only: it used to answer
|
||||
/// with the full status, which walks the whole tree for one saved file.
|
||||
#[test]
|
||||
fn restricted_status_paths_reads_only_the_named_paths() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
committed_repo(dir);
|
||||
std::fs::write(dir.join("a.txt"), "changed\n").unwrap();
|
||||
std::fs::write(dir.join("b.txt"), "changed\n").unwrap();
|
||||
|
||||
let repo = Repo::discover(dir).unwrap().expect("repository found");
|
||||
let one = repo.status_paths(&[repo.root().join("a.txt")]).unwrap();
|
||||
assert_eq!(one.iter().map(|s| s.rel_path.as_str()).collect::<Vec<_>>(), ["a.txt"]);
|
||||
assert_eq!(repo.status().unwrap().len(), 2, "the full status still lists both");
|
||||
}
|
||||
|
||||
/// The scoped read is `git status`, which applies the repository's clean filters to compare
|
||||
/// content: Restricted Mode must empty them there as it does for the full read.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn restricted_status_paths_does_not_run_repository_filters() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
committed_repo(dir);
|
||||
let marker = dir.join(".git/executed");
|
||||
let script = dir.join(".git/marker.sh");
|
||||
std::fs::write(&script, format!("#!/bin/sh\ntouch '{}'\ncat\n", marker.display())).unwrap();
|
||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
git(dir, &["config", "filter.marker.clean", script.to_str().unwrap()]);
|
||||
std::fs::write(dir.join(".gitattributes"), "*.txt filter=marker\n").unwrap();
|
||||
// Same size, new mtime: git has to read (and clean) the file to tell whether it changed.
|
||||
std::thread::sleep(std::time::Duration::from_millis(1100));
|
||||
std::fs::write(dir.join("a.txt"), "diff\n").unwrap();
|
||||
|
||||
let repo = Repo::discover(dir).unwrap().expect("repository found");
|
||||
let paths = [repo.root().join("a.txt")];
|
||||
let listed = repo.status_paths(&paths).unwrap();
|
||||
assert_eq!(listed.len(), 1, "the change is still listed");
|
||||
assert!(!marker.exists(), "Restricted Mode ran the repository's clean filter");
|
||||
// Control: a trusted run does use the filter, so the fixture is live.
|
||||
repo.set_execution_allowed(true);
|
||||
repo.status_paths(&paths).unwrap();
|
||||
assert!(marker.exists(), "control: git status did not run the filter");
|
||||
}
|
||||
}
|
||||
@@ -591,17 +591,8 @@ fn select_into(
|
||||
encoding: &dyn Fn(&Path) -> IdeResult<TextEncoding>,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let index = r.git_dir.join("index");
|
||||
match std::fs::File::open(index) {
|
||||
Ok(mut source) => {
|
||||
let metadata = source.metadata()?;
|
||||
let mut copy = std::fs::File::create(&tmp.0)?;
|
||||
copy.set_permissions(metadata.permissions())?;
|
||||
std::io::copy(&mut source, &mut copy)?;
|
||||
// Git uses the index timestamp to decide which same-size files need a content check.
|
||||
copy.set_modified(metadata.modified()?)?;
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
if index.exists() {
|
||||
std::fs::copy(&index, &tmp.0)?;
|
||||
}
|
||||
let env = [("GIT_INDEX_FILE", tmp.0.as_os_str())];
|
||||
fill_commit_index(r, &env, options, encoding)
|
||||
|
||||
@@ -2017,17 +2017,11 @@ fn partial_commit_of_chosen_hunks_leaves_worktree_and_index_alone() {
|
||||
#[test]
|
||||
fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index() {
|
||||
let fx = Fixture::new();
|
||||
fx.git(&["config", "core.checkStat", "minimal"]);
|
||||
fx.git(&["config", "core.trustctime", "false"]);
|
||||
let same_tick = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
|
||||
let set_mtime =
|
||||
|path| std::fs::File::options().write(true).open(fx.path(path)).unwrap().set_modified(same_tick).unwrap();
|
||||
let base = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\n";
|
||||
fx.write("f.txt", base);
|
||||
fx.write("staged.txt", "s\n");
|
||||
fx.write("old.txt", "moved\nfile\nwith\nlines\n");
|
||||
fx.write("bin.dat", "\0\x01");
|
||||
set_mtime("bin.dat");
|
||||
fx.commit_all("base");
|
||||
let repo = fx.repo();
|
||||
let utf8 = |_: &Path| -> ide_core::IdeResult<&encoding_rs::Encoding> { Ok(encoding_rs::UTF_8) };
|
||||
@@ -2038,9 +2032,6 @@ fn pending_changes_show_what_the_commit_would_hold_without_touching_the_index()
|
||||
fx.git(&["add", "staged.txt"]);
|
||||
fx.git(&["mv", "old.txt", "new.txt"]);
|
||||
fx.write("bin.dat", "\0\x02");
|
||||
// Git must recheck a same-size edit made on the same clock tick as the index.
|
||||
set_mtime("bin.dat");
|
||||
set_mtime(".git/index");
|
||||
fx.write("added.txt", "new\n");
|
||||
let index_before = std::fs::read(fx.dir.join(".git/index")).unwrap();
|
||||
|
||||
|
||||
@@ -1,366 +0,0 @@
|
||||
//! [`decode_text`](crate::decode_text) for files too large to hold: the same
|
||||
//! decisions, taken while reading a chunk at a time.
|
||||
|
||||
use crate::encoding::{SNIFF_LEN, sniff_utf16};
|
||||
use encoding_rs::{Decoder, Encoding, UTF_8, UTF_16BE, UTF_16LE};
|
||||
use std::io::{self, Read};
|
||||
|
||||
/// Raw bytes read per step; a step holds this plus its UTF-8 expansion (at most 3x).
|
||||
const CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// The text of a file as UTF-8 bytes, decoded as it is read.
|
||||
pub struct DecodedReader<R> {
|
||||
reader: R,
|
||||
decoder: Decoder,
|
||||
raw: Vec<u8>,
|
||||
/// Decoded bytes of the last step; `out[pos..len]` is unread.
|
||||
out: Vec<u8>,
|
||||
pos: usize,
|
||||
len: usize,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
/// Decodes the file `open` reads like [`decode_text`](crate::decode_text) does (BOM, UTF-8 and
|
||||
/// UTF-16 as detected, other text as `fallback` or else the detected encoding) without holding
|
||||
/// it: `None` for binary content, else a reader of the text as UTF-8.
|
||||
///
|
||||
/// Deciding the encoding of text that is neither BOM-marked nor UTF-8 needs a pass over the whole
|
||||
/// file before the decoding pass, so `open` gives a fresh reader of the file up to twice.
|
||||
pub fn decode_stream<R: Read>(
|
||||
open: impl FnMut() -> io::Result<R>,
|
||||
fallback: Option<&str>,
|
||||
) -> io::Result<Option<DecodedReader<R>>> {
|
||||
decode_stream_in(open, fallback, CHUNK)
|
||||
}
|
||||
|
||||
fn decode_stream_in<R: Read>(
|
||||
mut open: impl FnMut() -> io::Result<R>,
|
||||
fallback: Option<&str>,
|
||||
chunk: usize,
|
||||
) -> io::Result<Option<DecodedReader<R>>> {
|
||||
let Some((detected, bom_len, has_bom)) = detect(&mut open, chunk)? else { return Ok(None) };
|
||||
let fallback = fallback.and_then(|label| Encoding::for_label(label.trim().as_bytes()));
|
||||
let encoding = match fallback {
|
||||
Some(enc)
|
||||
if !has_bom && enc != detected && detected != UTF_8 && detected != UTF_16LE && detected != UTF_16BE =>
|
||||
{
|
||||
enc
|
||||
}
|
||||
_ => detected,
|
||||
};
|
||||
let mut reader = open()?;
|
||||
io::copy(&mut (&mut reader).take(bom_len as u64), &mut io::sink())?;
|
||||
let decoder = encoding.new_decoder_without_bom_handling();
|
||||
let out = vec![0; decoder.max_utf8_buffer_length(chunk).unwrap_or(chunk * 3)];
|
||||
Ok(Some(DecodedReader { reader, decoder, raw: vec![0; chunk], out, pos: 0, len: 0, done: false }))
|
||||
}
|
||||
|
||||
/// The encoding [`decode`](crate::encoding::decode) finds for the file, its BOM length and
|
||||
/// whether it has a BOM; `None` for binary content.
|
||||
fn detect<R: Read>(
|
||||
open: &mut impl FnMut() -> io::Result<R>,
|
||||
chunk: usize,
|
||||
) -> io::Result<Option<(&'static Encoding, usize, bool)>> {
|
||||
let mut reader = open()?;
|
||||
let mut head = vec![0; SNIFF_LEN];
|
||||
let n = read_full(&mut reader, &mut head)?;
|
||||
head.truncate(n);
|
||||
if let Some((enc, bom_len)) = Encoding::for_bom(&head) {
|
||||
return Ok(Some((enc, bom_len, true)));
|
||||
}
|
||||
if head.contains(&0) {
|
||||
return Ok(sniff_utf16(&head).map(|enc| (enc, 0, false)));
|
||||
}
|
||||
let mut detector = chardetng::EncodingDetector::new();
|
||||
let mut utf8 = Utf8Check::default();
|
||||
detector.feed(&head, false);
|
||||
utf8.feed(&head);
|
||||
if n == SNIFF_LEN {
|
||||
let mut buf = vec![0; chunk];
|
||||
loop {
|
||||
let n = read_retry(&mut reader, &mut buf)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
detector.feed(&buf[..n], false);
|
||||
utf8.feed(&buf[..n]);
|
||||
}
|
||||
}
|
||||
detector.feed(&[], true);
|
||||
let encoding = if utf8.is_valid() { UTF_8 } else { detector.guess(None, true) };
|
||||
Ok(Some((encoding, 0, false)))
|
||||
}
|
||||
|
||||
/// Reads until `buf` is full or the reader ends.
|
||||
fn read_full(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let mut filled = 0;
|
||||
while filled < buf.len() {
|
||||
match read_retry(reader, &mut buf[filled..])? {
|
||||
0 => break,
|
||||
n => filled += n,
|
||||
}
|
||||
}
|
||||
Ok(filled)
|
||||
}
|
||||
|
||||
fn read_retry(reader: &mut impl Read, buf: &mut [u8]) -> io::Result<usize> {
|
||||
loop {
|
||||
match reader.read(buf) {
|
||||
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that bytes fed in pieces form valid UTF-8, as `std::str::from_utf8` does for the whole.
|
||||
#[derive(Default)]
|
||||
struct Utf8Check {
|
||||
/// The start of a character cut by the end of the previous piece.
|
||||
tail: Vec<u8>,
|
||||
invalid: bool,
|
||||
}
|
||||
|
||||
impl Utf8Check {
|
||||
fn feed(&mut self, mut bytes: &[u8]) {
|
||||
if self.invalid {
|
||||
return;
|
||||
}
|
||||
while !self.tail.is_empty() && !bytes.is_empty() {
|
||||
self.tail.push(bytes[0]);
|
||||
bytes = &bytes[1..];
|
||||
match std::str::from_utf8(&self.tail) {
|
||||
Ok(_) => self.tail.clear(),
|
||||
Err(e) if e.error_len().is_none() => {}
|
||||
Err(_) => {
|
||||
self.invalid = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !self.tail.is_empty() {
|
||||
return;
|
||||
}
|
||||
match std::str::from_utf8(bytes) {
|
||||
Ok(_) => {}
|
||||
Err(e) if e.error_len().is_none() => self.tail.extend_from_slice(&bytes[e.valid_up_to()..]),
|
||||
Err(_) => self.invalid = true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether everything fed so far was UTF-8 (a truncated final character is not).
|
||||
fn is_valid(&self) -> bool {
|
||||
!self.invalid && self.tail.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Read> Read for DecodedReader<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
while self.pos == self.len {
|
||||
if self.done {
|
||||
return Ok(0);
|
||||
}
|
||||
let n = read_retry(&mut self.reader, &mut self.raw)?;
|
||||
let last = n == 0;
|
||||
let needed = self.decoder.max_utf8_buffer_length(n).unwrap_or(n * 3 + 16);
|
||||
if self.out.len() < needed {
|
||||
self.out.resize(needed, 0);
|
||||
}
|
||||
// Malformed input becomes U+FFFD, as in `decode_without_bom_handling`.
|
||||
let (_, _, written, _) = self.decoder.decode_to_utf8(&self.raw[..n], &mut self.out, last);
|
||||
self.pos = 0;
|
||||
self.len = written;
|
||||
self.done = last;
|
||||
}
|
||||
let n = buf.len().min(self.len - self.pos);
|
||||
buf[..n].copy_from_slice(&self.out[self.pos..self.pos + n]);
|
||||
self.pos += n;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::decode_text;
|
||||
|
||||
/// Hands out at most `step` bytes per read, so chunk edges fall everywhere.
|
||||
struct Trickle<'a> {
|
||||
bytes: &'a [u8],
|
||||
step: usize,
|
||||
}
|
||||
|
||||
impl Read for Trickle<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let n = buf.len().min(self.step).min(self.bytes.len());
|
||||
buf[..n].copy_from_slice(&self.bytes[..n]);
|
||||
self.bytes = &self.bytes[n..];
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
fn streamed(bytes: &[u8], fallback: Option<&str>, chunk: usize, step: usize) -> Option<Vec<u8>> {
|
||||
let reader = decode_stream_in(|| Ok(Trickle { bytes, step }), fallback, chunk).unwrap()?;
|
||||
let mut out = Vec::new();
|
||||
let mut reader = reader;
|
||||
// Small reads too: the consumer's buffer is not the chunk either.
|
||||
let mut buf = [0; 7];
|
||||
loop {
|
||||
let n = reader.read(&mut buf).unwrap();
|
||||
if n == 0 {
|
||||
return Some(out);
|
||||
}
|
||||
out.extend_from_slice(&buf[..n]);
|
||||
}
|
||||
}
|
||||
|
||||
fn utf16(text: &str, bom: bool, big: bool) -> Vec<u8> {
|
||||
let mut bytes =
|
||||
if bom { vec![if big { 0xFE } else { 0xFF }, if big { 0xFF } else { 0xFE }] } else { Vec::new() };
|
||||
for unit in text.encode_utf16() {
|
||||
bytes.extend(if big { unit.to_be_bytes() } else { unit.to_le_bytes() });
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Text with multi-byte characters and surrogate pairs at every alignment.
|
||||
fn sample(len: usize) -> String {
|
||||
let mut text = String::new();
|
||||
let pieces = [
|
||||
"ascii line\n",
|
||||
"caf\u{e9} cr\u{e8}me\n",
|
||||
"\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\n",
|
||||
"\u{1f600}\u{1f4a9} x\n",
|
||||
"\u{20ac}5\r\n",
|
||||
];
|
||||
let mut i = 0;
|
||||
while text.len() < len {
|
||||
text.push_str(pieces[i * 7 % pieces.len()]);
|
||||
i += 1;
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn inputs() -> Vec<(String, Vec<u8>)> {
|
||||
let text = sample(1500);
|
||||
let mut inputs = vec![
|
||||
("utf8".to_string(), text.clone().into_bytes()),
|
||||
("utf8 bom".to_string(), [&[0xEF, 0xBB, 0xBF][..], text.as_bytes()].concat()),
|
||||
("utf16le bom".to_string(), utf16(&text, true, false)),
|
||||
("utf16be bom".to_string(), utf16(&text, true, true)),
|
||||
("utf16le".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, false)),
|
||||
("utf16be".to_string(), utf16(&sample(1500).replace(|c: char| !c.is_ascii(), "e"), false, true)),
|
||||
(
|
||||
"gbk".to_string(),
|
||||
encoding_rs::GBK
|
||||
.encode(&sample(1500).replace(['\u{1f600}', '\u{1f4a9}', '\u{20ac}'], ""))
|
||||
.0
|
||||
.into_owned(),
|
||||
),
|
||||
(
|
||||
"latin1".to_string(),
|
||||
encoding_rs::WINDOWS_1252
|
||||
.encode(&sample(1500).replace(|c: char| c as u32 > 0xff && c != '\u{20ac}', ""))
|
||||
.0
|
||||
.into_owned(),
|
||||
),
|
||||
("empty".to_string(), Vec::new()),
|
||||
("binary".to_string(), b"\x7FELF\x02\x01\x01\x00\x00\x00 and text".repeat(100)),
|
||||
("late nul".to_string(), [&b"abc caf\xe9 ".repeat(1200)[..], b"\0 tail"].concat()),
|
||||
("truncated utf8".to_string(), text.as_bytes()[..text.len() - 1].to_vec()),
|
||||
("truncated utf16".to_string(), utf16(&text, true, false)[..utf16(&text, true, false).len() - 1].to_vec()),
|
||||
(
|
||||
"lone surrogate".to_string(),
|
||||
[&[0xFF, 0xFE][..], &[0x3D, 0xD8, b'a', 0][..], &utf16(&text, false, false)[..]].concat(),
|
||||
),
|
||||
("invalid in the middle".to_string(), [text.as_bytes(), b"\xff\xfe\xc3", text.as_bytes()].concat()),
|
||||
(
|
||||
"shift jis".to_string(),
|
||||
encoding_rs::SHIFT_JIS
|
||||
.encode(
|
||||
"\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}\u{4e16}\u{754c}\u{ff76}\u{ff85}\n"
|
||||
.repeat(200)
|
||||
.as_str(),
|
||||
)
|
||||
.0
|
||||
.into_owned(),
|
||||
),
|
||||
];
|
||||
// The evidence for the encoding comes long after the sniffed head.
|
||||
let chinese = "\u{4e2d}\u{6587}\u{6d4b}\u{8bd5}\u{4e00}\u{6bb5}\u{6587}\u{672c}\n".repeat(300);
|
||||
let gbk = encoding_rs::GBK.encode(&chinese).0.into_owned();
|
||||
let head = "plain ascii line\n".repeat(1500);
|
||||
inputs.push(("gbk after a long ascii head".to_string(), [head.as_bytes(), &gbk].concat()));
|
||||
// Characters at every alignment against the sniffing head and the chunks.
|
||||
for pad in 0..5 {
|
||||
let mut bytes = "x".repeat(SNIFF_LEN - 3 + pad).into_bytes();
|
||||
bytes.extend("\u{4e2d}\u{1f600}\u{e9}".as_bytes());
|
||||
inputs.push((format!("utf8 at the head edge {pad}"), bytes));
|
||||
let mut bytes = "y".repeat(SNIFF_LEN - 2 + pad).into_bytes();
|
||||
bytes.extend([0xE9, b'z', 0xFF, b'e']);
|
||||
inputs.push((format!("latin1 at the head edge {pad}"), bytes));
|
||||
}
|
||||
inputs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_text_equals_the_whole_file_decode() {
|
||||
for (name, bytes) in inputs() {
|
||||
for fallback in [None, Some("gbk"), Some("windows-1252"), Some("utf-16le"), Some("nonsense")] {
|
||||
let expected = decode_text(&bytes, fallback).map(String::into_bytes);
|
||||
for chunk in [1, 2, 3, 4, 5, 16, 255, 4096, CHUNK] {
|
||||
for step in [1, 3, 8192, usize::MAX] {
|
||||
assert_eq!(
|
||||
streamed(&bytes, fallback, chunk, step),
|
||||
expected,
|
||||
"{name}, fallback {fallback:?}, chunk {chunk}, step {step}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_check_matches_from_utf8_for_any_split() {
|
||||
let samples: [&[u8]; 6] = [
|
||||
"a\u{e9}\u{4e2d}\u{1f600}z".as_bytes(),
|
||||
b"ab\xe4\xb8",
|
||||
b"\xe4\xb8a",
|
||||
b"\xf0\x9f\x98",
|
||||
b"ok\xc3(",
|
||||
b"\xed\xa0\x80",
|
||||
];
|
||||
for bytes in samples {
|
||||
for first in 0..=bytes.len() {
|
||||
for second in first..=bytes.len() {
|
||||
let mut check = Utf8Check::default();
|
||||
check.feed(&bytes[..first]);
|
||||
check.feed(&bytes[first..second]);
|
||||
check.feed(&bytes[second..]);
|
||||
assert_eq!(check.is_valid(), std::str::from_utf8(bytes).is_ok(), "{bytes:?} {first} {second}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_at_most_a_bounded_number_of_bytes_per_step() {
|
||||
// A reader that fails if asked for more than one chunk shows nothing is read whole.
|
||||
struct Capped<'a>(&'a [u8]);
|
||||
impl Read for Capped<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
assert!(buf.len() <= SNIFF_LEN.max(1024), "asked for {} bytes", buf.len());
|
||||
let n = buf.len().min(self.0.len());
|
||||
buf[..n].copy_from_slice(&self.0[..n]);
|
||||
self.0 = &self.0[n..];
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
let bytes = encoding_rs::WINDOWS_1252.encode(&"caf\u{e9}\n".repeat(50_000)).0.into_owned();
|
||||
let mut reader = decode_stream_in(|| Ok(Capped(&bytes)), None, 1024).unwrap().unwrap();
|
||||
let mut text = String::new();
|
||||
reader.read_to_string(&mut text).unwrap();
|
||||
assert_eq!(text, "caf\u{e9}\n".repeat(50_000));
|
||||
assert!(reader.out.len() <= 4 * 1024 + 16 && reader.raw.len() == 1024);
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,7 @@ pub fn save_properties_text(path: &Path, text: &str) -> IdeResult<f64> {
|
||||
}
|
||||
|
||||
/// Detects BOM-less UTF-16 from the distribution of NUL bytes in mostly-ASCII text.
|
||||
pub(crate) fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
|
||||
fn sniff_utf16(sample: &[u8]) -> Option<&'static Encoding> {
|
||||
if sample.len() < 4 {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
mod archive;
|
||||
mod bytes;
|
||||
mod compare;
|
||||
mod decode_stream;
|
||||
mod encoding;
|
||||
mod ops;
|
||||
mod private;
|
||||
@@ -31,7 +30,6 @@ pub use compare::{
|
||||
DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction,
|
||||
DirectorySyncFailure, DirectorySyncOperation, DirectorySyncProgress, compare_directories, copy_merge,
|
||||
};
|
||||
pub use decode_stream::{DecodedReader, decode_stream};
|
||||
use encoding::SNIFF_LEN;
|
||||
pub use encoding::{
|
||||
LARGE_FILE_THRESHOLD, MAX_OPEN_SIZE, READ_ONLY_THRESHOLD, decode_properties_escapes, encode,
|
||||
|
||||
@@ -1753,8 +1753,7 @@ mod tests {
|
||||
std::fs::write(root.join("src/a/after.rs"), "x").unwrap();
|
||||
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("src/a/after.rs"))));
|
||||
let paths = all_paths(&batches.lock());
|
||||
let excluded = root.join("node_modules");
|
||||
assert!(!paths.iter().any(|p| p != &excluded && p.starts_with(&excluded)), "{paths:?}");
|
||||
assert!(!paths.iter().any(|p| p.starts_with(root.join("node_modules"))), "{paths:?}");
|
||||
assert!(!paths.contains(&root.join("lib/out/o.txt")));
|
||||
|
||||
// Un-ignoring lib/out keeps its existing filename watch.
|
||||
|
||||
@@ -464,12 +464,15 @@ impl LocalHistory {
|
||||
/// The watcher saw `paths` disappear: files with history that are gone get a
|
||||
/// "Deleted" entry pointing at their last content (unless one was recorded already).
|
||||
pub fn note_removed(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
if paths.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut state = self.state.lock();
|
||||
let gone: Vec<(PathBuf, String, u64)> = {
|
||||
latest_snapshots_under(&state.entries, paths)
|
||||
let mut latest: HashMap<&Path, &HistoryEntry> = HashMap::new();
|
||||
for e in state.entries.iter().filter(|e| e.kind == HistoryKind::Snapshot) {
|
||||
if paths.iter().any(|p| e.path.starts_with(p)) {
|
||||
latest.insert(&e.path, e);
|
||||
}
|
||||
}
|
||||
latest
|
||||
.into_values()
|
||||
.filter(|e| e.label != DELETED && !e.path.exists())
|
||||
.map(|e| (e.path.to_path_buf(), e.id.clone(), e.size))
|
||||
@@ -697,32 +700,9 @@ fn collect_files(dir: &Path, limit: usize, out: &mut Vec<PathBuf>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest snapshot entry of every file at or below one of `roots`.
|
||||
/// Each entry is checked by looking up its own path and its ancestors in a set of the roots,
|
||||
/// so the cost does not grow with the number of roots (a batch can name tens of thousands).
|
||||
fn latest_snapshots_under<'a>(entries: &'a [HistoryEntry], roots: &[PathBuf]) -> HashMap<&'a Path, &'a HistoryEntry> {
|
||||
let roots: HashSet<&Path> = roots.iter().map(PathBuf::as_path).collect();
|
||||
let mut latest = HashMap::new();
|
||||
for e in entries.iter().filter(|e| e.kind == HistoryKind::Snapshot) {
|
||||
if e.path.ancestors().any(|dir| {
|
||||
#[cfg(test)]
|
||||
tests::ROOT_LOOKUPS.with(|n| n.set(n.get() + 1));
|
||||
roots.contains(dir)
|
||||
}) {
|
||||
latest.insert(&*e.path, e);
|
||||
}
|
||||
}
|
||||
latest
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
pub(super) static ROOT_LOOKUPS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_list_dedupe_prune() {
|
||||
@@ -866,79 +846,6 @@ mod tests {
|
||||
assert_eq!(h.stored_bytes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_removed_work_does_not_grow_with_the_number_of_removed_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let kept: Vec<PathBuf> =
|
||||
(0..300).map(|i| root.join("keep").join(format!("g{}", i / 50)).join(format!("f{i}.rs"))).collect();
|
||||
{
|
||||
let mut state = h.state.lock();
|
||||
for p in &kept {
|
||||
state.entries.push(HistoryEntry::snapshot(p, "x", "External change", now_ms()));
|
||||
}
|
||||
}
|
||||
let removed: Vec<PathBuf> =
|
||||
(0..5_000).map(|i| root.join("gone").join(format!("g{}", i / 50)).join(format!("f{i}.rs"))).collect();
|
||||
|
||||
ROOT_LOOKUPS.with(|n| n.set(0));
|
||||
h.note_removed(&removed).unwrap();
|
||||
|
||||
// At most one lookup per path component of each entry, however many paths were removed.
|
||||
let bound: usize = kept.iter().map(|p| p.components().count()).sum();
|
||||
let lookups = ROOT_LOOKUPS.with(Cell::get);
|
||||
assert!(lookups > 0 && lookups <= bound, "{lookups} root lookups for {} entries (bound {bound})", kept.len());
|
||||
assert_eq!(h.state.lock().entries.len(), kept.len(), "nothing was deleted, so nothing is appended");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_removed_marks_only_files_gone_under_a_removed_path() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
fs::create_dir_all(root.join("dir")).unwrap();
|
||||
fs::create_dir_all(root.join("dir2")).unwrap();
|
||||
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let (a, b) = (root.join("dir/a.txt"), root.join("dir/b.txt"));
|
||||
let sibling = root.join("dir2/c.txt");
|
||||
let (solo, multi, present, already) =
|
||||
(root.join("solo.txt"), root.join("multi.txt"), root.join("present.txt"), root.join("already.txt"));
|
||||
for (path, text) in [(&a, "a"), (&b, "b"), (&sibling, "c"), (&solo, "s"), (&present, "p"), (&already, "d")] {
|
||||
h.record(path, text, "Saved").unwrap();
|
||||
}
|
||||
h.record(&multi, "v1", "Saved").unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
h.record(&multi, "v2", "Saved").unwrap();
|
||||
h.put_label(&root, "Before Git checkout").unwrap();
|
||||
let snapshots = |path: &Path| -> Vec<HistoryEntry> {
|
||||
h.list(path).unwrap().into_iter().filter(|e| e.kind == HistoryKind::Snapshot).collect()
|
||||
};
|
||||
fs::write(&present, "p").unwrap();
|
||||
h.note_removed(std::slice::from_ref(&already)).unwrap();
|
||||
let entries_before_removal = h.state.lock().entries.len();
|
||||
assert_eq!(snapshots(&already)[0].label, DELETED, "recorded as deleted before the batch");
|
||||
let already_entries = snapshots(&already).len();
|
||||
|
||||
// `dir2` shares the name prefix of `dir` but is not below it.
|
||||
h.note_removed(&[]).unwrap();
|
||||
assert_eq!(h.state.lock().entries.len(), entries_before_removal, "an empty batch changes nothing");
|
||||
h.note_removed(&[root.join("dir"), solo.clone(), multi.clone(), present.clone(), already.clone()]).unwrap();
|
||||
|
||||
for (path, text) in [(&a, "a"), (&b, "b"), (&solo, "s"), (&multi, "v2")] {
|
||||
let newest = &snapshots(path)[0];
|
||||
assert_eq!((newest.label.as_str(), h.content(&newest.id).unwrap().as_str()), (DELETED, text));
|
||||
}
|
||||
assert_eq!(snapshots(&multi).len(), 3, "Saved v1, Saved v2, Deleted");
|
||||
assert!(snapshots(&sibling).iter().all(|e| e.label != DELETED), "sibling with a shared name prefix");
|
||||
assert!(snapshots(&present).iter().all(|e| e.label != DELETED), "still on disk");
|
||||
assert_eq!(snapshots(&already).len(), already_entries, "already recorded as deleted");
|
||||
assert_eq!(
|
||||
h.state.lock().entries.len(),
|
||||
entries_before_removal + 4,
|
||||
"one Deleted entry each for a, b, solo and multi"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_undo_captures_current_bytes_and_empty_folders() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -113,13 +113,7 @@ fn restrict_project_layer(below: &Json, layer: &mut Json) {
|
||||
// The IDE-wide interpreter list, its view options and the project interpreters of
|
||||
// other projects belong to the user's settings, not to one project.
|
||||
if let Some(python) = layer.get_mut("languages").and_then(|l| l.get_mut("python")).and_then(Json::as_object_mut) {
|
||||
for key in [
|
||||
"interpreters",
|
||||
"hiddenInterpreters",
|
||||
"hideOtherProjectInterpreters",
|
||||
"showInterpreterPaths",
|
||||
"interpreterPaths",
|
||||
] {
|
||||
for key in ["interpreters", "hiddenInterpreters", "hideOtherProjectInterpreters", "showInterpreterPaths"] {
|
||||
python.remove(key);
|
||||
}
|
||||
}
|
||||
@@ -736,8 +730,6 @@ mod tests {
|
||||
let store = SettingsStore::load(&cfg, Some(&proj));
|
||||
store.set(SettingsScope::Global, "languages.python.interpreters", json!(["/envs/a/bin/python"])).unwrap();
|
||||
store.set(SettingsScope::Global, "languages.python.showInterpreterPaths", json!(false)).unwrap();
|
||||
let paths = json!({ "/envs/a/bin/python": ["/shared/lib"] });
|
||||
store.set(SettingsScope::Global, "languages.python.interpreterPaths", paths).unwrap();
|
||||
let loaded = SettingsStore::load(&cfg, Some(&proj)).effective();
|
||||
assert_eq!(loaded.languages.python.interpreters, ["/envs/a/bin/python"]);
|
||||
assert!(!loaded.languages.python.show_interpreter_paths);
|
||||
@@ -747,12 +739,10 @@ mod tests {
|
||||
proj.join(".openidea/settings.toml"),
|
||||
"[languages.python]\ninterpreters = [\"/proj/bin/python\"]\n\
|
||||
hiddenInterpreters = [\"/envs/a/bin/python\"]\nhideOtherProjectInterpreters = true\n\
|
||||
showInterpreterPaths = true\n\
|
||||
[languages.python.interpreterPaths]\n\"/envs/a/bin/python\" = [\"/proj/evil\"]\n",
|
||||
showInterpreterPaths = true\n",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = SettingsStore::load(&cfg, Some(&proj)).effective();
|
||||
assert_eq!(loaded.languages.python.interpreter_paths["/envs/a/bin/python"], ["/shared/lib"]);
|
||||
assert_eq!(loaded.languages.python.interpreters, ["/envs/a/bin/python"]);
|
||||
assert!(loaded.languages.python.hidden_interpreters.is_empty());
|
||||
assert!(!loaded.languages.python.hide_other_project_interpreters);
|
||||
|
||||
@@ -64,7 +64,7 @@ JSON-RPC 2.0 with `Content-Length` framing (`ide-jsonrpc`), over the server's st
|
||||
| notification `plugin` | server → client | `{ window, event }` from code plugins of the remote project |
|
||||
| request `plugin_secret` | server → client | `{ plugin, name }` → `string` or `null`: a secret from the desktop's keychain |
|
||||
|
||||
The protocol version is `PROTOCOL_VERSION` in `rpc.rs`; the desktop refuses a server that speaks another one. Change it when an existing command's argument or result changes shape. A binary argument is an `IpcBytes` (a base64 string in JSON, `string` in the bindings), never a `Vec<u8>`, which is an array of numbers about 3.6 times the size. Errors are `IdeError`s carried as JSON in the JSON-RPC error message, so the frontend sees the same `kind` / `message` as for a local command.
|
||||
The protocol version is `PROTOCOL_VERSION` in `rpc.rs`. Errors are `IdeError`s carried as JSON in the JSON-RPC error message, so the frontend sees the same `kind` / `message` as for a local command.
|
||||
|
||||
## Routing commands
|
||||
|
||||
|
||||
@@ -125,16 +125,16 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
## Manage agents
|
||||
|
||||
**Settings › Agents › Agent Setup** (also **More Agents…** in the agent picker) lists built-in agents and agents from the ACP Registry.
|
||||
**Settings › Tools › Agents** (also **More Agents…** in the agent picker) has two tabs:
|
||||
|
||||
- **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions. When the agent is a global npm install (such as Claude Code, Codex or Gemini CLI), **Check for updates** compares it with npm's latest stable release and **Update to…** updates that installation.
|
||||
- **ACP Registry**: agents published in the [ACP Registry](https://agentclientprotocol.com). Search, **Install**, **Update** and **Remove**. Installed agents are kept in OpenIDEA's data directory; downloads are checked against the registry's SHA-256 when it provides one.
|
||||
|
||||
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
**Settings › Tools › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
|
||||
### External MCP servers
|
||||
|
||||
**Settings › Agents › MCP Connections** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
|
||||
**Settings › Agents › External MCP Servers** configures MCP servers across three persistent levels, while the composer's **MCP** picker (or `/mcp`) controls them per session:
|
||||
|
||||
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
|
||||
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
|
||||
|
||||
@@ -69,7 +69,6 @@ Long operations (pull, prune, Compose) show progress at the top with a **Cancel*
|
||||
|
||||
Selecting an item shows tabs in the detail pane:
|
||||
|
||||
- **Compose project**: **Dashboard** (project overview, services with live resource usage, named volumes created by the project).
|
||||
- **Container**: **Dashboard** (overview, live resource usage, port bindings that open in the browser, mounts, networks, environment variables, labels), **Log** (last 1,000 lines, following while the container runs, with **Timestamps**), **Processes** (`docker top`) and **Inspect** (the raw JSON).
|
||||
- **Image**: **Dashboard** (tags, containers using it, environment, labels), **Layers** and **Inspect**.
|
||||
- **Volume** and **network**: **Dashboard** and **Inspect**.
|
||||
|
||||
@@ -43,8 +43,7 @@ The project interpreter is chosen in this order:
|
||||
|
||||
1. The interpreter set in **Settings › Languages & Frameworks › Python Interpreter**.
|
||||
2. A virtualenv in the project: `.venv`, `venv`, `env` or `.env` (a folder with `pyvenv.cfg`), or a pixi environment in `.pixi/envs/`.
|
||||
3. The Pipenv environment for the nearest `Pipfile`, including one selected by a `.venv` file or `PIPENV_CUSTOM_VENV_NAME`.
|
||||
4. The Python version the project pins for mise or asdf (`mise.toml`, `.tool-versions` and the other mise config files).
|
||||
3. The Python version the project pins for mise or asdf (`mise.toml`, `.tool-versions` and the other mise config files).
|
||||
|
||||
The interpreter list on that page also shows what the IDE detects on the machine: the active `VIRTUAL_ENV`, virtualenvs made by virtualenvwrapper, pipenv and Poetry, pyenv versions, Pythons installed by uv, mise and asdf installs, conda environments (Miniconda, Anaconda, Miniforge, Mambaforge, micromamba, and every env that `conda env list` shows), and the `python` executables on `PATH`.
|
||||
|
||||
@@ -52,10 +51,6 @@ The selected interpreter is passed to basedpyright and Pyright (`python.pythonPa
|
||||
|
||||
The **Python Interpreter** item in the status bar shows the current interpreter. Click it to switch, or to open **Add New Interpreter…** and **Interpreter Settings…**.
|
||||
|
||||
### Interpreter paths
|
||||
|
||||
**Settings › Languages & Frameworks › Python › All Interpreters › Show Paths for Selected Interpreter** lists the interpreter's `sys.path` and lets you add folders outside the project to it, such as a checkout of a shared library. The added folders are saved per interpreter in the IDE settings, so they apply to every project that uses it. basedpyright and Pyright get them as `extraPaths`, runs, debug sessions, tests and the Python Console get them on `PYTHONPATH`, and they are listed under **External Libraries**. At run time they are searched before the interpreter's own entries. A folder that no longer exists is marked as missing and skipped, and so is one that `PYTHONPATH` cannot hold (not absolute, or with its separator in the name). A folder inside the project is not listed under External Libraries, so its files stay editable. The interpreter's own entries cannot be removed, and a Docker or Compose run target has no paths of its own to edit.
|
||||
|
||||
### A Docker or Compose run target as the interpreter
|
||||
|
||||
When the project's dependencies are installed only in an image, choose a Docker or Docker Compose [run target](/en/guide/remote/containers#docker-and-docker-compose-run-targets) as the interpreter: the interpreter list and the status bar item show those targets next to the local interpreters.
|
||||
@@ -74,7 +69,6 @@ On **Settings › Languages & Frameworks › Python Interpreter**, choose **Add
|
||||
- **Virtualenv Environment**: `python -m venv` from the base interpreter you pick.
|
||||
- **uv Environment**: `uv venv <location> --python <base>` (uv must be on `PATH`).
|
||||
- **Poetry Environment**: `poetry env use <base>` in the project.
|
||||
- **Pipenv Environment**: `pipenv --python <base>` in the project (pipenv must be on `PATH`). Pipenv writes a `Pipfile` when the project has none, importing `requirements.txt` if there is one. With **Install packages from Pipfile** it then runs `pipenv install --dev`. An environment the project already has is reused; if it was built on another Python version than the base interpreter, nothing is changed and the dialog says so (remove it with `pipenv --rm` to start over).
|
||||
- **Conda Environment**: `conda create -n <name>` in conda's envs directory, with the chosen Python version.
|
||||
|
||||
You can also select an existing interpreter or environment folder. The new interpreter becomes the project interpreter.
|
||||
|
||||
@@ -20,7 +20,7 @@ A file holds only the values that differ from the layer below. Tables merge key
|
||||
|
||||
Some settings are ignored in the project file: `mcpServer`, imported color schemes (`editor.customSchemes`) and `agents.newTaskApprovals` are global only. Project trust is never read from settings.
|
||||
|
||||
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › MCP Connections**, and again after its definition changes.
|
||||
A project file can't loosen what coding agents may do: `agentSecurity.allowedCommands` and `agents.defaults` are global only, and `agentSecurity.blockedCommands` in a project adds to the global list rather than replacing it. An MCP server in the project's `agents.mcpServers` stays off until you turn it on in **Settings › Agents › External MCP Servers**, and again after its definition changes.
|
||||
|
||||
## File format
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <por
|
||||
| 通知 `plugin` | 服务端 → 客户端 | `{ window, event }`:远程项目中代码插件发出的事件 |
|
||||
| 请求 `plugin_secret` | 服务端 → 客户端 | `{ plugin, name }` → `string` 或 `null`:从桌面端钥匙串取密钥 |
|
||||
|
||||
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`;桌面端会拒绝使用其他版本协议的服务端。已有命令的参数或结果形态改变时要修改它。二进制参数使用 `IpcBytes`(JSON 中是 base64 字符串,绑定中是 `string`),不要用 `Vec<u8>`——它会变成体积约 3.6 倍的数字数组。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
|
||||
协议版本是 `rpc.rs` 中的 `PROTOCOL_VERSION`。错误是以 JSON 形式放在 JSON-RPC 错误消息里的 `IdeError`,所以前端看到的 `kind` / `message` 与本地命令完全一样。
|
||||
|
||||
## 命令路由
|
||||
|
||||
|
||||
@@ -125,16 +125,16 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
## 管理 agent
|
||||
|
||||
**设置 › 智能体 › 智能体配置**(也可以在 agent 选择器中点 **更多 Agent…**)列出了内置智能体和 ACP Registry 提供的智能体。
|
||||
**设置 › 工具 › 智能体**(也可以在 agent 选择器中点 **更多 Agent…**)有两个标签页:
|
||||
|
||||
- **内置**:每个内置 agent 的可执行文件是否在 `PATH` 中找到、指定 **自定义可执行文件** 的输入框、传给 agent 进程的 **环境变量**(格式为 `NAME=value; OTHER=value`;这些值保存在系统凭据存储中)以及登录方式。改动对新会话生效。如果 agent 是 npm 全局安装(例如 Claude Code、Codex、Gemini CLI),**检查更新** 会与 npm 的最新稳定版比较,点击 **更新至…** 即可更新这份安装。
|
||||
- **ACP 注册表**:[ACP Registry](https://agentclientprotocol.com) 中发布的 agent,可以搜索、**安装**、**更新** 和 **移除**。安装的 agent 保存在 OpenIDEA 的数据目录中;注册表提供 SHA-256 时会校验下载内容。
|
||||
|
||||
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
**设置 › 工具 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
|
||||
### 外部 MCP 服务器
|
||||
|
||||
**设置 › 智能体 › MCP 连接** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
|
||||
**设置 › 智能体 › 外部 MCP 服务器** 按三个持久层级管理 MCP 服务器,输入框底部的 **MCP** 选择器(或 `/mcp` 命令)则按单个会话控制它们:
|
||||
|
||||
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
|
||||
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
|
||||
|
||||
@@ -69,7 +69,6 @@ OpenIDEA 通过 `docker` 命令行操作 Docker,所以只要能提供可用的
|
||||
|
||||
选中某项后,详情区会显示以下标签页:
|
||||
|
||||
- **Compose 项目**:**仪表盘**(项目概览、各服务的实时资源使用情况、该项目创建的命名卷)。
|
||||
- **容器**:**仪表盘**(概览、实时资源使用情况、可在浏览器中打开的端口绑定、挂载、网络、环境变量、标签)、**日志**(最近 1,000 行,容器运行时持续跟随,可切换 **时间戳**)、**进程**(`docker top`)和 **检查**(原始 JSON)。
|
||||
- **镜像**:**仪表盘**(标签、使用它的容器、环境变量、标签)、**镜像层** 和 **检查**。
|
||||
- **卷** 和 **网络**:**仪表盘** 和 **检查**。
|
||||
|
||||
@@ -43,8 +43,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
|
||||
|
||||
1. **设置 › 语言和框架 › Python 解释器** 中选定的解释器。
|
||||
2. 项目里的虚拟环境:`.venv`、`venv`、`env` 或 `.env`(含 `pyvenv.cfg` 的目录),或 `.pixi/envs/` 下的 pixi 环境。
|
||||
3. 最近的 `Pipfile` 对应的 Pipenv 环境,包括通过 `.venv` 文件或 `PIPENV_CUSTOM_VENV_NAME` 指定的环境。
|
||||
4. 项目通过 mise 或 asdf 固定的 Python 版本(`mise.toml`、`.tool-versions` 等 mise 配置文件)。
|
||||
3. 项目通过 mise 或 asdf 固定的 Python 版本(`mise.toml`、`.tool-versions` 等 mise 配置文件)。
|
||||
|
||||
该页面的解释器列表还会列出 IDE 在本机找到的解释器:当前激活的 `VIRTUAL_ENV`,virtualenvwrapper、pipenv 和 Poetry 创建的虚拟环境,pyenv 的各个版本,uv 安装的 Python,mise 和 asdf 的安装,conda 环境(Miniconda、Anaconda、Miniforge、Mambaforge、micromamba,以及 `conda env list` 能看到的所有环境),还有 `PATH` 上的 `python` 可执行文件。
|
||||
|
||||
@@ -52,10 +51,6 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
|
||||
|
||||
状态栏上的 **Python 解释器** 显示当前解释器,点击可以切换,也可以打开 **添加新的解释器…** 和 **解释器设置…**。
|
||||
|
||||
### 解释器路径
|
||||
|
||||
**设置 › 语言和框架 › Python › 所有解释器 › 显示所选解释器的路径** 列出该解释器的 `sys.path`,并可以把项目之外的文件夹(例如共享库的检出目录)添加进去。添加的文件夹按解释器保存在 IDE 设置中,因此对使用该解释器的每个项目生效。basedpyright 和 Pyright 通过 `extraPaths` 获得这些文件夹,运行、调试、测试和 Python 控制台通过 `PYTHONPATH` 获得,它们也会显示在 **External Libraries** 下。运行时它们会先于解释器自带的条目被搜索。已不存在的文件夹会标记为缺失并被跳过;`PYTHONPATH` 无法容纳的文件夹(不是绝对路径,或名称中含有分隔符)同样会被跳过。位于项目内的文件夹不会列在 External Libraries 下,其中的文件仍可编辑。解释器自带的条目不能删除,Docker 或 Compose 运行目标没有可编辑的路径。
|
||||
|
||||
### 以 Docker 或 Compose 运行目标作为解释器
|
||||
|
||||
如果项目的依赖只安装在镜像里,可以把 Docker 或 Docker Compose [运行目标](/zh/guide/remote/containers#docker-和-docker-compose-运行目标)选为解释器:解释器列表和状态栏项会把这些目标列在本地解释器旁边。
|
||||
@@ -74,7 +69,6 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
|
||||
- **Virtualenv 环境**:用你选的基础解释器执行 `python -m venv`。
|
||||
- **uv 环境**:执行 `uv venv <location> --python <base>`(`PATH` 上需要有 uv)。
|
||||
- **Poetry 环境**:在项目中执行 `poetry env use <base>`。
|
||||
- **Pipenv 环境**:在项目中执行 `pipenv --python <base>`(`PATH` 上需要有 pipenv)。项目没有 `Pipfile` 时,Pipenv 会写入一个,有 `requirements.txt` 时从中导入。勾选 **安装 Pipfile 中的软件包** 时,随后执行 `pipenv install --dev`。项目已有的环境会被复用;如果它的 Python 版本与基础解释器不同,不做任何改动并在对话框中提示(可用 `pipenv --rm` 删除后重建)。
|
||||
- **Conda 环境**:执行 `conda create -n <名称>`,环境建在 conda 的 envs 目录中,Python 版本为所选版本。
|
||||
|
||||
也可以直接选择已有的解释器或环境目录。新解释器会成为项目解释器。
|
||||
|
||||
@@ -20,7 +20,7 @@ description: "OpenIDEA 的设置保存在哪里、全局文件与项目文件如
|
||||
|
||||
有些设置在项目文件中会被忽略:`mcpServer`、导入的配色方案(`editor.customSchemes`)和 `agents.newTaskApprovals` 只能全局配置。项目信任状态永远不会从设置文件中读取。
|
||||
|
||||
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › MCP 连接** 中将其开启;服务器定义改变后也需要重新开启。
|
||||
项目文件不能放宽编码智能体的权限:`agentSecurity.allowedCommands` 和 `agents.defaults` 只能全局配置;项目中的 `agentSecurity.blockedCommands` 会追加到全局列表中,而不是替换它。项目 `agents.mcpServers` 中的 MCP 服务器会保持关闭,直到你在 **设置 › 智能体 › 外部 MCP 服务器** 中将其开启;服务器定义改变后也需要重新开启。
|
||||
|
||||
## 文件格式
|
||||
|
||||
|
||||
@@ -131,60 +131,3 @@ for (const home of [false, true]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test("short prompts fit before and after a completed agent exchange", async ({ workbench: page }) => {
|
||||
await prepare(page, true, false);
|
||||
const box = page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
|
||||
const scroller = page.locator(".cm-scroller").filter({ has: box });
|
||||
const overflow = () =>
|
||||
scroller.evaluate((el) => ({
|
||||
x: el.scrollWidth - el.clientWidth,
|
||||
y: el.scrollHeight - el.clientHeight,
|
||||
}));
|
||||
|
||||
await expect(box.locator(".cm-placeholder")).toBeVisible();
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
await box.fill("Reply with OK.");
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
await page.getByRole("button", { name: "Start", exact: true }).click();
|
||||
await expect(page.locator("html")).toHaveAttribute("data-submitted-prompt", /Reply with OK/);
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("test:agent-ack")));
|
||||
await expect(page.getByRole("tab", { name: task.title })).toBeVisible();
|
||||
await page.evaluate(async (id) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const { useAgents } = await import(storePath);
|
||||
useAgents.setState({
|
||||
entries: new Map([
|
||||
[
|
||||
id,
|
||||
[
|
||||
{ type: "user", text: "Reply with OK.", attachments: [] },
|
||||
{ type: "agent", text: "OK" },
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
}, task.id);
|
||||
await expect(page.getByText("OK", { exact: true })).toBeVisible();
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
|
||||
await expect(box.locator(".cm-placeholder")).toBeVisible();
|
||||
await expect(scroller).toHaveCSS("overflow-x", "hidden");
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
await box.fill("Short draft");
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
|
||||
await box.fill("word".repeat(2000));
|
||||
await expect(scroller).toHaveCSS("overflow-y", "auto");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const { x, y } = await overflow();
|
||||
return x === 0 && y > 0;
|
||||
})
|
||||
.toBe(true);
|
||||
await box.fill("");
|
||||
await expect(box.locator(".cm-placeholder")).toBeVisible();
|
||||
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
|
||||
});
|
||||
Loaded 100 of 576 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user