mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 23:56:05 -10:00
Compare commits
76
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6ad1bee8f | ||
|
|
3ed4fa6836 | ||
|
|
4990a90bbf | ||
|
|
762b509b66 | ||
|
|
2964b2ffc5 | ||
|
|
704952a6ae | ||
|
|
65007093e7 | ||
|
|
696ab0c3ba | ||
|
|
e282546697 | ||
|
|
93fb7b6a85 | ||
|
|
e691aa9fb3 | ||
|
|
44a12abbd7 | ||
|
|
497b25bf4a | ||
|
|
4ecfb98c94 | ||
|
|
f1d6b0dc1b | ||
|
|
f2cfe38931 | ||
|
|
d18ac58b56 | ||
|
|
0021a764c3 | ||
|
|
a30103d410 | ||
|
|
89798baa3c | ||
|
|
c09c9b8aaf | ||
|
|
995a9563f7 | ||
|
|
893d9af6e6 | ||
|
|
73496669e7 | ||
|
|
add914f7fb | ||
|
|
0fd0f08865 | ||
|
|
054d2ba517 | ||
|
|
738dc12ef7 | ||
|
|
6135a5326d | ||
|
|
403bb28ca4 | ||
|
|
3249d4ee90 | ||
|
|
79e41c85ff | ||
|
|
f0a7cca1b1 | ||
|
|
21f1e2bbb4 | ||
|
|
ffdb5d74f2 | ||
|
|
d4d9e7d191 | ||
|
|
6a41509fd2 | ||
|
|
6efece99a4 | ||
|
|
0fab45689f | ||
|
|
71090202b6 | ||
|
|
8ed08510ed | ||
|
|
500df4ffc4 | ||
|
|
81aa9418aa | ||
|
|
706ce87cb7 | ||
|
|
4e5dbc8e0c | ||
|
|
79accd1311 | ||
|
|
85d02e03f9 | ||
|
|
e689c95e93 | ||
|
|
bb243909bf | ||
|
|
64544a4edd | ||
|
|
4fd1e4356e | ||
|
|
1794cd4fbb | ||
|
|
10d39e14ca | ||
|
|
101890ab4c | ||
|
|
86778d259f | ||
|
|
59c39a7e77 | ||
|
|
4d45ddc5a5 | ||
|
|
bfd6f01471 | ||
|
|
895d042dd7 | ||
|
|
eb37d9e96a | ||
|
|
dc8ae96206 | ||
|
|
e70bca39ee | ||
|
|
2fe09e73f5 | ||
|
|
b921de184b | ||
|
|
23739c90c7 | ||
|
|
923325aeae | ||
|
|
d7351dca1d | ||
|
|
8959f7aa5d | ||
|
|
5e4f187107 | ||
|
|
aebd26bd7d | ||
|
|
c43a6169be | ||
|
|
c4836f6cd8 | ||
|
|
02235cae04 | ||
|
|
fcef18048a | ||
|
|
d72363b6ba | ||
|
|
4ab4e0b44f |
No files matched your search
+65
-15
@@ -32,7 +32,12 @@ jobs:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
rust: ${{ steps.classify.outputs.rust }}
|
||||
server: ${{ steps.classify.outputs.server }}
|
||||
plugins: ${{ steps.classify.outputs.plugins }}
|
||||
deny: ${{ steps.classify.outputs.deny }}
|
||||
frontend: ${{ steps.classify.outputs.frontend }}
|
||||
e2e: ${{ steps.classify.outputs.e2e }}
|
||||
catalog: ${{ steps.classify.outputs.catalog }}
|
||||
steps:
|
||||
- id: classify
|
||||
env:
|
||||
@@ -40,26 +45,55 @@ jobs:
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
jobs="rust server plugins deny frontend e2e catalog"
|
||||
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
|
||||
echo "rust=true" >> "$GITHUB_OUTPUT"
|
||||
echo "frontend=true" >> "$GITHUB_OUTPUT"
|
||||
for job in $jobs; do echo "$job=true" >> "$GITHUB_OUTPUT"; done
|
||||
exit 0
|
||||
fi
|
||||
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
|
||||
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
|
||||
cat files.txt
|
||||
# A change to CI itself runs everything.
|
||||
ci='^\.github/(workflows/ci\.yml|actions/)'
|
||||
docs='^(docs/|\.agents/|\.claude/|\.idea/|\.github/ISSUE_TEMPLATE/|\.github/pull_request_template\.md$|[^/]+\.md$|LICENSE$|NOTICE$)'
|
||||
# Frontend-only paths. The Rust code embeds a few files under src/; those stay out.
|
||||
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
|
||||
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|evals/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
|
||||
embedded='^src/(bindings\.ts|styles/tokens\.css|features/plugins/views/frame-bridge\.js|platform/keymaps/)'
|
||||
# A job runs when any changed file falls outside the paths that can't affect it.
|
||||
rust=false
|
||||
if grep -Ev "$docs|$web" files.txt | grep -q . || grep -Eq "$embedded" files.txt; then rust=true; fi
|
||||
frontend=false
|
||||
if grep -Ev "$docs" files.txt | grep -q .; then frontend=true; fi
|
||||
echo "rust=$rust frontend=$frontend"
|
||||
echo "rust=$rust" >> "$GITHUB_OUTPUT"
|
||||
echo "frontend=$frontend" >> "$GITHUB_OUTPUT"
|
||||
# Plugin web pages are their own pnpm projects, checked by the Plugins job only.
|
||||
plugin_web='^plugins/official/[^/]+/web-src/'
|
||||
# Paths the frontend checks never read...
|
||||
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)'
|
||||
# ...except these, which frontend tests and e2e fixtures load.
|
||||
read_by_web='^(fixtures/(folding|django-app)/|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# What the browser app and its e2e tests are built from.
|
||||
app='^(src/|e2e/|public/|index\.html$|vite\.config\.ts$|tsconfig\.json$|playwright\.config\.ts$|package\.json$|pnpm-(lock|workspace)\.yaml$|crates/ide-plugin/tests/fixtures/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# The plugin workspaces: the SDK, the plugins, their interface and the host's fixture plugins.
|
||||
plugin_ws='^(sdk/|plugins/|wit/|crates/ide-plugin/tests/fixtures/|rust-toolchain(\.toml)?$)'
|
||||
# Never compiled into the openidea-server binary.
|
||||
not_server='^(src-tauri/|sdk/|fixtures/|crates/[^/]+/(tests|benches)/)'
|
||||
deps='(^|/)Cargo\.(toml|lock)$|^deny\.toml$'
|
||||
# The text catalog test reads the string literals of every Rust source.
|
||||
rust_source='^(crates|src-tauri/src)/.*\.rs$'
|
||||
|
||||
any() { grep -Eq "$1" files.txt; }
|
||||
outside() { [ -n "$(grep -Ev "$1" files.txt || true)" ]; }
|
||||
set_job() { echo "$1=$2" | tee -a "$GITHUB_OUTPUT"; }
|
||||
|
||||
if any "$ci"; then
|
||||
for job in $jobs; do set_job "$job" true; done
|
||||
exit 0
|
||||
fi
|
||||
on() { if "${@:2}"; then set_job "$1" true; else set_job "$1" false; fi; }
|
||||
rust_build() { outside "$1" || any "$embedded"; }
|
||||
web_checks() { outside "$docs|$plugin_web|$backend" || any "$read_by_web"; }
|
||||
catalog_only() { ! web_checks && any "$rust_source"; }
|
||||
on rust rust_build "$docs|$web|$plugin_web"
|
||||
on server rust_build "$docs|$web|$plugin_web|$not_server"
|
||||
on plugins any "$plugin_ws"
|
||||
on deny any "$deps"
|
||||
on frontend web_checks
|
||||
on e2e any "$app"
|
||||
on catalog catalog_only
|
||||
|
||||
rust:
|
||||
name: Rust (${{ matrix.os }})
|
||||
@@ -111,7 +145,7 @@ jobs:
|
||||
server:
|
||||
name: Remote server (linux musl)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
if: needs.changes.outputs.server == 'true'
|
||||
timeout-minutes: 40
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
@@ -129,7 +163,7 @@ jobs:
|
||||
plugins:
|
||||
name: Plugins (SDK, official, fixtures)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
if: needs.changes.outputs.plugins == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
@@ -181,7 +215,7 @@ jobs:
|
||||
deny:
|
||||
name: Cargo deny
|
||||
needs: changes
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
if: needs.changes.outputs.deny == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -210,10 +244,26 @@ jobs:
|
||||
- run: pnpm test
|
||||
- run: pnpm build
|
||||
|
||||
# A backend-only change can still drop a string the text catalog uses: run that one test.
|
||||
catalog:
|
||||
name: Text catalog
|
||||
needs: changes
|
||||
if: needs.changes.outputs.catalog == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
|
||||
|
||||
e2e:
|
||||
name: E2E (${{ matrix.shard }}/2)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.frontend == 'true'
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
|
||||
@@ -15,6 +15,7 @@ on:
|
||||
- "crates/**"
|
||||
- "languages/**"
|
||||
- "fixtures/**"
|
||||
- "java/**"
|
||||
- "Cargo.toml"
|
||||
- "Cargo.lock"
|
||||
- "src/features/run/**"
|
||||
@@ -41,12 +42,77 @@ env:
|
||||
CARGO_INCREMENTAL: 0
|
||||
|
||||
jobs:
|
||||
# The languages a pull request can affect: a change to one language's fixture, definition or
|
||||
# JDT LS bundle runs that language; crates the smoke doesn't exercise and other crates' tests
|
||||
# run none; anything else runs them all. Pushes and manual runs always run them all.
|
||||
changes:
|
||||
name: Changes
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
languages: ${{ steps.classify.outputs.languages }}
|
||||
steps:
|
||||
- id: classify
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
all="typescript python rust go java kotlin php c cpp"
|
||||
emit() { tr ' ' '\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\n") | map(select(. != ""))'; }
|
||||
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
|
||||
echo "languages=$(emit "$all")" | tee -a "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
|
||||
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
|
||||
cat files.txt
|
||||
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
|
||||
# SDKs, build tools and the project model): cargo metadata, deps of ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-search|ide-spell|ide-ssh|ide-streams|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger)/|src/platform/|smoke/|package\.json$|pnpm-lock\.yaml$|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
crates/ide-host/tests/language_smoke.rs | crates/ide-host/tests/project_smoke.rs) langs="$all"; break ;;
|
||||
crates/*/tests/* | crates/*/benches/*) ;;
|
||||
fixtures/ts-app/*) langs+=" typescript" ;;
|
||||
fixtures/python-app/*) langs+=" python" ;;
|
||||
fixtures/rust-app/*) langs+=" rust" ;;
|
||||
fixtures/go-app/*) langs+=" go" ;;
|
||||
fixtures/java-app/*) langs+=" java" ;;
|
||||
fixtures/kotlin-gradle/*) langs+=" kotlin" ;;
|
||||
fixtures/php-app/*) langs+=" php" ;;
|
||||
fixtures/c-app/*) langs+=" c cpp" ;;
|
||||
fixtures/*) ;;
|
||||
languages/typescript.toml | languages/typescriptreact.toml | languages/javascript.toml | languages/javascriptreact.toml) langs+=" typescript" ;;
|
||||
languages/python.toml) langs+=" python" ;;
|
||||
languages/rust.toml) langs+=" rust" ;;
|
||||
languages/go.toml | languages/gomod.toml | languages/gowork.toml) langs+=" go" ;;
|
||||
languages/java.toml) langs+=" java" ;;
|
||||
languages/kotlin.toml) langs+=" kotlin" ;;
|
||||
languages/php.toml) langs+=" php" ;;
|
||||
languages/c.toml) langs+=" c" ;;
|
||||
languages/cpp.toml) langs+=" cpp" ;;
|
||||
languages/*) ;;
|
||||
java/kotlin-bridge/*) langs+=" kotlin" ;;
|
||||
java/*) langs+=" java kotlin" ;;
|
||||
*) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;;
|
||||
esac
|
||||
done < files.txt
|
||||
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
smoke:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
needs: changes
|
||||
if: needs.changes.outputs.languages != '[]'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: [typescript, python, rust, go, java, kotlin, php, c, cpp]
|
||||
language: ${{ fromJSON(needs.changes.outputs.languages) }}
|
||||
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
|
||||
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
|
||||
timeout-minutes: 40
|
||||
|
||||
+146
-32
@@ -359,6 +359,9 @@ struct TaskFile {
|
||||
/// `None` for a worktree task, and a task saved before these were recorded.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
touched: Option<BTreeSet<String>>,
|
||||
/// The checkout as the last turn started, its copies in the store's `<id>.turn` folder.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
turn: Option<worktree::TurnStart>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
subagents: Vec<SavedSubagent>,
|
||||
/// Turns to drop from the session once it is loaded (a fork of an earlier point).
|
||||
@@ -382,6 +385,8 @@ struct TaskState {
|
||||
saved: Option<String>,
|
||||
/// See `TaskFile::touched`.
|
||||
touched: Option<Arc<BTreeSet<String>>>,
|
||||
/// See `TaskFile::turn`.
|
||||
turn: Option<Arc<worktree::TurnStart>>,
|
||||
pending_rollback: u32,
|
||||
/// The user named the task; see `TaskFile::title_renamed`.
|
||||
title_renamed: bool,
|
||||
@@ -753,6 +758,7 @@ impl AgentManager {
|
||||
before: BTreeMap::new(),
|
||||
saved: None,
|
||||
touched: Some(BTreeSet::new()),
|
||||
turn: None,
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: true,
|
||||
@@ -866,6 +872,7 @@ impl AgentManager {
|
||||
before,
|
||||
saved,
|
||||
touched: (req.isolation == Isolation::Local).then(BTreeSet::new),
|
||||
turn: None,
|
||||
subagents: Vec::new(),
|
||||
pending_rollback: 0,
|
||||
title_renamed: false,
|
||||
@@ -1189,6 +1196,8 @@ impl AgentManager {
|
||||
before: (*s.before).clone(),
|
||||
saved: s.saved.clone(),
|
||||
touched: s.touched.as_deref().cloned(),
|
||||
// The source's next turn replaces its copies: the fork's last turn is one of its own.
|
||||
turn: None,
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: total - keep,
|
||||
title_renamed: s.title_renamed,
|
||||
@@ -1528,6 +1537,7 @@ impl AgentManager {
|
||||
self.tasks.write().remove(id);
|
||||
*task.deleted.lock() = true;
|
||||
let _ = std::fs::remove_file(self.shared.paths.store_dir.join(format!("{id}.json")));
|
||||
let _ = std::fs::remove_dir_all(task.turn_dir());
|
||||
let saved = task.state.lock().saved.clone();
|
||||
if let Some(saved) = saved
|
||||
&& !self.tasks.read().values().any(|t| t.state.lock().saved.as_ref() == Some(&saved))
|
||||
@@ -1570,18 +1580,47 @@ impl AgentManager {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Content of `path` (in the task's directory) when the task started.
|
||||
pub async fn base_text(&self, id: &str, path: PathBuf) -> IdeResult<Option<String>> {
|
||||
let at = self.task(id)?.base();
|
||||
blocking(move || match at.rev()? {
|
||||
Some(rev) => worktree::file_at(at.cwd(), &path, &rev),
|
||||
None => Ok(None),
|
||||
/// The files the task's last turn changed, against the checkout as it started (while a
|
||||
/// turn runs: that turn's so far). None before the task's first turn.
|
||||
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()) };
|
||||
blocking(move || {
|
||||
let changed = match &turn.changed {
|
||||
Some(changed) => changed.clone(),
|
||||
None => worktree::changed_in_turn(&cwd, &turn)?.1,
|
||||
};
|
||||
worktree::turn_changes(&cwd, &turn, &dir, &changed)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Content of `path` (in the task's directory) as `view` compares it: when the task
|
||||
/// started, in `HEAD`, or when the last turn started.
|
||||
pub async fn base_text(&self, id: &str, path: PathBuf, view: AgentChangesView) -> IdeResult<Option<String>> {
|
||||
let task = self.task(id)?;
|
||||
if view == AgentChangesView::LastTurn {
|
||||
let (cwd, turn, dir) = task.last_turn();
|
||||
let Some(turn) = turn else { return Ok(None) };
|
||||
return blocking(move || worktree::turn_text(&cwd, &path, &turn, &dir)).await;
|
||||
}
|
||||
let at = task.base();
|
||||
blocking(move || {
|
||||
let rev = match view {
|
||||
AgentChangesView::Group => worktree::head_commit(at.cwd())?,
|
||||
_ => at.rev()?,
|
||||
};
|
||||
match rev {
|
||||
Some(rev) => worktree::file_at(at.cwd(), &path, &rev),
|
||||
None => Ok(None),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Rollback: puts the task's changed files among `rel_paths` (all with `None`) back as
|
||||
/// `view` compares them: as they were when it started, or as they are in `HEAD`.
|
||||
/// `view` compares them: as they were when it started, as they are in `HEAD`, or as they
|
||||
/// were when its last turn started.
|
||||
pub async fn rollback_changes(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -1592,15 +1631,18 @@ impl AgentManager {
|
||||
if task.state.lock().busy {
|
||||
return Err(IdeError::invalid("the agent is working: stop it before rolling back its changes"));
|
||||
}
|
||||
if view == AgentChangesView::LastTurn {
|
||||
return self.rollback_turn(&task, rel_paths).await;
|
||||
}
|
||||
let at = task.base();
|
||||
let (before, saved, touched) = {
|
||||
let s = task.state.lock();
|
||||
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)), s.touched.clone())
|
||||
};
|
||||
let restamped = blocking(move || {
|
||||
let (restamped, restored) = blocking(move || {
|
||||
let (changes, rev) = match view {
|
||||
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
|
||||
AgentChangesView::SinceStart => (at.changes(&before)?, 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() {
|
||||
@@ -1608,6 +1650,7 @@ impl AgentManager {
|
||||
None => Default::default(),
|
||||
};
|
||||
let mut restamped = Vec::new();
|
||||
let mut restored = Vec::new();
|
||||
for change in changes.iter().filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path))) {
|
||||
// A rename goes back to its old path too; the new one is taken away first, so a
|
||||
// case-only rename on a case-insensitive disk ends as the old file.
|
||||
@@ -1617,6 +1660,58 @@ impl AgentManager {
|
||||
if before.contains_key(&change.rel_path) {
|
||||
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
|
||||
}
|
||||
restored.push(change.rel_path.clone());
|
||||
}
|
||||
}
|
||||
Ok((restamped, restored))
|
||||
})
|
||||
.await?;
|
||||
{
|
||||
let mut s = task.state.lock();
|
||||
if !restamped.is_empty() {
|
||||
let mut before = (*s.before).clone();
|
||||
before.extend(restamped);
|
||||
s.before = Arc::new(before);
|
||||
}
|
||||
// Rolled back further than the last turn: what it changed there is gone, not the turn's to list.
|
||||
if let Some(turn) = &s.turn
|
||||
&& let Some(changed) = &turn.changed
|
||||
&& restored.iter().any(|rel| changed.contains(rel))
|
||||
{
|
||||
let changed = changed.iter().filter(|rel| !restored.contains(rel)).cloned().collect();
|
||||
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(changed), ..(**turn).clone() }));
|
||||
}
|
||||
}
|
||||
task.persist();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Puts the last turn's changed files among `rel_paths` (all with `None`) back as they
|
||||
/// were when it started.
|
||||
async fn rollback_turn(&self, task: &Task, rel_paths: Option<Vec<String>>) -> IdeResult<()> {
|
||||
let (cwd, turn, dir) = task.last_turn();
|
||||
let Some(turn) = turn else { return Ok(()) };
|
||||
let (before, saved) = {
|
||||
let s = task.state.lock();
|
||||
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
|
||||
};
|
||||
let restamped = blocking(move || {
|
||||
let changed = match &turn.changed {
|
||||
Some(changed) => changed.clone(),
|
||||
None => worktree::changed_in_turn(&cwd, &turn)?.1,
|
||||
};
|
||||
let mut restamped = Vec::new();
|
||||
for change in worktree::turn_changes(&cwd, &turn, &dir, &changed)?
|
||||
.iter()
|
||||
.filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path)))
|
||||
{
|
||||
worktree::restore_turn(&cwd, &turn, &dir, change)?;
|
||||
// Back to the user's own edits from before the task: not a change of the task.
|
||||
if let Some(Some(_)) = before.get(&change.rel_path)
|
||||
&& let Some(copy) = saved.as_deref().and_then(|d| worktree::saved_copy(d, &change.rel_path))
|
||||
&& std::fs::read(&change.path.0).is_ok_and(|now| now == copy)
|
||||
{
|
||||
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
|
||||
}
|
||||
}
|
||||
Ok(restamped)
|
||||
@@ -1752,6 +1847,7 @@ impl Task {
|
||||
before: Arc::new(file.before),
|
||||
saved: file.saved,
|
||||
touched: file.touched.map(Arc::new),
|
||||
turn: file.turn.map(Arc::new),
|
||||
pending_rollback: file.pending_rollback,
|
||||
title_renamed: file.title_renamed,
|
||||
busy: false,
|
||||
@@ -1785,31 +1881,48 @@ impl Task {
|
||||
(s.before.clone(), s.touched.clone())
|
||||
}
|
||||
|
||||
/// The changed files of the checkout as a turn starts, when the task records what its turns change.
|
||||
async fn checkout_before_turn(&self) -> Option<Snapshot> {
|
||||
let cwd = {
|
||||
let s = self.state.lock();
|
||||
s.touched.as_ref()?;
|
||||
s.task.cwd.0.clone()
|
||||
};
|
||||
blocking(move || worktree::snapshot(&cwd)).await.ok()
|
||||
/// Where the copies of the files already changed as the last turn started are kept.
|
||||
fn turn_dir(&self) -> PathBuf {
|
||||
self.shared.paths.store_dir.join(format!("{}.turn", self.id))
|
||||
}
|
||||
|
||||
/// Records the files that changed in the checkout since `start`, as the turn ends, as the task's.
|
||||
async fn record_turn_changes(&self, start: Option<Snapshot>) {
|
||||
let Some(start) = start else { return };
|
||||
let cwd = self.state.lock().task.cwd.0.clone();
|
||||
let Ok(end) = blocking(move || worktree::snapshot(&cwd)).await else { return };
|
||||
let changed = worktree::changed_between(&start, &end);
|
||||
if changed.is_empty() {
|
||||
return;
|
||||
}
|
||||
/// The checkout as the last turn started, with the folder of its copies.
|
||||
fn last_turn(&self) -> (PathBuf, Option<Arc<worktree::TurnStart>>, PathBuf) {
|
||||
let s = self.state.lock();
|
||||
(s.task.cwd.0.clone(), s.turn.clone(), self.turn_dir())
|
||||
}
|
||||
|
||||
/// Records the checkout as a turn starts: what the turn's changes are compared with.
|
||||
async fn checkout_before_turn(&self) {
|
||||
let (cwd, previous, dir) = self.last_turn();
|
||||
let turn = match blocking(move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
|
||||
Ok(turn) => Some(Arc::new(turn)),
|
||||
Err(e) => {
|
||||
tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id);
|
||||
None
|
||||
}
|
||||
};
|
||||
self.state.lock().turn = turn;
|
||||
self.persist();
|
||||
}
|
||||
|
||||
/// Records the files that changed in the checkout while the turn ran: the turn's, and in
|
||||
/// the project's own checkout also the task's.
|
||||
async fn record_turn_changes(&self) {
|
||||
let (cwd, turn, _) = self.last_turn();
|
||||
let Some(turn) = turn else { return };
|
||||
let start = turn.clone();
|
||||
let Ok((in_worktree, all)) = blocking(move || worktree::changed_in_turn(&cwd, &start)).await else { return };
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
let Some(touched) = &s.touched else { return };
|
||||
let mut touched = (**touched).clone();
|
||||
touched.extend(changed);
|
||||
s.touched = Some(Arc::new(touched));
|
||||
if !in_worktree.is_empty()
|
||||
&& let Some(touched) = &s.touched
|
||||
{
|
||||
let mut touched = (**touched).clone();
|
||||
touched.extend(in_worktree);
|
||||
s.touched = Some(Arc::new(touched));
|
||||
}
|
||||
s.turn = Some(Arc::new(worktree::TurnStart { changed: Some(all), ..(*turn).clone() }));
|
||||
}
|
||||
self.persist();
|
||||
}
|
||||
@@ -1926,6 +2039,7 @@ impl Task {
|
||||
before: (*s.before).clone(),
|
||||
saved: s.saved.clone(),
|
||||
touched: s.touched.as_deref().cloned(),
|
||||
turn: s.turn.as_deref().cloned(),
|
||||
subagents: s.conversation.saved_subagents(),
|
||||
pending_rollback: s.pending_rollback,
|
||||
title_renamed: s.title_renamed,
|
||||
@@ -1977,11 +2091,11 @@ impl Task {
|
||||
/// the user stops one. The caller set `busy`.
|
||||
async fn run(self: Arc<Self>, mut prompt: AgentPrompt) {
|
||||
loop {
|
||||
let start = self.checkout_before_turn().await;
|
||||
self.checkout_before_turn().await;
|
||||
let result = self.turn(&prompt).await;
|
||||
self.cancel_pending.store(false, Ordering::Release);
|
||||
tokio::time::sleep(TURN_GRACE).await;
|
||||
self.record_turn_changes(start).await;
|
||||
self.record_turn_changes().await;
|
||||
let changed = self.state.lock().conversation.end_turn(Some(now_ms()));
|
||||
self.mark_dirty(changed);
|
||||
let send_now = self.send_now.swap(false, Ordering::AcqRel);
|
||||
|
||||
+436
-49
@@ -399,163 +399,429 @@ pub fn apply_save_json(
|
||||
Ok(saved_names)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
|
||||
".github/plugin/plugin.json",
|
||||
".plugin/plugin.json",
|
||||
".claude-plugin/plugin.json",
|
||||
".cursor-plugin/plugin.json",
|
||||
"plugin.json",
|
||||
];
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum SourceFormat {
|
||||
Jsonc,
|
||||
CodexToml,
|
||||
CopilotPlugin { root: PathBuf },
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct SourceSpec {
|
||||
id: &'static str,
|
||||
label: &'static str,
|
||||
id: String,
|
||||
label: String,
|
||||
path: PathBuf,
|
||||
format: SourceFormat,
|
||||
suggested_scope: McpScope,
|
||||
native_provider: Option<&'static str>,
|
||||
claude_project_lookup: bool,
|
||||
disabled_servers: std::sync::Arc<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CopilotSettings {
|
||||
disabled_mcp_servers: std::sync::Arc<BTreeSet<String>>,
|
||||
disabled_plugins: BTreeSet<String>,
|
||||
}
|
||||
|
||||
fn external_source_specs(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<SourceSpec> {
|
||||
let mut specs = Vec::new();
|
||||
let no_disabled: std::sync::Arc<BTreeSet<String>> = std::sync::Arc::new(BTreeSet::new());
|
||||
if let Some(root) = workspace_root {
|
||||
specs.push(SourceSpec {
|
||||
id: "workspace-mcp",
|
||||
label: "Project (.mcp.json)",
|
||||
id: "workspace-mcp".into(),
|
||||
label: "Project (.mcp.json)".into(),
|
||||
path: root.join(".mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("claude"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "vscode-mcp",
|
||||
label: "VS Code (.vscode/mcp.json)",
|
||||
id: "vscode-mcp".into(),
|
||||
label: "VS Code (.vscode/mcp.json)".into(),
|
||||
path: root.join(".vscode").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "cursor-project",
|
||||
label: "Cursor Project (.cursor/mcp.json)",
|
||||
id: "cursor-project".into(),
|
||||
label: "Cursor Project (.cursor/mcp.json)".into(),
|
||||
path: root.join(".cursor").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("cursor"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "codex-project",
|
||||
label: "Codex Project (.codex/config.toml)",
|
||||
id: "codex-project".into(),
|
||||
label: "Codex Project (.codex/config.toml)".into(),
|
||||
path: root.join(".codex").join("config.toml"),
|
||||
format: SourceFormat::CodexToml,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("codex"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "gemini-project",
|
||||
label: "Gemini Project (.gemini/settings.json)",
|
||||
id: "gemini-project".into(),
|
||||
label: "Gemini Project (.gemini/settings.json)".into(),
|
||||
path: root.join(".gemini").join("settings.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::Workspace,
|
||||
native_provider: Some("gemini"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
}
|
||||
if let Some(home) = home_dir {
|
||||
let copilot_dir = home.join(".copilot");
|
||||
let copilot_settings = read_copilot_settings(&copilot_dir);
|
||||
specs.push(SourceSpec {
|
||||
id: "copilot-cli",
|
||||
label: "GitHub Copilot CLI",
|
||||
path: home.join(".copilot").join("mcp-config.json"),
|
||||
id: "copilot-cli".into(),
|
||||
label: "GitHub Copilot CLI".into(),
|
||||
path: copilot_dir.join("mcp-config.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("copilot"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: copilot_settings.disabled_mcp_servers.clone(),
|
||||
});
|
||||
specs.extend(copilot_plugin_source_specs(&copilot_dir, &copilot_settings));
|
||||
specs.push(SourceSpec {
|
||||
id: "claude-code",
|
||||
label: "Claude Code",
|
||||
id: "claude-code".into(),
|
||||
label: "Claude Code".into(),
|
||||
path: home.join(".claude.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("claude"),
|
||||
claude_project_lookup: true,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "codex",
|
||||
label: "Codex",
|
||||
id: "codex".into(),
|
||||
label: "Codex".into(),
|
||||
path: home.join(".codex").join("config.toml"),
|
||||
format: SourceFormat::CodexToml,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("codex"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "cursor",
|
||||
label: "Cursor",
|
||||
id: "cursor".into(),
|
||||
label: "Cursor".into(),
|
||||
path: home.join(".cursor").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("cursor"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "gemini",
|
||||
label: "Gemini CLI",
|
||||
id: "gemini".into(),
|
||||
label: "Gemini CLI".into(),
|
||||
path: home.join(".gemini").join("settings.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("gemini"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "jetbrains-air",
|
||||
label: "JetBrains Air",
|
||||
id: "jetbrains-air".into(),
|
||||
label: "JetBrains Air".into(),
|
||||
path: home.join(".jetbrains").join("mcp").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled.clone(),
|
||||
});
|
||||
specs.push(SourceSpec {
|
||||
id: "copilot-intellij",
|
||||
label: "GitHub Copilot (JetBrains)",
|
||||
id: "copilot-intellij".into(),
|
||||
label: "GitHub Copilot (JetBrains)".into(),
|
||||
path: home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
|
||||
format: SourceFormat::Jsonc,
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: None,
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: no_disabled,
|
||||
});
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
fn read_copilot_settings(copilot_dir: &Path) -> CopilotSettings {
|
||||
let Ok(text) = std::fs::read_to_string(copilot_dir.join("settings.json")) else {
|
||||
return CopilotSettings::default();
|
||||
};
|
||||
if spec.format == SourceFormat::CodexToml {
|
||||
return parse_codex_toml_servers(&text);
|
||||
}
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return BTreeMap::new();
|
||||
return CopilotSettings::default();
|
||||
};
|
||||
let mut servers = extract_servers_from_root(&root, None);
|
||||
if spec.claude_project_lookup
|
||||
&& let Some(ws) = workspace_root
|
||||
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
|
||||
{
|
||||
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
|
||||
for (proj_key, proj_val) in projects {
|
||||
let matches = Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
|
||||
if matches {
|
||||
for (name, srv) in extract_servers_from_root(proj_val, None) {
|
||||
servers.insert(name, srv);
|
||||
let disabled_mcp_servers = root
|
||||
.get("disabledMcpServers")
|
||||
.and_then(Value::as_array)
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned))
|
||||
.collect::<BTreeSet<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let disabled_plugins = root
|
||||
.get("enabledPlugins")
|
||||
.and_then(Value::as_object)
|
||||
.map(|obj| {
|
||||
obj.iter()
|
||||
.filter(|(_, v)| v.as_bool() == Some(false))
|
||||
.map(|(k, _)| k.trim().to_owned())
|
||||
.filter(|k| !k.is_empty())
|
||||
.collect::<BTreeSet<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
CopilotSettings { disabled_mcp_servers: std::sync::Arc::new(disabled_mcp_servers), disabled_plugins }
|
||||
}
|
||||
|
||||
fn copilot_plugin_source_specs(copilot_dir: &Path, settings: &CopilotSettings) -> Vec<SourceSpec> {
|
||||
let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(installed) = root.get("installedPlugins").and_then(Value::as_array) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut seen_ids = HashSet::new();
|
||||
let mut specs = Vec::new();
|
||||
for entry in installed {
|
||||
let Some(obj) = entry.as_object() else { continue };
|
||||
if obj.get("enabled").and_then(Value::as_bool) == Some(false) {
|
||||
continue;
|
||||
}
|
||||
let Some(name) = obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
let marketplace = obj.get("marketplace").and_then(Value::as_str).map(str::trim).unwrap_or_default();
|
||||
if settings.disabled_plugins.contains(name)
|
||||
|| (!marketplace.is_empty()
|
||||
&& (settings.disabled_plugins.contains(&format!("{name}@{marketplace}"))
|
||||
|| settings.disabled_plugins.contains(&format!("{marketplace}/{name}"))))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(raw_cache) = obj.get("cache_path").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let plugin_root =
|
||||
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
||||
if !plugin_root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let Some((manifest_path, _)) = read_copilot_plugin_servers(&plugin_root) else {
|
||||
continue;
|
||||
};
|
||||
let base_id = if marketplace.is_empty() {
|
||||
format!("copilot-plugin:{name}")
|
||||
} else {
|
||||
format!("copilot-plugin:{marketplace}/{name}")
|
||||
};
|
||||
let mut id = base_id.clone();
|
||||
let mut suffix = 2usize;
|
||||
while !seen_ids.insert(id.clone()) {
|
||||
id = format!("{base_id}#{suffix}");
|
||||
suffix += 1;
|
||||
}
|
||||
let label = if marketplace.is_empty() {
|
||||
format!("GitHub Copilot Plugin ({name})")
|
||||
} else {
|
||||
format!("GitHub Copilot Plugin ({name} · {marketplace})")
|
||||
};
|
||||
specs.push(SourceSpec {
|
||||
id,
|
||||
label,
|
||||
path: manifest_path,
|
||||
format: SourceFormat::CopilotPlugin { root: plugin_root },
|
||||
suggested_scope: McpScope::User,
|
||||
native_provider: Some("copilot"),
|
||||
claude_project_lookup: false,
|
||||
disabled_servers: settings.disabled_mcp_servers.clone(),
|
||||
});
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
fn resolve_within_dir(base_dir: &Path, candidate: &Path) -> Option<PathBuf> {
|
||||
if candidate.as_os_str().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let base_canon = dunce::canonicalize(base_dir).ok()?;
|
||||
let clean = candidate.strip_prefix(".").unwrap_or(candidate);
|
||||
let joined = if clean.is_relative() { base_dir.join(clean) } else { clean.to_path_buf() };
|
||||
let meta = std::fs::metadata(&joined).ok()?;
|
||||
if !meta.is_file() {
|
||||
return None;
|
||||
}
|
||||
let target_canon = dunce::canonicalize(&joined).ok()?;
|
||||
target_canon.starts_with(&base_canon).then_some(joined)
|
||||
}
|
||||
|
||||
fn expand_plugin_root_vars(value: &str, root: &str) -> String {
|
||||
value.replace("${COPILOT_PLUGIN_ROOT}", root).replace("${CLAUDE_PLUGIN_ROOT}", root).replace("${PLUGIN_ROOT}", root)
|
||||
}
|
||||
|
||||
fn expand_plugin_servers(servers: &mut BTreeMap<String, AgentMcpServer>, plugin_root: &Path) {
|
||||
let root = plugin_root.to_string_lossy();
|
||||
for srv in servers.values_mut() {
|
||||
if let Some(cmd) = srv.command.as_mut() {
|
||||
*cmd = expand_plugin_root_vars(cmd, &root);
|
||||
}
|
||||
for arg in &mut srv.args {
|
||||
*arg = expand_plugin_root_vars(arg, &root);
|
||||
}
|
||||
if let Some(url) = srv.url.as_mut() {
|
||||
*url = expand_plugin_root_vars(url, &root);
|
||||
}
|
||||
for val in srv.env.values_mut() {
|
||||
*val = expand_plugin_root_vars(val, &root);
|
||||
}
|
||||
for val in srv.headers.values_mut() {
|
||||
*val = expand_plugin_root_vars(val, &root);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_plugin_manifest_servers(
|
||||
plugin_root: &Path,
|
||||
manifest_path: &Path,
|
||||
mcp_val: &Value,
|
||||
) -> (PathBuf, BTreeMap<String, AgentMcpServer>) {
|
||||
match mcp_val {
|
||||
Value::String(rel) => {
|
||||
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
|
||||
let map = read_external_file(&path);
|
||||
return (path, map);
|
||||
}
|
||||
(manifest_path.to_path_buf(), BTreeMap::new())
|
||||
}
|
||||
Value::Object(_) => {
|
||||
let wrapper = json!({ "mcpServers": mcp_val });
|
||||
(manifest_path.to_path_buf(), extract_servers_from_root(&wrapper, None))
|
||||
}
|
||||
Value::Array(items) => {
|
||||
let mut merged = BTreeMap::new();
|
||||
let mut first_path: Option<PathBuf> = None;
|
||||
for item in items {
|
||||
match item {
|
||||
Value::String(rel) => {
|
||||
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
|
||||
let map = read_external_file(&path);
|
||||
if !map.is_empty() && first_path.is_none() {
|
||||
first_path = Some(path);
|
||||
}
|
||||
merged.extend(map);
|
||||
}
|
||||
}
|
||||
Value::Object(_) => {
|
||||
let map = extract_servers_from_root(item, None);
|
||||
if !map.is_empty() && first_path.is_none() {
|
||||
first_path = Some(manifest_path.to_path_buf());
|
||||
}
|
||||
merged.extend(map);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(first_path.unwrap_or_else(|| manifest_path.to_path_buf()), merged)
|
||||
}
|
||||
_ => (manifest_path.to_path_buf(), BTreeMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_copilot_plugin_servers(plugin_root: &Path) -> Option<(PathBuf, BTreeMap<String, AgentMcpServer>)> {
|
||||
if let Some(dot_mcp) = resolve_within_dir(plugin_root, Path::new(".mcp.json")) {
|
||||
let mut servers = read_external_file(&dot_mcp);
|
||||
if !servers.is_empty() {
|
||||
expand_plugin_servers(&mut servers, plugin_root);
|
||||
return Some((dot_mcp, servers));
|
||||
}
|
||||
}
|
||||
for rel in COPILOT_PLUGIN_MANIFESTS {
|
||||
let Some(manifest_path) = resolve_within_dir(plugin_root, Path::new(rel)) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(text) = std::fs::read_to_string(&manifest_path) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(manifest) = parse_jsonc_value(&text) else {
|
||||
continue;
|
||||
};
|
||||
let Some(mcp_val) = manifest.get("mcpServers") else {
|
||||
continue;
|
||||
};
|
||||
let (source_path, mut servers) = extract_plugin_manifest_servers(plugin_root, &manifest_path, mcp_val);
|
||||
if !servers.is_empty() {
|
||||
expand_plugin_servers(&mut servers, plugin_root);
|
||||
return Some((source_path, servers));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
|
||||
let mut servers = match &spec.format {
|
||||
SourceFormat::CopilotPlugin { root } => {
|
||||
read_copilot_plugin_servers(root).map(|(_, map)| map).unwrap_or_default()
|
||||
}
|
||||
SourceFormat::CodexToml => {
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
parse_codex_toml_servers(&text)
|
||||
}
|
||||
SourceFormat::Jsonc => {
|
||||
let Ok(text) = std::fs::read_to_string(&spec.path) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let Ok(root) = parse_jsonc_value(&text) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut map = extract_servers_from_root(&root, None);
|
||||
if spec.claude_project_lookup
|
||||
&& let Some(ws) = workspace_root
|
||||
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
|
||||
{
|
||||
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
|
||||
for (proj_key, proj_val) in projects {
|
||||
let matches =
|
||||
Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
|
||||
if matches {
|
||||
for (name, srv) in extract_servers_from_root(proj_val, None) {
|
||||
map.insert(name, srv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
map
|
||||
}
|
||||
};
|
||||
for name in spec.disabled_servers.iter() {
|
||||
if let Some(srv) = servers.get_mut(name) {
|
||||
srv.enabled = false;
|
||||
}
|
||||
}
|
||||
servers
|
||||
@@ -612,8 +878,8 @@ pub fn discover_external_sources(home_dir: Option<&Path>, workspace_root: Option
|
||||
})
|
||||
.collect();
|
||||
out.push(McpExternalSource {
|
||||
id: spec.id.to_owned(),
|
||||
label: spec.label.to_owned(),
|
||||
id: spec.id,
|
||||
label: spec.label,
|
||||
path: IpcPath(spec.path),
|
||||
suggested_scope: spec.suggested_scope,
|
||||
native_provider: spec.native_provider.map(str::to_owned),
|
||||
@@ -641,7 +907,7 @@ pub fn apply_import_selected(
|
||||
let mut by_source: BTreeMap<&str, BTreeMap<String, AgentMcpServer>> = BTreeMap::new();
|
||||
for spec in &specs {
|
||||
if selections.iter().any(|s| s.source_id == spec.id) {
|
||||
by_source.insert(spec.id, read_source_servers(spec, workspace_root));
|
||||
by_source.insert(spec.id.as_str(), read_source_servers(spec, workspace_root));
|
||||
}
|
||||
}
|
||||
let target = match scope {
|
||||
@@ -1370,4 +1636,125 @@ mod tests {
|
||||
assert_eq!(workspace["events-sse"].transport, McpTransport::Sse);
|
||||
assert_eq!(workspace["events-sse"].url.as_deref(), Some("https://sse.example.com/events"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovers_and_imports_copilot_installed_plugin_mcp_servers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
let copilot = home.join(".copilot");
|
||||
let azure_root = copilot.join("installed-plugins/_direct/azure-skills");
|
||||
let inline_root = copilot.join("installed-plugins/awesome-copilot/inline-tools");
|
||||
let disabled_root = copilot.join("installed-plugins/_direct/disabled-plug");
|
||||
let outside_root = tmp.path().join("outside");
|
||||
|
||||
std::fs::create_dir_all(azure_root.join(".plugin")).unwrap();
|
||||
std::fs::create_dir_all(inline_root.join(".claude-plugin")).unwrap();
|
||||
std::fs::create_dir_all(&disabled_root).unwrap();
|
||||
std::fs::create_dir_all(&outside_root).unwrap();
|
||||
|
||||
std::fs::write(
|
||||
azure_root.join(".plugin/plugin.json"),
|
||||
r#"{"name":"azure","version":"1.2.106","mcpServers":"./.mcp.json"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
azure_root.join(".mcp.json"),
|
||||
r#"{"mcpServers":{"azure":{"command":"npx","args":["-y","@azure/mcp@latest","${COPILOT_PLUGIN_ROOT}/cfg"],"env":{"PLUG_DIR":"${CLAUDE_PLUGIN_ROOT}"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
inline_root.join(".claude-plugin/plugin.json"),
|
||||
r#"{"name":"inline-tools","version":"0.1.0","mcpServers":{"inline-srv":{"command":"${PLUGIN_ROOT}/bin/run","args":["--stdio"]},"muted-srv":{"command":"echo","args":["off"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(
|
||||
disabled_root.join(".mcp.json"),
|
||||
r#"{"mcpServers":{"never":{"command":"npx","args":["never"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
std::fs::write(outside_root.join("secret.json"), r#"{"mcpServers":{"escaped":{"command":"sh"}}}"#).unwrap();
|
||||
let escape_root = copilot.join("installed-plugins/_direct/escape-plug");
|
||||
std::fs::create_dir_all(escape_root.join(".plugin")).unwrap();
|
||||
std::fs::write(
|
||||
escape_root.join(".plugin/plugin.json"),
|
||||
r#"{"name":"escape-plug","mcpServers":"../../../../outside/secret.json"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// `~/.copilot/config.json` includes leading `//` comments in Copilot CLI.
|
||||
let config_json = format!(
|
||||
"// Managed automatically.\n{}",
|
||||
serde_json::json!({
|
||||
"installedPlugins": [
|
||||
{
|
||||
"name": "azure",
|
||||
"marketplace": "",
|
||||
"enabled": true,
|
||||
"cache_path": azure_root,
|
||||
},
|
||||
{
|
||||
"name": "inline-tools",
|
||||
"marketplace": "awesome-copilot",
|
||||
"enabled": true,
|
||||
"cache_path": inline_root,
|
||||
},
|
||||
{
|
||||
"name": "disabled-plug",
|
||||
"marketplace": "",
|
||||
"enabled": false,
|
||||
"cache_path": disabled_root,
|
||||
},
|
||||
{
|
||||
"name": "escape-plug",
|
||||
"marketplace": "",
|
||||
"enabled": true,
|
||||
"cache_path": escape_root,
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
std::fs::write(copilot.join("config.json"), config_json).unwrap();
|
||||
std::fs::write(copilot.join("settings.json"), r#"{"disabledMcpServers":["muted-srv"]}"#).unwrap();
|
||||
|
||||
let sources = discover_external_sources(Some(&home), None);
|
||||
assert_eq!(sources.len(), 2);
|
||||
|
||||
let azure_src = sources.iter().find(|s| s.id == "copilot-plugin:azure").unwrap();
|
||||
assert_eq!(azure_src.label, "GitHub Copilot Plugin (azure)");
|
||||
assert_eq!(azure_src.native_provider.as_deref(), Some("copilot"));
|
||||
assert_eq!(azure_src.path.0, azure_root.join(".mcp.json"));
|
||||
assert_eq!(azure_src.servers.len(), 1);
|
||||
assert!(azure_src.servers[0].enabled);
|
||||
assert_eq!(
|
||||
azure_src.servers[0].args,
|
||||
vec!["-y", "@azure/mcp@latest", &format!("{}/cfg", azure_root.display())]
|
||||
);
|
||||
|
||||
let inline_src = sources.iter().find(|s| s.id == "copilot-plugin:awesome-copilot/inline-tools").unwrap();
|
||||
assert_eq!(inline_src.label, "GitHub Copilot Plugin (inline-tools · awesome-copilot)");
|
||||
assert_eq!(inline_src.path.0, inline_root.join(".claude-plugin/plugin.json"));
|
||||
let active = inline_src.servers.iter().find(|s| s.name == "inline-srv").unwrap();
|
||||
assert!(active.enabled);
|
||||
assert_eq!(active.command.as_deref(), Some(format!("{}/bin/run", inline_root.display()).as_str()));
|
||||
let muted = inline_src.servers.iter().find(|s| s.name == "muted-srv").unwrap();
|
||||
assert!(!muted.enabled);
|
||||
|
||||
let mut user = BTreeMap::new();
|
||||
let mut workspace = BTreeMap::new();
|
||||
let imported = apply_import_selected(
|
||||
&mut user,
|
||||
&mut workspace,
|
||||
Some(&home),
|
||||
None,
|
||||
McpScope::User,
|
||||
&[McpImportSelection { source_id: "copilot-plugin:azure".into(), name: "azure".into() }],
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(imported, vec!["azure".to_string()]);
|
||||
assert_eq!(user["azure"].env.get("PLUG_DIR").map(String::as_str), Some(azure_root.to_str().unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -672,6 +672,8 @@ pub enum AgentChangesView {
|
||||
SinceStart,
|
||||
/// The uncommitted files against `HEAD`; commits made since the start stay.
|
||||
Group,
|
||||
/// What the last turn changed, against the checkout as that turn started.
|
||||
LastTurn,
|
||||
}
|
||||
|
||||
/// A task's uncommitted files and the commits made since it started.
|
||||
|
||||
@@ -2852,7 +2852,10 @@ async fn task_project_root_controls_local_and_worktree_repositories() {
|
||||
let changes = mgr.changes(&task.id).await.unwrap();
|
||||
assert_eq!(changes.len(), 1);
|
||||
assert_eq!(changes[0].path.0, task.cwd.0.join("file.txt"));
|
||||
assert_eq!(mgr.base_text(&task.id, changes[0].path.0.clone()).await.unwrap().as_deref(), Some("original\n"));
|
||||
assert_eq!(
|
||||
mgr.base_text(&task.id, changes[0].path.0.clone(), AgentChangesView::SinceStart).await.unwrap().as_deref(),
|
||||
Some("original\n")
|
||||
);
|
||||
let saved = std::fs::read(root.join("store").join(format!("{}.json", task.id))).unwrap();
|
||||
assert!(String::from_utf8(saved).unwrap().contains("projectRoot"));
|
||||
let mut old = serde_json::to_value(&task).unwrap();
|
||||
@@ -3636,6 +3639,178 @@ async fn changed(mgr: &AgentManager, id: &str) -> Vec<String> {
|
||||
mgr.changes(id).await.unwrap().into_iter().map(|c| c.rel_path).collect()
|
||||
}
|
||||
|
||||
/// Waits until the turn asks for permission, runs `work` (what the agent does), then stops it.
|
||||
async fn one_turn(mgr: &AgentManager, id: &str, prompt: Option<&str>, work: impl FnOnce()) {
|
||||
if let Some(prompt) = prompt {
|
||||
mgr.prompt(id, text(prompt), false).await.unwrap();
|
||||
}
|
||||
wait_for(mgr, id, AgentStatus::NeedsInput).await;
|
||||
work();
|
||||
mgr.cancel(id, None).unwrap();
|
||||
wait_for(mgr, id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
async fn turn_changed(mgr: &AgentManager, id: &str) -> Vec<(String, ide_vcs::ChangeKind, u32, u32)> {
|
||||
let changes = mgr.turn_changes(id).await.unwrap();
|
||||
changes.into_iter().map(|c| (c.rel_path, c.kind, c.added, c.removed)).collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
|
||||
use ide_vcs::ChangeKind::{Added, Deleted, Modified};
|
||||
for isolation in [Isolation::Local, Isolation::Worktree] {
|
||||
for eol in EOLS {
|
||||
let repo = Checkout::new(eol);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.write("gone.txt", "base\n");
|
||||
repo.write("mine.txt", "base\n");
|
||||
repo.commit("init");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let cwd = task.cwd.0.clone();
|
||||
let write = |rel: &str, text: &str| {
|
||||
let text = match eol {
|
||||
Eol::Lf => text.to_owned(),
|
||||
Eol::Crlf => text.replace('\n', "\r\n"),
|
||||
};
|
||||
std::fs::write(cwd.join(rel), text).unwrap();
|
||||
};
|
||||
let read = |rel: &str| std::fs::read_to_string(cwd.join(rel)).unwrap().replace("\r\n", "\n");
|
||||
let case = format!("{isolation:?} {eol:?}");
|
||||
assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty(), "{case}: no turn has ended yet");
|
||||
|
||||
one_turn(&mgr, &task.id, None, || {
|
||||
write("a.txt", "base\nturn 1\n");
|
||||
write("one.txt", "one\n");
|
||||
})
|
||||
.await;
|
||||
// The user's own work between the turns belongs to neither.
|
||||
write("mine.txt", "base\nmine\n");
|
||||
one_turn(&mgr, &task.id, Some("more"), || {
|
||||
write("a.txt", "base\nturn 1\nturn 2\n");
|
||||
write("one.txt", "one\ntwo\n");
|
||||
write("two.txt", "two\n");
|
||||
std::fs::remove_file(cwd.join("gone.txt")).unwrap();
|
||||
})
|
||||
.await;
|
||||
// And after the turn.
|
||||
write("later.txt", "mine\n");
|
||||
|
||||
assert_eq!(
|
||||
turn_changed(&mgr, &task.id).await,
|
||||
[
|
||||
("a.txt".into(), Modified, 1, 0),
|
||||
("gone.txt".into(), Deleted, 0, 1),
|
||||
("one.txt".into(), Modified, 1, 0),
|
||||
("two.txt".into(), Added, 1, 0),
|
||||
],
|
||||
"{case}"
|
||||
);
|
||||
let turn_base = |rel: &str| {
|
||||
let path = cwd.join(rel);
|
||||
let mgr = &mgr;
|
||||
let id = task.id.clone();
|
||||
async move {
|
||||
let text = mgr.base_text(&id, path, AgentChangesView::LastTurn).await.unwrap();
|
||||
text.map(|t| t.replace("\r\n", "\n"))
|
||||
}
|
||||
};
|
||||
assert_eq!(turn_base("a.txt").await.as_deref(), Some("base\nturn 1\n"), "{case}");
|
||||
assert_eq!(turn_base("gone.txt").await.as_deref(), Some("base\n"), "{case}");
|
||||
assert_eq!(turn_base("two.txt").await, None, "{case}");
|
||||
let whole: Vec<String> = changed(&mgr, &task.id).await;
|
||||
assert!(["a.txt", "one.txt"].iter().all(|f| whole.iter().any(|w| w == f)), "{case}: {whole:?}");
|
||||
|
||||
// One file, then the rest, after a restart: from the copies saved as the turn started.
|
||||
mgr.rollback_changes(&task.id, Some(vec!["one.txt".into()]), AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(read("one.txt"), "one\n", "{case}");
|
||||
assert_eq!(turn_changed(&mgr, &task.id).await.len(), 3, "{case}");
|
||||
mgr.shutdown();
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(read("a.txt"), "base\nturn 1\n", "{case}");
|
||||
assert_eq!(read("gone.txt"), "base\n", "{case}");
|
||||
assert!(!cwd.join("two.txt").exists(), "{case}");
|
||||
assert_eq!(read("mine.txt"), "base\nmine\n", "{case}: the user's edit between turns stays");
|
||||
assert_eq!(read("later.txt"), "mine\n", "{case}: and the one after");
|
||||
assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty(), "{case}");
|
||||
// The task's own changes from its first turn stay.
|
||||
let whole: Vec<String> = changed(&mgr, &task.id).await;
|
||||
assert!(["a.txt", "one.txt"].iter().all(|f| whole.iter().any(|w| w == f)), "{case}: {whole:?}");
|
||||
|
||||
mgr.delete(&task.id, true).await.unwrap();
|
||||
assert!(!repo.dir.join("store").join(format!("{}.turn", task.id)).exists(), "{case}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rolling_back_the_whole_task_leaves_the_last_turn_nothing_to_list() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.commit("init");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || repo.write("a.txt", "base\nturn 1\n")).await;
|
||||
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
|
||||
assert_eq!(turn_changed(&mgr, &task.id).await.len(), 1);
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert_eq!(repo.read("a.txt"), "base\n");
|
||||
assert!(mgr.turn_changes(&task.id).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_commit_made_in_the_last_turn_is_among_its_changes() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.commit("init");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Worktree,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let cwd = task.cwd.0.clone();
|
||||
let git = |args: &[&str]| {
|
||||
let ok = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(&cwd)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(ok, "{args:?}");
|
||||
};
|
||||
one_turn(&mgr, &task.id, None, || {
|
||||
std::fs::write(cwd.join("a.txt"), "base\nagent\n").unwrap();
|
||||
std::fs::write(cwd.join("new.txt"), "new\n").unwrap();
|
||||
git(&["add", "."]);
|
||||
git(&["commit", "-q", "-m", "agent"]);
|
||||
})
|
||||
.await;
|
||||
let rel: Vec<String> = mgr.turn_changes(&task.id).await.unwrap().into_iter().map(|c| c.rel_path).collect();
|
||||
assert_eq!(rel, ["a.txt", "new.txt"]);
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(cwd.join("a.txt")).unwrap(), "base\n");
|
||||
assert!(!cwd.join("new.txt").exists());
|
||||
mgr.delete(&task.id, true).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn work_uncommitted_by_a_reset_during_a_local_task_is_not_rolled_back() {
|
||||
for eol in EOLS {
|
||||
@@ -3652,7 +3827,7 @@ async fn work_uncommitted_by_a_reset_during_a_local_task_is_not_rolled_back() {
|
||||
repo.git(&["reset", "-q", "--soft", "HEAD~1"]);
|
||||
assert_eq!(changed(&mgr, &task.id).await, ["a.txt"], "{eol:?}");
|
||||
|
||||
let base = mgr.base_text(&task.id, repo.dir.join("a.txt")).await.unwrap();
|
||||
let base = mgr.base_text(&task.id, repo.dir.join("a.txt"), AgentChangesView::SinceStart).await.unwrap();
|
||||
assert_eq!(base.map(|b| b.replace("\r\n", "\n")).as_deref(), Some("base\n"), "{eol:?}");
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert_eq!(repo.read("a.txt"), "base\n", "{eol:?}");
|
||||
@@ -3792,7 +3967,11 @@ async fn a_local_task_in_a_repository_without_commits_lists_and_rolls_back_its_c
|
||||
let (mgr, task) = repo.task().await;
|
||||
repo.write("new.txt", "agent\n");
|
||||
assert_eq!(changed(&mgr, &task.id).await, ["new.txt"], "{eol:?}");
|
||||
assert_eq!(mgr.base_text(&task.id, repo.dir.join("new.txt")).await.unwrap(), None, "{eol:?}");
|
||||
assert_eq!(
|
||||
mgr.base_text(&task.id, repo.dir.join("new.txt"), AgentChangesView::SinceStart).await.unwrap(),
|
||||
None,
|
||||
"{eol:?}"
|
||||
);
|
||||
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert!(!repo.dir.join("new.txt").exists(), "{eol:?}");
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use crate::model::{AgentChange, AgentChanges, AgentCommit};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_vcs::{ChangeKind, LogQuery, Repo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
@@ -610,7 +611,6 @@ pub(crate) fn restore(
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<()> {
|
||||
let path = &change.path.0;
|
||||
let content = match before.get(&change.rel_path) {
|
||||
Some(None) => None,
|
||||
Some(Some(_)) => {
|
||||
@@ -626,11 +626,16 @@ pub(crate) fn restore(
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(path, Some(rev))?
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))?
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
put(&change.path.0, content)
|
||||
}
|
||||
|
||||
/// Writes `content` to `path`, or removes the file when there is none.
|
||||
fn put(path: &Path, content: Option<Vec<u8>>) -> IdeResult<()> {
|
||||
match content {
|
||||
Some(bytes) => {
|
||||
if let Some(parent) = path.parent() {
|
||||
@@ -646,6 +651,187 @@ pub(crate) fn restore(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The bytes of the copy of `rel` saved in `dir`, if there is one.
|
||||
pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(dir.join(saved_name(rel))).ok()
|
||||
}
|
||||
|
||||
/// The checkout as the task's last turn started: what that turn's changes are compared with
|
||||
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
|
||||
/// and copies of those.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct TurnStart {
|
||||
/// `HEAD` then (`None` outside a repository or before its first commit).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub head: Option<String>,
|
||||
/// The files already changed then, stamped.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub before: BTreeMap<String, Stamp>,
|
||||
/// The files among `before` with a copy in the task's turn folder.
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub saved: BTreeSet<String>,
|
||||
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub changed: Option<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
|
||||
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
|
||||
/// starting a turn copies little more than what the turn before it changed.
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let head = repo.head()?.1;
|
||||
// As the turn's end is read, so the two compare.
|
||||
let before = snapshot(cwd)?;
|
||||
let mut saved = BTreeSet::new();
|
||||
match previous {
|
||||
Some(previous) => {
|
||||
for rel in &previous.saved {
|
||||
let unchanged =
|
||||
before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
|
||||
if unchanged {
|
||||
saved.insert(rel.clone());
|
||||
} else {
|
||||
let _ = std::fs::remove_file(dir.join(saved_name(rel)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
for (rel, stamp) in &before {
|
||||
let path = repo.root().join(rel);
|
||||
if stamp.is_none()
|
||||
|| saved.contains(rel)
|
||||
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
// One that can't be copied is listed but can't be rolled back, as a large one.
|
||||
if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
|
||||
saved.insert(rel.clone());
|
||||
}
|
||||
}
|
||||
Ok(TurnStart { head, before, saved, changed: None })
|
||||
}
|
||||
|
||||
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
|
||||
/// `changed_between` sees them), and in the commits made since.
|
||||
pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<String>, BTreeSet<String>)> {
|
||||
let end = snapshot(cwd)?;
|
||||
let worktree = changed_between(&start.before, &end);
|
||||
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
|
||||
if let Some(repo) = discover(cwd)?
|
||||
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
|
||||
&& *from != to
|
||||
{
|
||||
for f in repo.diff_revisions(from, &to)? {
|
||||
all.extend(f.old_path);
|
||||
all.insert(f.path);
|
||||
}
|
||||
}
|
||||
Ok((worktree, all))
|
||||
}
|
||||
|
||||
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
|
||||
fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
match start.before.get(rel) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
|
||||
Some(bytes) => Ok(Some(bytes)),
|
||||
None => Err(IdeError::invalid(format!(
|
||||
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
|
||||
))),
|
||||
},
|
||||
None => match &start.head {
|
||||
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
|
||||
None => Ok(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Added and removed lines from `old` to `new`; none for binary content.
|
||||
fn line_stats(old: Option<&[u8]>, new: Option<&[u8]>) -> (u32, u32) {
|
||||
if [old, new].iter().flatten().any(|b| b.contains(&0)) {
|
||||
return (0, 0);
|
||||
}
|
||||
let text = |b: Option<&[u8]>| b.map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default();
|
||||
ide_vcs::diff_hunks(&text(old), &text(new))
|
||||
.iter()
|
||||
.fold((0, 0), |(added, removed), h| (added + h.lines, removed + h.old_lines))
|
||||
}
|
||||
|
||||
/// The files among `changed` that differ from how they were as the turn `start` began.
|
||||
pub(crate) fn turn_changes(
|
||||
cwd: &Path,
|
||||
start: &TurnStart,
|
||||
dir: &Path,
|
||||
changed: &BTreeSet<String>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
for rel in changed {
|
||||
let path = repo.root().join(rel);
|
||||
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
|
||||
let Some(now) = existing(&path) else { continue };
|
||||
let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) {
|
||||
Ok(then) if then == now => continue,
|
||||
Ok(then) => {
|
||||
let kind = match (&then, &now) {
|
||||
(None, _) => ChangeKind::Added,
|
||||
(_, None) => ChangeKind::Deleted,
|
||||
_ => ChangeKind::Modified,
|
||||
};
|
||||
(kind, line_stats(then.as_deref(), now.as_deref()))
|
||||
}
|
||||
// Its start wasn't saved: listed, without counts.
|
||||
Err(_) => (ChangeKind::Modified, (0, 0)),
|
||||
};
|
||||
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The text of `path` as the turn `start` began, `None` when there was no file.
|
||||
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(repo.root(), path)?;
|
||||
if let (None, Some(head)) = (start.before.get(&rel), &start.head) {
|
||||
return file_at(cwd, path, head);
|
||||
}
|
||||
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&bytes, None),
|
||||
};
|
||||
Ok(Some(encoding.decode(&bytes).0.into_owned()))
|
||||
}
|
||||
|
||||
/// `path` relative to the repository at `root`, with `/` separators.
|
||||
fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
|
||||
let rel = path
|
||||
.strip_prefix(root)
|
||||
.map(Path::to_path_buf)
|
||||
.ok()
|
||||
.or_else(|| {
|
||||
// Another spelling of the same place (a link, `/var` and `/private/var`); the file may be gone.
|
||||
let root = dunce::canonicalize(root).ok()?;
|
||||
let parent = dunce::canonicalize(path.parent()?).ok()?;
|
||||
Some(parent.strip_prefix(&root).ok()?.join(path.file_name()?))
|
||||
})
|
||||
.ok_or_else(|| IdeError::invalid(format!("{} is outside the repository", path.display())))?;
|
||||
Ok(rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/"))
|
||||
}
|
||||
|
||||
/// Puts `change` back as it was when the turn `start` began.
|
||||
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
|
||||
let repo = repo_at(cwd)?;
|
||||
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
@@ -815,6 +1001,67 @@ mod tests {
|
||||
assert!(!created.path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turn_copies_only_what_changed_since_the_last_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "base\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
let dir = tmp.path().join("turn");
|
||||
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::<BTreeSet<_>>();
|
||||
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
|
||||
let first = start_turn(&repo, &dir, None).unwrap();
|
||||
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
|
||||
// A copy made again would replace this mark.
|
||||
std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
|
||||
let second = start_turn(&repo, &dir, Some(&first)).unwrap();
|
||||
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
|
||||
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
|
||||
// Back as committed: nothing to keep a copy of.
|
||||
git(&repo, &["checkout", "--", "a.txt"]);
|
||||
let third = start_turn(&repo, &dir, Some(&second)).unwrap();
|
||||
assert_eq!(third.saved, set(&["b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "a.txt"), None);
|
||||
// Without a record of the last turn (a task from before), every copy is made afresh.
|
||||
let fresh = start_turn(&repo, &dir, None).unwrap();
|
||||
assert_eq!(fresh.saved, set(&["b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_turns_start_is_found_through_another_spelling_of_the_checkout() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = dunce::canonicalize(tmp.path()).unwrap().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "base\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
let dir = tmp.path().join("turn");
|
||||
let start = start_turn(&repo, &dir, None).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
|
||||
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
|
||||
let link = tmp.path().join("link");
|
||||
std::os::unix::fs::symlink(&repo, &link).unwrap();
|
||||
for at in [&repo, &link] {
|
||||
assert_eq!(turn_text(&repo, &at.join("a.txt"), &start, &dir).unwrap().as_deref(), Some("turn 1\n"));
|
||||
assert_eq!(turn_text(&repo, &at.join("new.txt"), &start, &dir).unwrap(), None);
|
||||
}
|
||||
assert!(turn_text(&repo, &tmp.path().join("elsewhere.txt"), &start, &dir).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commits_since_the_base_are_listed_with_their_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -536,7 +536,9 @@ impl PathMap {
|
||||
let abs = if p.is_absolute() {
|
||||
p.to_path_buf()
|
||||
} else {
|
||||
let in_base = base.map(|b| Path::new(b).join(p)).filter(|c| c.exists());
|
||||
// rustc prints workspace members' files relative to the workspace root, above
|
||||
// the member's manifest directory (`base`) when a member is built on its own.
|
||||
let in_base = base.and_then(|b| Path::new(b).ancestors().map(|a| a.join(p)).find(|c| c.exists()));
|
||||
in_base.unwrap_or_else(|| cwd.join(p))
|
||||
};
|
||||
let abs = normalize(&abs);
|
||||
@@ -1303,6 +1305,22 @@ mod tests {
|
||||
assert_eq!(identifier_len("x é_1 c", 2), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_a_member_build_s_workspace_relative_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
write(&root, "client/src/main.rs", "fn main() {}\n");
|
||||
write(&root, "client/src/lib.rs", "\n");
|
||||
write(&root, "src/lib.rs", "\n");
|
||||
let map = PathMap { root: root.clone(), canonical: None };
|
||||
let member = root.join("client");
|
||||
let base = member.to_str();
|
||||
// Build Module runs in the member; rustc names its files from the workspace root.
|
||||
assert_eq!(map.resolve("client/src/main.rs", &member, base), root.join("client/src/main.rs"));
|
||||
// A crate built from its own directory names them from there.
|
||||
assert_eq!(map.resolve("src/lib.rs", &member, base), member.join("src/lib.rs"));
|
||||
}
|
||||
|
||||
// Uses Unix absolute paths for the canonical root.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
|
||||
@@ -1875,6 +1875,14 @@ pub fn goto_declaration(text: &str, path: &Path, pos: Pos, local_repo: Option<Pa
|
||||
goto_declaration_in(text, path, pos, local_repo, Vec::new)
|
||||
}
|
||||
|
||||
/// The declaration of the property `name` in the pom at `path`, for files it configures
|
||||
/// outside the pom itself (a YAML resource's `@name@`): the first `<properties>` entry
|
||||
/// along the parent chain declaring it, `project.*` built-ins included.
|
||||
pub fn property_declaration(pom: &Path, name: &str, local_repo: Option<PathBuf>) -> Option<PomGoto> {
|
||||
let text = xml::read_text(pom)?;
|
||||
property_target(&text, pom, name, local_repo)
|
||||
}
|
||||
|
||||
/// [`goto_declaration`], where a `<parent>` and a dependency or plugin whose version no
|
||||
/// management entry provides (or a management entry itself) go to the artifact's own
|
||||
/// POM: the project module among `modules` with its coordinates, else the local
|
||||
|
||||
@@ -446,6 +446,12 @@ pub struct LanguageCodeStyle {
|
||||
/// Comment Code › Add a space at line comment start.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub line_comment_add_space: Option<bool>,
|
||||
/// PHP: align `=>` in multi-line arrays after formatting (other languages ignore it).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub align_key_value_pairs: Option<bool>,
|
||||
/// PHP: align `=` of consecutive assignment statements after formatting.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub align_consecutive_assignments: Option<bool>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
|
||||
@@ -1062,11 +1062,13 @@ mod tests {
|
||||
#[test]
|
||||
fn a_child_inside_a_project_gets_its_environment() {
|
||||
let root = std::path::Path::new("/openidea-test-process/project");
|
||||
// Absolute on the platform: the search path drops relative entries.
|
||||
let devshell = if cfg!(windows) { r"C:\nix\store\x-devshell\bin" } else { "/nix/store/x-devshell/bin" };
|
||||
crate::project_env::set(
|
||||
root,
|
||||
vec![
|
||||
("OPENIDEA_PROJECT_VAR".into(), Some("devshell".into())),
|
||||
("PATH".into(), Some("/nix/store/x-devshell/bin".into())),
|
||||
("PATH".into(), Some(devshell.into())),
|
||||
("OPENIDEA_PROJECT_UNSET".into(), None),
|
||||
],
|
||||
);
|
||||
@@ -1075,7 +1077,7 @@ mod tests {
|
||||
let mut inside = Command::new("true");
|
||||
inside.current_dir(root.join("src")).env("OPENIDEA_PROJECT_VAR", "call site");
|
||||
host_env(&mut inside);
|
||||
assert_eq!(get(&inside, "PATH"), Some(Some("/nix/store/x-devshell/bin".into())));
|
||||
assert_eq!(get(&inside, "PATH"), Some(Some(devshell.into())));
|
||||
assert_eq!(get(&inside, "OPENIDEA_PROJECT_UNSET"), Some(None));
|
||||
assert_eq!(get(&inside, "OPENIDEA_PROJECT_VAR"), Some(Some("call site".into())), "the call site's value wins");
|
||||
|
||||
@@ -1093,7 +1095,7 @@ mod tests {
|
||||
assert_eq!(host_var_os_in(root, "OPENIDEA_PROJECT_VAR"), Some("devshell".into()));
|
||||
assert_eq!(host_var_os("OPENIDEA_PROJECT_VAR"), None);
|
||||
let search = crate::tool_path::search_path_in(root);
|
||||
assert_eq!(std::env::split_paths(&search).next(), Some("/nix/store/x-devshell/bin".into()));
|
||||
assert_eq!(std::env::split_paths(&search).next(), Some(devshell.into()));
|
||||
crate::project_env::remove(root);
|
||||
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
|
||||
}
|
||||
|
||||
@@ -1504,6 +1504,10 @@ pub struct MavenSettings {
|
||||
pub active_profiles: String,
|
||||
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
|
||||
pub delegate_build: bool,
|
||||
/// Download `-sources.jar` of dependencies when the Java language server imports the
|
||||
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
|
||||
/// from a library class's Download Sources banner.
|
||||
pub download_sources: bool,
|
||||
}
|
||||
|
||||
impl MavenSettings {
|
||||
|
||||
@@ -912,7 +912,7 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
|
||||
|
||||
/// A `runInTerminal` program and the pseudo-terminal it runs in.
|
||||
pub(crate) struct ProgramTerminal {
|
||||
writer: ide_core::input::InputWriter,
|
||||
writer: Arc<ide_core::input::InputWriter>,
|
||||
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
|
||||
#[cfg_attr(not(unix), allow(dead_code))]
|
||||
pid: Option<u32>,
|
||||
@@ -1025,10 +1025,12 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
|
||||
let _ = child.wait();
|
||||
})
|
||||
.map_err(|e| format!("terminal input worker: {e}"))?;
|
||||
let writer = Arc::new(writer);
|
||||
let pid = child.process_id();
|
||||
forward_terminal_output(
|
||||
s,
|
||||
reader,
|
||||
writer.clone(),
|
||||
#[cfg(unix)]
|
||||
wait_readable,
|
||||
);
|
||||
@@ -1043,10 +1045,35 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
|
||||
Ok(json!({ "processId": pid }))
|
||||
}
|
||||
|
||||
/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept).
|
||||
/// A terminal's cursor position query (DSR). ConPTY sends one when it starts and runs the program
|
||||
/// only once the terminal answers; programs that lay out a prompt ask it too.
|
||||
const CURSOR_QUERY: &[u8] = b"\x1b[6n";
|
||||
|
||||
/// `chunk` without its cursor position queries, and how many there were.
|
||||
pub(crate) fn take_cursor_queries(chunk: &[u8]) -> (Vec<u8>, usize) {
|
||||
let mut out = Vec::with_capacity(chunk.len());
|
||||
let mut queries = 0;
|
||||
let mut rest = chunk;
|
||||
while let Some(at) = rest.windows(CURSOR_QUERY.len()).position(|w| w == CURSOR_QUERY) {
|
||||
out.extend_from_slice(&rest[..at]);
|
||||
rest = &rest[at + CURSOR_QUERY.len()..];
|
||||
queries += 1;
|
||||
}
|
||||
out.extend_from_slice(rest);
|
||||
(out, queries)
|
||||
}
|
||||
|
||||
/// Length of the end of `pending` that may begin a cursor position query the next read completes.
|
||||
pub(crate) fn partial_cursor_query(pending: &[u8]) -> usize {
|
||||
(1..CURSOR_QUERY.len()).rev().find(|&n| pending.ends_with(&CURSOR_QUERY[..n])).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept). The debug
|
||||
/// console is no terminal, so cursor position queries are answered here (top-left corner).
|
||||
fn forward_terminal_output(
|
||||
s: &Session,
|
||||
mut reader: Box<dyn std::io::Read + Send>,
|
||||
answer: Arc<ide_core::input::InputWriter>,
|
||||
#[cfg(unix)] mut wait_readable: impl FnMut() -> std::io::Result<()> + Send + 'static,
|
||||
) {
|
||||
let session = s.id;
|
||||
@@ -1078,11 +1105,20 @@ fn forward_terminal_output(
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Keep incomplete UTF-8 sequences, and a `\r` that may start a `\r\n`, for the next chunk.
|
||||
let mut valid = match std::str::from_utf8(&pending) {
|
||||
Ok(_) => pending.len(),
|
||||
let (rest, queries) = take_cursor_queries(&pending);
|
||||
pending = rest;
|
||||
for _ in 0..queries {
|
||||
if let Err(e) = answer.write(b"\x1b[1;1R") {
|
||||
tracing::warn!(%session, "debug terminal cursor position: {e}");
|
||||
}
|
||||
}
|
||||
// Keep incomplete UTF-8 sequences, a `\r` that may start a `\r\n`, and the start of
|
||||
// a cursor position query for the next chunk.
|
||||
let keep = partial_cursor_query(&pending);
|
||||
let mut valid = match std::str::from_utf8(&pending[..pending.len() - keep]) {
|
||||
Ok(_) => pending.len() - keep,
|
||||
Err(e) if e.error_len().is_none() => e.valid_up_to(),
|
||||
Err(_) => pending.len(),
|
||||
Err(_) => pending.len() - keep,
|
||||
};
|
||||
if valid > 0 && pending[valid - 1] == b'\r' {
|
||||
valid -= 1;
|
||||
|
||||
@@ -1010,6 +1010,44 @@ async fn run_in_terminal_spawns_debuggee() {
|
||||
assert!(response["body"]["processId"].as_u64().unwrap() > 0);
|
||||
}
|
||||
|
||||
/// The debug console answers a terminal's cursor position query: ConPTY asks one before it runs
|
||||
/// the program at all (Windows debuggees never started), and programs that lay out a prompt ask too.
|
||||
#[tokio::test]
|
||||
async fn run_in_terminal_answers_cursor_position_queries() {
|
||||
#[cfg(unix)]
|
||||
let program = vec![
|
||||
"sh".into(),
|
||||
"-c".into(),
|
||||
r"stty -echo -icanon min 6; printf '\033[6n'; reply=$(dd bs=6 count=1 2>/dev/null); stty sane; case $reply in *'[1;1R') echo answered;; esac".into(),
|
||||
];
|
||||
#[cfg(windows)]
|
||||
let program = vec!["cmd".into(), "/c".into(), "echo answered".into()];
|
||||
let h = harness(Script { run_in_terminal: Some(program), ..Script::default() });
|
||||
h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Output { output, .. } if output.contains("answered"))).await;
|
||||
let output: String = h
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Debug { event: DebugEvent::Output { output, .. }, .. } => Some(output.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(!output.contains("\x1b[6n"), "{output:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_position_queries_are_taken_out_of_the_output() {
|
||||
use crate::session::{partial_cursor_query, take_cursor_queries};
|
||||
assert_eq!(take_cursor_queries(b"a\x1b[6nb\x1b[6n"), (b"ab".to_vec(), 2));
|
||||
assert_eq!(take_cursor_queries(b"\x1b[0mtext"), (b"\x1b[0mtext".to_vec(), 0));
|
||||
assert_eq!(partial_cursor_query(b"text\x1b["), 2);
|
||||
assert_eq!(partial_cursor_query(b"text\x1b[6"), 3);
|
||||
assert_eq!(partial_cursor_query(b"text\x1b[0m"), 0);
|
||||
assert_eq!(partial_cursor_query(b"text"), 0);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn run_in_terminal_program_reads_typed_input() {
|
||||
|
||||
+117
-11
@@ -19,10 +19,16 @@ struct State {
|
||||
settings: Vec<(String, String)>,
|
||||
read_only: bool,
|
||||
session_id: String,
|
||||
session: Mutex<bool>,
|
||||
session: Mutex<Session>,
|
||||
closed: CancellationToken,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Session {
|
||||
initialized: bool,
|
||||
strict_read_only: bool,
|
||||
}
|
||||
|
||||
/// The response format: a names line, a types line, then one JSON array per row, so rows past
|
||||
/// the grid's limit are skipped without being parsed.
|
||||
const FORMAT: &str = "JSONCompactEachRowWithNamesAndTypes";
|
||||
@@ -109,12 +115,23 @@ impl ClickhousePool {
|
||||
settings: setup.params,
|
||||
read_only: source.read_only,
|
||||
session_id: uuid::Uuid::new_v4().to_string(),
|
||||
session: Mutex::new(false),
|
||||
session: Mutex::new(Session::default()),
|
||||
closed: CancellationToken::new(),
|
||||
}));
|
||||
let cancel = CancellationToken::new();
|
||||
let initialize = async {
|
||||
pool.execute("SELECT 1", 1, &cancel).await?;
|
||||
if let Err(error) = pool.execute("SELECT 1", 1, &cancel).await {
|
||||
if !rejects_driver_setting(&error) {
|
||||
return Err(error);
|
||||
}
|
||||
// Retry only the connection probe. Keep relying on the server for write protection
|
||||
// only after verifying strict read-only mode in this same session.
|
||||
pool.0.session.lock().await.strict_read_only = true;
|
||||
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
|
||||
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
for sql in setup.statements {
|
||||
pool.execute(&sql, 0, &cancel).await?;
|
||||
}
|
||||
@@ -151,7 +168,7 @@ impl ClickhousePool {
|
||||
}
|
||||
|
||||
/// `max_rows`: the rows the server may send (the skipped ones included).
|
||||
fn request(&self, client: &Client, query_id: &str, max_rows: usize, initialized: bool) -> RequestBuilder {
|
||||
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
|
||||
let mut request = client
|
||||
.post(self.0.endpoint.clone())
|
||||
.basic_auth(&self.0.user, Some(&self.0.password))
|
||||
@@ -162,16 +179,20 @@ impl ClickhousePool {
|
||||
("session_timeout", "3600".into()),
|
||||
("query_id", query_id.to_owned()),
|
||||
("default_format", FORMAT.into()),
|
||||
]);
|
||||
if !session.strict_read_only {
|
||||
request = request.query(&[
|
||||
("output_format_json_quote_denormals", "1".into()),
|
||||
("max_result_rows", max_rows.saturating_add(1).to_string()),
|
||||
("result_overflow_mode", "break".into()),
|
||||
]);
|
||||
if initialized {
|
||||
}
|
||||
if session.initialized {
|
||||
request = request.query(&[("session_check", "1")]);
|
||||
} else {
|
||||
request = request.query(&[("database", &self.0.database)]);
|
||||
}
|
||||
if self.0.read_only {
|
||||
if self.0.read_only && !session.strict_read_only {
|
||||
request = request.query(&[("readonly", "1")]);
|
||||
}
|
||||
request
|
||||
@@ -200,7 +221,7 @@ impl ClickhousePool {
|
||||
};
|
||||
let client = self.client()?;
|
||||
let query_id = uuid::Uuid::new_v4().to_string();
|
||||
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), *session).body(sql.to_owned());
|
||||
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), &session).body(sql.to_owned());
|
||||
let started = Instant::now();
|
||||
let fetch = async {
|
||||
let mut response = request.send().await.map_err(http_error)?;
|
||||
@@ -254,7 +275,7 @@ impl ClickhousePool {
|
||||
match result {
|
||||
Some(result) => {
|
||||
if result.is_ok() {
|
||||
*session = true;
|
||||
session.initialized = true;
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -323,9 +344,9 @@ type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
|
||||
|
||||
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
|
||||
/// page), then keeps `max_rows` rows; later rows only set `has_more` and are read past
|
||||
/// unparsed, so a grid limit bounds memory however large the block
|
||||
/// `result_overflow_mode=break` lets the server send. A line that is not a JSON array
|
||||
/// starts the exception ClickHouse writes when a query fails mid-stream.
|
||||
/// unparsed, so a grid limit bounds memory even if a strict read-only server does not allow
|
||||
/// per-query result limits. A line that is not a JSON array starts the exception ClickHouse
|
||||
/// writes when a query fails mid-stream.
|
||||
struct RowReader {
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
@@ -479,6 +500,20 @@ fn read_pem(path: &str, label: &str) -> IdeResult<Vec<u8>> {
|
||||
.map_err(|error| IdeError::new(ErrorKind::Io, format!("cannot read ClickHouse {label}: {error}")))
|
||||
}
|
||||
|
||||
fn rejects_driver_setting(error: &IdeError) -> bool {
|
||||
error
|
||||
.message
|
||||
.split_once(": ")
|
||||
.and_then(|(_, detail)| detail.strip_prefix("Code: 164. DB::Exception: Cannot modify '"))
|
||||
.and_then(|detail| detail.split_once("' setting in readonly mode"))
|
||||
.is_some_and(|(name, _)| {
|
||||
matches!(
|
||||
name,
|
||||
"output_format_json_quote_denormals" | "max_result_rows" | "result_overflow_mode" | "readonly"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn reserved_setting(name: &str) -> bool {
|
||||
let name = name.to_ascii_lowercase();
|
||||
name.starts_with("output_format_json_")
|
||||
@@ -726,6 +761,77 @@ mod tests {
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connects_when_server_forbids_settings_in_readonly_mode() {
|
||||
let (port, requests) = server(vec![
|
||||
(
|
||||
"500 Internal Server Error",
|
||||
"X-ClickHouse-Exception-Code: 164\r\n",
|
||||
"Code: 164. DB::Exception: Cannot modify 'output_format_json_quote_denormals' setting in readonly mode. (READONLY)",
|
||||
),
|
||||
("200 OK", "", ONE),
|
||||
("200 OK", "", "[\"n\"]\n[\"UInt64\"]\n[1]\n[2]\n"),
|
||||
])
|
||||
.await;
|
||||
let source = DataSource {
|
||||
read_only: true,
|
||||
properties: vec![DbProperty { name: "max_threads".into(), value: "2".into() }],
|
||||
..source(port)
|
||||
};
|
||||
let pool = Pool::connect(&source, None, None).await.unwrap();
|
||||
let result = pool.execute("SELECT number FROM numbers(2)", 1, &CancellationToken::new()).await.unwrap();
|
||||
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
|
||||
assert!(result.has_more);
|
||||
|
||||
let requests = requests.await.unwrap();
|
||||
assert!(requests[0].ends_with("SELECT 1"));
|
||||
assert!(requests[0].contains("output_format_json_quote_denormals=1"));
|
||||
assert!(requests[1].ends_with("SELECT getSetting('readonly')"));
|
||||
assert!(requests[2].contains("session_check=1"));
|
||||
for request in &requests[1..] {
|
||||
assert!(request.contains("default_format=JSONCompactEachRowWithNamesAndTypes"));
|
||||
assert!(request.contains("max_threads=2"));
|
||||
for setting in
|
||||
["output_format_json_quote_denormals=", "max_result_rows=", "result_overflow_mode=", "readonly="]
|
||||
{
|
||||
assert!(!request.contains(setting), "{setting} is not allowed in a strict read-only session");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn readonly_probe_does_not_disable_settings_on_a_writable_session() {
|
||||
let (port, requests) = server(vec![
|
||||
(
|
||||
"500 Internal Server Error",
|
||||
"X-ClickHouse-Exception-Code: 164\r\n",
|
||||
"Code: 164. DB::Exception: Cannot modify 'max_result_rows' setting in readonly mode. (READONLY)",
|
||||
),
|
||||
("200 OK", "", "[\"readonly\"]\n[\"UInt64\"]\n[0]\n"),
|
||||
])
|
||||
.await;
|
||||
let source = DataSource { read_only: true, ..source(port) };
|
||||
let error = Pool::connect(&source, None, None).await.err().expect("writable session must stay rejected");
|
||||
assert!(error.message.contains("Cannot modify 'max_result_rows'"));
|
||||
assert!(requests.await.unwrap()[1].ends_with("SELECT getSetting('readonly')"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readonly_probe_matches_only_the_driver_settings() {
|
||||
for (code, setting, expected) in [
|
||||
(164, "max_result_rows", true),
|
||||
(164, "result_overflow_mode", true),
|
||||
(164, "readonly", true),
|
||||
(164, "max_threads", false),
|
||||
(516, "max_result_rows", false),
|
||||
] {
|
||||
let error = IdeError::invalid(format!(
|
||||
"ClickHouse HTTP 500: Code: {code}. DB::Exception: Cannot modify '{setting}' setting in readonly mode. (READONLY)"
|
||||
));
|
||||
assert_eq!(rejects_driver_setting(&error), expected, "{setting}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn server_errors_keep_details_and_hide_passwords() {
|
||||
let (port, requests) = server(vec![(
|
||||
|
||||
@@ -916,6 +916,37 @@ impl DbManager {
|
||||
self.tunnels.lock().remove(id);
|
||||
}
|
||||
|
||||
/// Creates a database on the server of data source `id` by running `statement` on the data
|
||||
/// source's own database, after closing the IDE's connections to `template`, the database
|
||||
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
|
||||
pub async fn create_database(&self, id: &str, template: &str, statement: &str) -> IdeResult<()> {
|
||||
let id = split_target(id).0;
|
||||
if self.source(id)?.read_only {
|
||||
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
|
||||
}
|
||||
self.disconnect(&format!("{id}:{template}")).await;
|
||||
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
|
||||
self.remember_statement(id, statement);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `database` of the server of data source `id` by running `statement` on the data
|
||||
/// source's own database, after closing the IDE's connections to `database`.
|
||||
/// Refuses the database the data source connects to and read-only data sources.
|
||||
pub async fn drop_database(&self, id: &str, database: &str, statement: &str) -> IdeResult<()> {
|
||||
let id = split_target(id).0;
|
||||
if self.source(id)?.read_only {
|
||||
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
|
||||
}
|
||||
if self.databases(id).await?.current == database {
|
||||
return Err(IdeError::invalid(format!("the data source connects to {database}; it cannot drop it")));
|
||||
}
|
||||
self.disconnect(&format!("{id}:{database}")).await;
|
||||
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
|
||||
self.remember_statement(id, statement);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
|
||||
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
|
||||
let id = split_target(id).0;
|
||||
|
||||
@@ -230,6 +230,44 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
|
||||
}
|
||||
|
||||
/// Runs `job` with the newest installed copy of its tool, the way the dialogs do.
|
||||
#[tokio::test]
|
||||
async fn drops_a_database_the_ide_holds_connections_to() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
db.execute("p", "DROP DATABASE IF EXISTS oi_drop_me", 0, &c).await?;
|
||||
db.execute("p", "CREATE DATABASE oi_drop_me TEMPLATE template0", 0, &c).await?;
|
||||
|
||||
// What the tree and a manual-commit console leave open on the database.
|
||||
db.schemas("p:oi_drop_me").await?;
|
||||
db.set_manual_commit("p:oi_drop_me", true).await?;
|
||||
db.execute("p:oi_drop_me", "SELECT 1", 1, &c).await?;
|
||||
|
||||
db.drop_database("p", "oi_drop_me", "drop database oi_drop_me").await?;
|
||||
assert!(!db.is_connected("p:oi_drop_me"));
|
||||
assert!(!db.databases("p").await?.names.iter().any(|n| n == "oi_drop_me"));
|
||||
|
||||
let current = db.databases("p").await?.current;
|
||||
let refused = db.drop_database("p", ¤t, &format!("drop database \"{current}\"")).await;
|
||||
assert!(refused.is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn creates_a_database_from_a_template_the_ide_holds_connections_to() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
db.execute("p", "DROP DATABASE IF EXISTS oi_from_template", 0, &c).await?;
|
||||
db.schemas("p:template1").await?;
|
||||
|
||||
db.create_database("p", "template1", "create database oi_from_template").await?;
|
||||
assert!(!db.is_connected("p:template1"));
|
||||
assert!(db.databases("p").await?.names.iter().any(|n| n == "oi_from_template"));
|
||||
db.execute("p", "DROP DATABASE oi_from_template", 0, &c).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_tool(db: &DbManager, target: &str, job: ide_db::tools::DbToolJob) -> IdeResult<()> {
|
||||
let install = ide_db::tools::find_installs(job.tool()).into_iter().next().expect("installed");
|
||||
let mut lines = Vec::new();
|
||||
|
||||
@@ -95,3 +95,44 @@ async fn sqlserver_values_paging_transactions_and_cancellation() {
|
||||
task.await.unwrap();
|
||||
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
|
||||
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
|
||||
let mut parts = server.splitn(4, ':');
|
||||
let (host, port, user, password) = (
|
||||
parts.next().unwrap(),
|
||||
parts.next().unwrap().parse().unwrap(),
|
||||
parts.next().unwrap(),
|
||||
parts.next().unwrap_or(""),
|
||||
);
|
||||
let source = |database: &str| DataSource {
|
||||
id: "s".into(),
|
||||
name: "sqlserver".into(),
|
||||
driver: DbDriver::SqlServer,
|
||||
host: host.into(),
|
||||
port: Some(port),
|
||||
user: user.into(),
|
||||
database: database.into(),
|
||||
ssl: DbSslMode::Disable,
|
||||
..Default::default()
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = ide_db::DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![source("master")]).await.unwrap();
|
||||
db.set_password("s", Some(password.into()), false).await.unwrap();
|
||||
let name = format!("oi_force_drop_{}", std::process::id());
|
||||
// The tree's connection to `model` would keep SQL Server from copying it.
|
||||
db.schemas("s:model").await.unwrap();
|
||||
db.create_database("s", "model", &format!("create database {name};")).await.unwrap();
|
||||
assert!(!db.is_connected("s:model"));
|
||||
|
||||
let other = Pool::connect(&source(&name), Some(password), None).await.unwrap();
|
||||
let held = Held::acquire(&other).await.unwrap();
|
||||
let force = format!("alter database {name} set single_user with rollback immediate;\ndrop database {name};");
|
||||
db.drop_database("s", &name, &force).await.unwrap();
|
||||
assert!(!db.databases("s").await.unwrap().names.contains(&name));
|
||||
drop(held);
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::settings::{ExternalFormatter, LanguagesSettings};
|
||||
use ide_core::{DocId, IdeError, IdeEvent, IdeResult, Pos, Range, TextEdit};
|
||||
use ide_language::LanguageConfig;
|
||||
use ide_core::settings::{ExternalFormatter, LanguagesSettings, Settings};
|
||||
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, Pos, Range, TextEdit};
|
||||
use ide_language::{LanguageConfig, PhpAlignment, Syntax};
|
||||
use ide_lsp::types::FormatOptions;
|
||||
use ide_tools::{Tools, formatter};
|
||||
use std::path::Path;
|
||||
@@ -129,12 +129,101 @@ pub async fn format(
|
||||
let project = host.project(window)?;
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let settings = project.settings.effective();
|
||||
let alignment = php_alignment(&settings, &snap.language);
|
||||
let original = alignment.any().then(|| (snap.language.clone(), snap.text.clone()));
|
||||
let Some(edits) = provider_edits(host, window, &project, snap, settings, range, options).await? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let Some((language, text)) = original else {
|
||||
return Ok(edits);
|
||||
};
|
||||
let syntax = host.syntax();
|
||||
tokio::task::spawn_blocking(move || align_formatted(&syntax, &language, &text, edits, range, alignment))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// PHP Code Style › Align key-value pairs / Align consecutive assignments (off by default, as in PhpStorm).
|
||||
fn php_alignment(settings: &Settings, language: &LanguageId) -> PhpAlignment {
|
||||
let style = settings.editor.code_style.languages.get(language.as_str());
|
||||
PhpAlignment {
|
||||
key_value_pairs: style.and_then(|s| s.align_key_value_pairs).unwrap_or(false),
|
||||
assignments: style.and_then(|s| s.align_consecutive_assignments).unwrap_or(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The formatter's `edits` to `text` followed by the alignment, as one set of edits to `text`.
|
||||
/// With a `range`, only its lines (where the formatter left them) are aligned.
|
||||
fn align_formatted(
|
||||
syntax: &Syntax,
|
||||
language: &LanguageId,
|
||||
text: &str,
|
||||
edits: Vec<TextEdit>,
|
||||
range: Option<Range>,
|
||||
alignment: PhpAlignment,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
let mut formatted = ide_text::Document::new(text);
|
||||
// Edits the editor has to sort out itself (overlapping ones) are passed on unaligned.
|
||||
let Ok((changes, _)) = formatted.apply_edits(&edits) else {
|
||||
return Ok(edits);
|
||||
};
|
||||
let lines = range.map(|range| {
|
||||
let original = ide_text::Document::new(text);
|
||||
let start = formatted.offset_to_pos(map_offset(&changes, original.pos_to_offset(range.start), false));
|
||||
let end = formatted.offset_to_pos(map_offset(&changes, original.pos_to_offset(range.end), true));
|
||||
let last = if end.col == 0 && end.line > start.line { end.line - 1 } else { end.line };
|
||||
(start.line as usize, last as usize)
|
||||
});
|
||||
let Some(aligned) = syntax.align_php(language, &formatted.text(), lines, alignment) else {
|
||||
return Ok(edits);
|
||||
};
|
||||
let original = ide_text::Document::new(text);
|
||||
Ok(original
|
||||
.diff(&aligned)
|
||||
.changes
|
||||
.into_iter()
|
||||
.map(|c| TextEdit {
|
||||
range: Range::new(original.offset_to_pos(c.from), original.offset_to_pos(c.to)),
|
||||
new_text: c.insert,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Where UTF-16 `offset` of the text before `changes` ends up after them; inside a replaced
|
||||
/// part, at its start or (`end`) its end.
|
||||
fn map_offset(changes: &ChangeSet, offset: u32, end: bool) -> u32 {
|
||||
let mut shift: i64 = 0;
|
||||
for c in &changes.changes {
|
||||
let inserted = c.insert.encode_utf16().count() as i64;
|
||||
if c.to < offset || (c.to == offset && (c.from < c.to || end)) {
|
||||
shift += inserted - i64::from(c.to - c.from);
|
||||
} else if c.from < offset {
|
||||
return (i64::from(c.from) + shift + if end { inserted } else { 0 }) as u32;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
(i64::from(offset) + shift) as u32
|
||||
}
|
||||
|
||||
/// The edits of the formatter that handles the document; `None` when it doesn't run
|
||||
/// (formatting on save is off for it).
|
||||
async fn provider_edits(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
project: &crate::Project,
|
||||
snap: ide_workspace::documents::DocumentInfo,
|
||||
settings: Settings,
|
||||
range: Option<Range>,
|
||||
options: FormatOptions,
|
||||
) -> IdeResult<Option<Vec<TextEdit>>> {
|
||||
let doc = snap.id;
|
||||
let language = project.languages.get(&snap.language);
|
||||
if options.tool.is_none()
|
||||
&& let Some(id) = settings.languages.plugin_formatters.get(snap.language.as_str()).filter(|s| !s.is_empty())
|
||||
{
|
||||
if options.on_save && !settings.editor.format_on_save {
|
||||
return Ok(Vec::new());
|
||||
return Ok(None);
|
||||
}
|
||||
if snap.read_only {
|
||||
return Err(IdeError::invalid("The file is read-only"));
|
||||
@@ -160,7 +249,8 @@ pub async fn format(
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
.map(Some);
|
||||
}
|
||||
// A committed PHP-CS-Fixer configuration takes over Reformat Code for `.php` files.
|
||||
if options.tool.is_none()
|
||||
@@ -168,7 +258,7 @@ pub async fn format(
|
||||
&& let Some(fixer) = formatter::php_cs_fixer(&snap.path)
|
||||
{
|
||||
if options.on_save && !settings.editor.format_on_save {
|
||||
return Ok(Vec::new());
|
||||
return Ok(None);
|
||||
}
|
||||
host.require_trust(window)?;
|
||||
if snap.read_only {
|
||||
@@ -188,7 +278,7 @@ pub async fn format(
|
||||
body: Some("PHP-CS-Fixer does not support selection formatting; formatted the whole file".into()),
|
||||
});
|
||||
}
|
||||
return Ok(edits);
|
||||
return Ok(Some(edits));
|
||||
}
|
||||
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
|
||||
if let Some(tool) = selected
|
||||
@@ -200,13 +290,13 @@ pub async fn format(
|
||||
}
|
||||
let Some(selected) = selected else {
|
||||
if options.on_save && !settings.editor.format_on_save {
|
||||
return Ok(Vec::new());
|
||||
return Ok(None);
|
||||
}
|
||||
return project.lsp.format(doc, range, options).await;
|
||||
return project.lsp.format(doc, range, options).await.map(Some);
|
||||
};
|
||||
let tool_settings = settings.languages.formatter(selected);
|
||||
if options.on_save && !tool_settings.run_on_save {
|
||||
return Ok(Vec::new());
|
||||
return Ok(None);
|
||||
}
|
||||
host.require_trust(window)?;
|
||||
if snap.read_only {
|
||||
@@ -262,7 +352,7 @@ pub async fn format(
|
||||
)),
|
||||
});
|
||||
}
|
||||
edits.map_err(|e| e.with_tool(tool))
|
||||
edits.map(Some).map_err(|e| e.with_tool(tool))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -413,6 +503,103 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn after(text: &str, edits: &[TextEdit]) -> String {
|
||||
let mut doc = ide_text::Document::new(text);
|
||||
doc.apply_edits(edits).unwrap();
|
||||
doc.text()
|
||||
}
|
||||
|
||||
fn whole_file(text: &str, formatted: &str) -> Vec<TextEdit> {
|
||||
let doc = ide_text::Document::new(text);
|
||||
doc.diff(formatted)
|
||||
.changes
|
||||
.into_iter()
|
||||
.map(|c| TextEdit {
|
||||
range: Range::new(doc.offset_to_pos(c.from), doc.offset_to_pos(c.to)),
|
||||
new_text: c.insert,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
|
||||
|
||||
#[test]
|
||||
fn php_alignment_is_off_unless_the_php_code_style_turns_it_on() {
|
||||
let php = LanguageId::new("php");
|
||||
let mut settings = Settings::default();
|
||||
assert_eq!(php_alignment(&settings, &php), PhpAlignment::default());
|
||||
let style =
|
||||
ide_core::editor_settings::LanguageCodeStyle { align_key_value_pairs: Some(true), ..Default::default() };
|
||||
settings.editor.code_style.languages.insert("php".into(), style);
|
||||
assert_eq!(php_alignment(&settings, &php), PhpAlignment { key_value_pairs: true, assignments: false });
|
||||
assert_eq!(php_alignment(&settings, &LanguageId::new("javascript")), PhpAlignment::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alignment_follows_the_formatter_edits_even_when_there_are_none() {
|
||||
let syntax = Syntax::new();
|
||||
let php = LanguageId::new("php");
|
||||
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
|
||||
let edits = align_formatted(&syntax, &php, text, Vec::new(), None, ALIGN).unwrap();
|
||||
assert_eq!(after(text, &edits), "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
|
||||
|
||||
// The language server re-indents the array: the alignment applies to its result.
|
||||
let text = "<?php\n$a = [\n'a' => 1,\n'bbb' => 2,\n];\n";
|
||||
let formatted = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
|
||||
let edits = align_formatted(&syntax, &php, text, whole_file(text, formatted), None, ALIGN).unwrap();
|
||||
assert_eq!(after(text, &edits), "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
|
||||
|
||||
let unchanged = whole_file(text, formatted);
|
||||
let off = align_formatted(&syntax, &php, text, unchanged.clone(), None, PhpAlignment::default()).unwrap();
|
||||
assert_eq!(off, unchanged);
|
||||
|
||||
let overlapping = vec![
|
||||
TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 4)), new_text: "x".into() },
|
||||
TextEdit { range: Range::new(Pos::new(1, 2), Pos::new(1, 6)), new_text: "y".into() },
|
||||
];
|
||||
let passed = align_formatted(&syntax, &php, text, overlapping.clone(), None, ALIGN).unwrap();
|
||||
assert_eq!(passed, overlapping);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_aligns_only_its_lines_whatever_the_formatter_changed() {
|
||||
let syntax = Syntax::new();
|
||||
let php = LanguageId::new("php");
|
||||
let text = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
|
||||
// PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection.
|
||||
let formatted = format!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
|
||||
let edits = whole_file(text, &formatted);
|
||||
// Lines 3..=6 select the array, up to the start of the line after it.
|
||||
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
|
||||
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
|
||||
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
|
||||
assert_eq!(
|
||||
after(text, &aligned),
|
||||
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n"
|
||||
);
|
||||
let range = Range::new(Pos::new(1, 0), Pos::new(2, 9));
|
||||
let aligned = align_formatted(&syntax, &php, text, Vec::new(), Some(range), ALIGN).unwrap();
|
||||
assert_eq!(after(text, &aligned), "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offsets_map_through_changes() {
|
||||
let changes = ChangeSet {
|
||||
changes: vec![
|
||||
ide_core::TextChange { from: 2, to: 2, insert: "ab".into() },
|
||||
ide_core::TextChange { from: 5, to: 8, insert: "x".into() },
|
||||
],
|
||||
};
|
||||
assert_eq!(map_offset(&changes, 0, false), 0);
|
||||
assert_eq!(map_offset(&changes, 2, false), 2);
|
||||
assert_eq!(map_offset(&changes, 2, true), 4);
|
||||
assert_eq!(map_offset(&changes, 4, false), 6);
|
||||
assert_eq!(map_offset(&changes, 6, false), 7);
|
||||
assert_eq!(map_offset(&changes, 6, true), 8);
|
||||
assert_eq!(map_offset(&changes, 8, false), 8);
|
||||
assert_eq!(map_offset(&changes, 10, false), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_ranges_are_one_based_unicode_columns() {
|
||||
let text = ide_text::Document::new("😀x = 1\ny = 2\n");
|
||||
|
||||
@@ -253,6 +253,16 @@ impl Host {
|
||||
self.project(window)?.require_trust()
|
||||
}
|
||||
|
||||
/// [`Self::require_trust`] for IDE-wide toolchain work (SDK detection, tool installs) that
|
||||
/// also runs from a window without a project, such as Settings opened from the Welcome
|
||||
/// screen: there is no project there to trust.
|
||||
pub fn require_trust_if_project(&self, window: &str) -> IdeResult<()> {
|
||||
match self.project(window) {
|
||||
Ok(project) => project.require_trust(),
|
||||
Err(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The window that owns what `window` starts.
|
||||
pub fn owner_window<'a>(&self, window: &'a str) -> &'a str {
|
||||
(self.owner)(window)
|
||||
|
||||
@@ -356,6 +356,13 @@ async fn run_to_end(call: &Call, config: RunConfig, errors: &mut BuildErrors) ->
|
||||
t.drain(..cut);
|
||||
}
|
||||
});
|
||||
let config = match resolve_jvm_application(call, config, errors).await? {
|
||||
Ok(config) => config,
|
||||
Err(reason) => {
|
||||
errors.process_outputs.push(reason);
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
let info = crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await?;
|
||||
let exit = wait_exit(call, info.id, None).await?.flatten();
|
||||
if exit == Some(0) {
|
||||
@@ -367,6 +374,177 @@ async fn run_to_end(call: &Call, config: RunConfig, errors: &mut BuildErrors) ->
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Run configuration kinds launched as a JVM main class (`JVM_APPLICATION_KINDS` in the UI).
|
||||
const JVM_APPLICATION_KINDS: [&str; 2] = ["application", "spring-boot"];
|
||||
const CLASSPATH: &str = "${classpath}";
|
||||
const TEST_CLASSPATH: &str = "${testClasspath}";
|
||||
|
||||
/// `java` options whose value is the next argument (`parseJavaArgs` in the UI).
|
||||
const JAVA_OPTIONS_WITH_VALUE: [&str; 13] = [
|
||||
"-cp",
|
||||
"-classpath",
|
||||
"--class-path",
|
||||
"-p",
|
||||
"--module-path",
|
||||
"--upgrade-module-path",
|
||||
"--add-modules",
|
||||
"--add-opens",
|
||||
"--add-exports",
|
||||
"--add-reads",
|
||||
"--patch-module",
|
||||
"--limit-modules",
|
||||
"--enable-native-access",
|
||||
];
|
||||
|
||||
/// The main class of `java` arguments and which classpath placeholder they use (`Some(true)`:
|
||||
/// `${testClasspath}`; `None`: an explicit classpath or none).
|
||||
fn java_main_class(args: &[String]) -> (Option<&str>, Option<bool>) {
|
||||
let mut test = None;
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let a = args[i].as_str();
|
||||
if a == "-jar" {
|
||||
return (None, test);
|
||||
}
|
||||
if matches!(a, "-cp" | "-classpath" | "--class-path") {
|
||||
match args.get(i + 1).map(String::as_str) {
|
||||
Some(CLASSPATH) => test = Some(false),
|
||||
Some(TEST_CLASSPATH) => test = Some(true),
|
||||
_ => {}
|
||||
}
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if JAVA_OPTIONS_WITH_VALUE.contains(&a) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if !a.starts_with('-') {
|
||||
return (Some(a), test);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
(None, test)
|
||||
}
|
||||
|
||||
/// `args` with the classpath placeholders replaced and the module path added (`resolveJavaCommand`).
|
||||
fn resolved_java_args(args: &[String], info: &ide_lsp::jdtls::JavaLaunchInfo) -> Vec<String> {
|
||||
let cp = info.class_paths.join(&info.path_list_separator);
|
||||
let mut out = Vec::with_capacity(args.len() + 2);
|
||||
if !info.module_paths.is_empty() && !args.iter().any(|a| a == "-p" || a == "--module-path") {
|
||||
out.push("--module-path".to_owned());
|
||||
out.push(info.module_paths.join(&info.path_list_separator));
|
||||
}
|
||||
out.extend(args.iter().map(|a| if a == CLASSPATH || a == TEST_CLASSPATH { cp.clone() } else { a.clone() }));
|
||||
out
|
||||
}
|
||||
|
||||
/// The module (relative to the project root) of a JVM source file: the part before
|
||||
/// `src/<set>/<language>/` (`jvmModuleDir` without a build model).
|
||||
fn jvm_module_of(rel: &str) -> Option<String> {
|
||||
let rel = rel.replace('\\', "/");
|
||||
let parts: Vec<&str> = rel.split('/').collect();
|
||||
(0..parts.len().saturating_sub(3)).find_map(|i| {
|
||||
(parts[i] == "src" && matches!(parts[i + 2], "java" | "kotlin" | "scala" | "groovy"))
|
||||
.then(|| parts[..i].join("/"))
|
||||
})
|
||||
}
|
||||
|
||||
/// The module of a configuration saved without one, found from its main class's source
|
||||
/// (`findJavaModule`): `None` unless exactly one module declares it.
|
||||
async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>> {
|
||||
let outer = main.split('$').next().unwrap_or(main);
|
||||
let (pkg, simple) = outer.rsplit_once('.').unwrap_or(("", outer));
|
||||
let mut names = vec![format!("{simple}.java"), format!("{simple}.kt")];
|
||||
if let Some(stem) = simple.strip_suffix("Kt") {
|
||||
names.push(format!("{stem}.kt"));
|
||||
}
|
||||
let mut modules = std::collections::BTreeSet::new();
|
||||
for name in names {
|
||||
for path in crate::ops::nav::find_files_named(&call.host(), call.window(), name).await? {
|
||||
let path = std::path::PathBuf::from(path);
|
||||
let Ok(text) = std::fs::read_to_string(&path) else { continue };
|
||||
let declared = text
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find_map(|l| l.strip_prefix("package "))
|
||||
.map(|p| p.trim_end_matches(';').trim())
|
||||
.unwrap_or("");
|
||||
if declared != pkg {
|
||||
continue;
|
||||
}
|
||||
let rel = path.strip_prefix(call.root()).unwrap_or(&path).to_string_lossy().into_owned();
|
||||
modules.insert(jvm_module_of(&rel).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
Ok((modules.len() == 1).then(|| modules.into_iter().next().unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// A JVM application configuration ready to start, as the Run tool window launches it:
|
||||
/// built per its before-launch build policy, with `${classpath}` / `${testClasspath}`, the
|
||||
/// module path and the module's `java` resolved through jdtls. `Err` says why it cannot start
|
||||
/// (compile errors are added to `errors`). Other configurations are returned as they are.
|
||||
async fn resolve_jvm_application(
|
||||
call: &Call,
|
||||
config: RunConfig,
|
||||
errors: &mut BuildErrors,
|
||||
) -> IdeResult<Result<RunConfig, String>> {
|
||||
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
|
||||
return Ok(Ok(config));
|
||||
}
|
||||
let (main, test) = java_main_class(&config.args);
|
||||
let Some(main) = main.map(str::to_owned) else {
|
||||
return Ok(Err(format!("No main class in '{}'", config.name)));
|
||||
};
|
||||
let module = match config.extras.module.clone() {
|
||||
Some(module) => module,
|
||||
None => match find_java_module(call, &main).await? {
|
||||
Some(module) => module,
|
||||
None => return Ok(Err(format!("Cannot determine the module for main class '{main}'"))),
|
||||
},
|
||||
};
|
||||
let policy = config.extras.build_policy.unwrap_or_default();
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
let host = call.host();
|
||||
let info = crate::ops::java::resolve_launch(
|
||||
&host,
|
||||
call.window(),
|
||||
std::path::PathBuf::from(&module),
|
||||
test == Some(true),
|
||||
policy,
|
||||
&cancel,
|
||||
)
|
||||
.await?;
|
||||
use ide_lsp::jdtls::JavaBuildStatus;
|
||||
if matches!(info.build, Some(JavaBuildStatus::Failed | JavaBuildStatus::WithErrors))
|
||||
&& policy != ide_run::BuildPolicy::MakeAndContinueOnErrors
|
||||
{
|
||||
for e in &info.errors {
|
||||
errors.errors.push(format!(
|
||||
"{}:{}: {}",
|
||||
std::path::PathBuf::from(e.path.clone()).display(),
|
||||
e.line,
|
||||
e.message
|
||||
));
|
||||
}
|
||||
let reason = if info.build == Some(JavaBuildStatus::Failed) {
|
||||
format!("Build failed; '{}' was not started.", config.name)
|
||||
} else {
|
||||
format!("Build has compile errors; '{}' was not started.", config.name)
|
||||
};
|
||||
return Ok(Err(reason));
|
||||
}
|
||||
if test.is_some() && info.class_paths.is_empty() {
|
||||
return Ok(Err("The classpath is empty: is the module imported by the Java language server?".to_owned()));
|
||||
}
|
||||
let args = resolved_java_args(&config.args, &info);
|
||||
let command = match (&info.java_exec, config.command.as_str()) {
|
||||
(Some(exec), "java") => exec.clone(),
|
||||
_ => config.command.clone(),
|
||||
};
|
||||
Ok(Ok(RunConfig { command, args, ..config }))
|
||||
}
|
||||
|
||||
/// The configuration's before-launch tasks, as the Run tool window runs them; returns why
|
||||
/// the launch is aborted, if it is. Tool windows are not activated.
|
||||
async fn before_launch(
|
||||
@@ -608,6 +786,10 @@ one by one",
|
||||
if let Some(reason) = before_launch(&call, &config, &configs, &mut Vec::new(), &mut errors).await? {
|
||||
return Err(execution_failed(&[errors.text(), Some(reason)]));
|
||||
}
|
||||
let config = match resolve_jvm_application(&call, config, &mut errors).await? {
|
||||
Ok(config) => config,
|
||||
Err(reason) => return Err(execution_failed(&[errors.text(), Some(reason)])),
|
||||
};
|
||||
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
|
||||
let output_path = collector.lock().path.clone();
|
||||
let sink = collector.clone();
|
||||
@@ -684,6 +866,40 @@ provided, values are merged over existing env.",
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn strings(args: &[&str]) -> Vec<String> {
|
||||
args.iter().map(|a| (*a).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_arguments_name_the_main_class_and_classpath_placeholder() {
|
||||
let run = strings(&["-Xmx1g", "-cp", CLASSPATH, "--add-opens", "a/b=ALL-UNNAMED", "com.example.App", "x"]);
|
||||
assert_eq!(java_main_class(&run), (Some("com.example.App"), Some(false)));
|
||||
assert_eq!(java_main_class(&strings(&["-classpath", TEST_CLASSPATH, "T"])), (Some("T"), Some(true)));
|
||||
assert_eq!(java_main_class(&strings(&["-cp", "lib/*", "Main"])), (Some("Main"), None));
|
||||
assert_eq!(java_main_class(&strings(&["-jar", "app.jar"])), (None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolved_java_arguments_replace_the_placeholder_and_add_the_module_path() {
|
||||
let info = ide_lsp::jdtls::JavaLaunchInfo {
|
||||
class_paths: vec!["/p/target/classes".into(), "/m2/a.jar".into()],
|
||||
module_paths: vec!["/m2/mod.jar".into()],
|
||||
path_list_separator: ":".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
resolved_java_args(&strings(&["-cp", CLASSPATH, "App"]), &info),
|
||||
strings(&["--module-path", "/m2/mod.jar", "-cp", "/p/target/classes:/m2/a.jar", "App"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_file_belongs_to_the_module_before_its_source_set() {
|
||||
assert_eq!(jvm_module_of("repro-dto/src/main/java/com/example/App.java").as_deref(), Some("repro-dto"));
|
||||
assert_eq!(jvm_module_of("src/test/kotlin/AppTest.kt").as_deref(), Some(""));
|
||||
assert_eq!(jvm_module_of("scripts/App.java"), None);
|
||||
}
|
||||
|
||||
fn config() -> RunConfig {
|
||||
RunConfig {
|
||||
id: "user:x".into(),
|
||||
|
||||
@@ -236,7 +236,7 @@ impl Tool {
|
||||
destructive: false,
|
||||
output_schema: None,
|
||||
input_schema: json!({ "type": "object", "properties": {
|
||||
"projectPath": { "type": "string", "description": "Any directory inside an open project. Optional when only one project is open." }
|
||||
"projectPath": { "type": "string", "description": "Any directory inside an open project. Defaults to the connection's project (`?project=`) or the only open one." }
|
||||
}, "required": [] }),
|
||||
},
|
||||
handler: Arc::new(move |call| Box::pin(handler(call))),
|
||||
|
||||
@@ -369,10 +369,21 @@ pub async fn agent_delete(host: &Host, window: &str, task: String, remove_worktr
|
||||
host.project(window)?.agents.delete(&task, remove_worktree).await
|
||||
}
|
||||
|
||||
/// The task's changed files as `view` compares them (without: since it started).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_changes(host: &Host, window: &str, task: String) -> IdeResult<Vec<AgentChange>> {
|
||||
pub async fn agent_changes(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
view: Option<AgentChangesView>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.changes(&task).await
|
||||
let agents = &host.project(window)?.agents;
|
||||
match view.unwrap_or_default() {
|
||||
AgentChangesView::SinceStart => agents.changes(&task).await,
|
||||
AgentChangesView::Group => Ok(agents.grouped_changes(&task).await?.uncommitted),
|
||||
AgentChangesView::LastTurn => agents.turn_changes(&task).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// The task's uncommitted changes and the commits made since it started.
|
||||
@@ -382,11 +393,17 @@ pub async fn agent_grouped_changes(host: &Host, window: &str, task: String) -> I
|
||||
host.project(window)?.agents.grouped_changes(&task).await
|
||||
}
|
||||
|
||||
/// Content of `path` when the task started (left side of its diff).
|
||||
/// Content of `path` as `view` compares it (without: when the task started), the left side of its diff.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_base_text(host: &Host, window: &str, task: String, path: IpcPath) -> IdeResult<Option<String>> {
|
||||
pub async fn agent_base_text(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
path: IpcPath,
|
||||
view: Option<AgentChangesView>,
|
||||
) -> IdeResult<Option<String>> {
|
||||
host.require_trust(window)?;
|
||||
host.project(window)?.agents.base_text(&task, path.into_path_buf()).await
|
||||
host.project(window)?.agents.base_text(&task, path.into_path_buf(), view.unwrap_or_default()).await
|
||||
}
|
||||
|
||||
/// Rollback: the task's changed files among `paths` (all without) back as `view` compares them.
|
||||
|
||||
@@ -139,6 +139,32 @@ pub async fn db_disconnect(host: &Host, window: &str, id: String) -> IdeResult<(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_create_database(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
template: String,
|
||||
statement: String,
|
||||
) -> IdeResult<()> {
|
||||
// Creates a database on the server of data source `id` with `statement`, copied from `template` (New › Database).
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.create_database(&id, &template, &statement).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_drop_database(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
database: String,
|
||||
statement: String,
|
||||
) -> IdeResult<()> {
|
||||
// Drops `database` of the server of data source `id` with `statement` (Drop… on a database node).
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.drop_database(&id, &database, &statement).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_databases(host: &Host, window: &str, id: String) -> IdeResult<Databases> {
|
||||
// Databases of the server of data source `id` (PostgreSQL); connect to one as `<id>:<database>`.
|
||||
@@ -478,10 +504,12 @@ ide_command::domain!(
|
||||
db_connected,
|
||||
db_console_path,
|
||||
db_consoles,
|
||||
db_create_database,
|
||||
db_database_catalog,
|
||||
db_databases,
|
||||
db_ddl,
|
||||
db_disconnect,
|
||||
db_drop_database,
|
||||
db_execute,
|
||||
db_explain,
|
||||
db_finish_transaction,
|
||||
|
||||
@@ -70,6 +70,18 @@ pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
/// An automatic save: `false` (nothing written) when the file changed on disk after the
|
||||
/// buffer was edited, which only an explicit save overwrites.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
|
||||
if saved {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
|
||||
}
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
@@ -109,6 +121,7 @@ ide_command::domain!(
|
||||
doc_open,
|
||||
doc_open_untitled,
|
||||
doc_save,
|
||||
doc_autosave,
|
||||
doc_save_all,
|
||||
doc_save_as,
|
||||
doc_snapshot,
|
||||
|
||||
@@ -311,6 +311,11 @@ async fn shutdown_does_not_wait_forever_for_a_stuck_capture() {
|
||||
shutdown_within(&f.host, std::time::Duration::from_millis(200)).await;
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(5));
|
||||
assert!(cancel.is_cancelled());
|
||||
// The cleanup is only waited for briefly and finishes in the background on a busy machine.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
while stuck_dir.exists() && std::time::Instant::now() < deadline {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(!stuck_dir.exists(), "its directory is removed once the wait is over");
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ pub async fn java_resolve_launch(
|
||||
result
|
||||
}
|
||||
|
||||
async fn resolve_launch(
|
||||
pub(crate) async fn resolve_launch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: PathBuf,
|
||||
|
||||
@@ -359,10 +359,22 @@ pub async fn lsp_goto(host: &Host, window: &str, doc: DocId, pos: Pos, kind: Got
|
||||
if kind != GotoKind::Definition {
|
||||
return result;
|
||||
}
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else { return result };
|
||||
// A Maven placeholder (`@profileActive@` in `application.yml` or `.properties`) navigates to its pom.
|
||||
let maven = super::maven_placeholder::definition(host, window, doc, pos).await;
|
||||
let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Definition) else {
|
||||
return match maven {
|
||||
None => result,
|
||||
Some(found) => {
|
||||
let in_string = in_string_literal(host, window, doc, pos).await;
|
||||
definition_targets(result, vec![found], in_string)
|
||||
}
|
||||
};
|
||||
};
|
||||
let found = plugin_call(move || plugins.provide_definition(&d, pos)).await.unwrap_or_default();
|
||||
let found: Vec<Location> =
|
||||
found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }).collect();
|
||||
let found: Vec<Location> = maven
|
||||
.into_iter()
|
||||
.chain(found.into_iter().map(|l| Location { path: l.path.into(), range: l.range, uri: None }))
|
||||
.collect();
|
||||
let in_string = !found.is_empty() && in_string_literal(host, window, doc, pos).await;
|
||||
definition_targets(result, found, in_string)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
//! ⌘B on a Maven resource-filtering placeholder: `@property@` in a YAML or properties
|
||||
//! resource (Spring's `application.yml` / `application.properties`) jumps to the `<properties>` entry that defines it,
|
||||
//! in the nearest `pom.xml` above the file, up through the project root. Parent
|
||||
//! poms the nearest pom declares itself are followed from there; a parent outside
|
||||
//! that walk that no pom declares is not.
|
||||
|
||||
use super::doc::blocking;
|
||||
use crate::Host;
|
||||
use ide_build::maven;
|
||||
use ide_core::{DocId, Location, Pos};
|
||||
use std::path::Path;
|
||||
|
||||
/// The definition location of the placeholder under `pos` in `doc`, when `doc` is a
|
||||
/// YAML or properties file holding a `@token@` there and a pom above it defines that property.
|
||||
pub(crate) async fn definition(host: &Host, window: &str, doc: DocId, pos: Pos) -> Option<Location> {
|
||||
let project = host.project(window).ok()?;
|
||||
blocking(move || {
|
||||
let snap = project.documents.text_snapshot(doc)?;
|
||||
if snap.large || !matches!(snap.language.as_str(), "yaml" | "properties") {
|
||||
return Ok(None);
|
||||
}
|
||||
let path = project.documents.identity(doc)?.0;
|
||||
let Some((name, _token_at)) = placeholder_at(&snap.text, pos) else { return Ok(None) };
|
||||
Ok(pom_defining(&project.root, &path, &name))
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// The `@token@` enclosing `pos` on its line, with the token's range (UTF-16 columns).
|
||||
fn placeholder_at(text: &str, pos: Pos) -> Option<(String, ide_core::Range)> {
|
||||
let line = text.split_inclusive('\n').nth(pos.line as usize)?;
|
||||
let line = line.trim_end_matches(['\n', '\r']);
|
||||
let cursor = utf16_to_byte(line, pos.col)?;
|
||||
let mut opener: Option<usize> = None;
|
||||
for (i, b) in line.as_bytes().iter().enumerate() {
|
||||
if *b != b'@' {
|
||||
continue;
|
||||
}
|
||||
if let Some(start) = opener.replace(i) {
|
||||
let token = &line[start + 1..i];
|
||||
let valid =
|
||||
!token.is_empty() && token.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'));
|
||||
if valid && start <= cursor && cursor <= i {
|
||||
let col = |byte: usize| line[..byte].encode_utf16().count() as u32;
|
||||
return Some((
|
||||
token.to_owned(),
|
||||
ide_core::Range::new(Pos::new(pos.line, col(start)), Pos::new(pos.line, col(i + 1))),
|
||||
));
|
||||
}
|
||||
opener = None;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The nearest `pom.xml` above `from` (up to and including `root`) defining `name`.
|
||||
fn pom_defining(root: &Path, from: &Path, name: &str) -> Option<Location> {
|
||||
let mut dir = from.parent()?.to_path_buf();
|
||||
loop {
|
||||
let pom = dir.join("pom.xml");
|
||||
if pom.is_file()
|
||||
&& let Some(found) = maven::property_declaration(&pom, name, maven::default_local_repo())
|
||||
{
|
||||
return Some(Location::file(found.path, found.range));
|
||||
}
|
||||
if dir == root || !dir.starts_with(root) {
|
||||
return None;
|
||||
}
|
||||
dir = dir.parent()?.to_path_buf();
|
||||
}
|
||||
}
|
||||
|
||||
/// UTF-16 column → byte offset within one line.
|
||||
fn utf16_to_byte(line: &str, col: u32) -> Option<usize> {
|
||||
let col = col as usize;
|
||||
let mut units = 0usize;
|
||||
for (byte, c) in line.char_indices() {
|
||||
if units == col {
|
||||
return Some(byte);
|
||||
}
|
||||
units += c.len_utf16();
|
||||
if units > col {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(units == col).then_some(line.len())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::Pos;
|
||||
|
||||
fn at(line: u32, col: u32) -> Pos {
|
||||
Pos::new(line, col)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_placeholder_under_the_cursor_and_its_range() {
|
||||
let text = "spring:\n profiles:\n active: @profileActive@\n";
|
||||
let (name, range) = placeholder_at(text, at(2, 20)).unwrap();
|
||||
assert_eq!(name, "profileActive");
|
||||
assert_eq!(range.start, at(2, 12));
|
||||
assert_eq!(range.end, at(2, 27));
|
||||
// The `@`s themselves and inside the token navigate; just past the token does not.
|
||||
for col in [12u32, 13, 26] {
|
||||
assert_eq!(placeholder_at(text, at(2, col)).unwrap().0, "profileActive");
|
||||
}
|
||||
// A second pair on the line and unrelated cursors stay unresolved.
|
||||
let multi = "a: @one@ @two@\n";
|
||||
assert_eq!(placeholder_at(multi, at(0, 4)).unwrap().0, "one");
|
||||
assert_eq!(placeholder_at(multi, at(0, 10)).unwrap().0, "two");
|
||||
assert!(placeholder_at(multi, at(0, 8)).is_none(), "between the pairs");
|
||||
assert!(placeholder_at(multi, at(0, 9)).is_some(), "the opening @ of the next pair");
|
||||
assert!(placeholder_at(multi, at(0, 14)).is_none(), "just past the last pair");
|
||||
assert!(placeholder_at("value: plain\n", at(0, 7)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nearest_pom_wins_and_the_walk_stops_at_the_project_root() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let deep = root.join("core/src/main/resources");
|
||||
std::fs::create_dir_all(&deep).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
"<project>\n <properties>\n <parentName>parent</parentName>\n </properties>\n</project>\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir_all(root.join("core")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("core/pom.xml"),
|
||||
"<project>\n <properties>\n <name>module</name>\n </properties>\n</project>\n",
|
||||
)
|
||||
.unwrap();
|
||||
let from = deep.join("application.yml");
|
||||
// The module pom defines `name` first: its file wins, pointing at its `<name>` entry.
|
||||
let found = pom_defining(&root, &from, "name").unwrap();
|
||||
assert_eq!(found.path, root.join("core/pom.xml"));
|
||||
assert_eq!(found.range.start.line, 2);
|
||||
// A property only the parent defines resolves there; unknown ones resolve nowhere.
|
||||
let parent = pom_defining(&root, &from, "parentName").unwrap();
|
||||
assert_eq!(parent.path, root.join("pom.xml"));
|
||||
assert_eq!(parent.range.start.line, 2);
|
||||
assert!(pom_defining(&root, &from, "missing").is_none());
|
||||
// A file outside the project root has no pom walk.
|
||||
let outside = tmp.path().join("elsewhere/application.yml");
|
||||
std::fs::create_dir_all(tmp.path().join("elsewhere")).unwrap();
|
||||
assert!(pom_defining(&root, &outside, "name").is_none());
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ pub mod history;
|
||||
pub mod java;
|
||||
pub mod jvm_icons;
|
||||
pub mod lsp;
|
||||
pub mod maven_placeholder;
|
||||
pub mod nav;
|
||||
pub mod notebook;
|
||||
pub mod project;
|
||||
|
||||
@@ -34,9 +34,9 @@ pub struct ProjectInterpreter {
|
||||
}
|
||||
|
||||
/// Installed interpreters / toolchains of `kind`; project-local ones first.
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<Vec<Sdk>> {
|
||||
host.require_trust(window)?;
|
||||
host.require_trust_if_project(window)?;
|
||||
let project = host.project(window).ok();
|
||||
if kind == SdkKind::Jdk {
|
||||
host.apply_added_jdks();
|
||||
@@ -63,10 +63,10 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
|
||||
}
|
||||
|
||||
/// The Python interpreters of the recently opened projects, each with its project.
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeResult<Vec<ProjectInterpreter>> {
|
||||
// Newest first. The open project is skipped: `sdk_detect` lists its own.
|
||||
host.require_trust(window)?;
|
||||
host.require_trust_if_project(window)?;
|
||||
let current = host.project(window).ok().map(|p| p.root.clone());
|
||||
let config = host.config_dir.clone();
|
||||
// Probing runs the project's interpreter (and its settings may name any program): only
|
||||
@@ -111,9 +111,9 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
|
||||
}
|
||||
|
||||
/// An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run.
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) -> IdeResult<Option<Sdk>> {
|
||||
host.require_trust(window)?;
|
||||
host.require_trust_if_project(window)?;
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
tokio::task::spawn_blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref())))
|
||||
.await
|
||||
@@ -320,7 +320,7 @@ pub async fn sdk_locate_tools(
|
||||
}
|
||||
|
||||
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_create_venv(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -330,7 +330,7 @@ pub async fn sdk_python_create_venv(
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<Sdk> {
|
||||
host.require_trust(window)?;
|
||||
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, &cancel, &|line| {
|
||||
@@ -343,14 +343,14 @@ pub async fn sdk_python_create_venv(
|
||||
result?
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_packages(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
python: PathBuf,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<PythonPackage>> {
|
||||
host.require_trust(window)?;
|
||||
host.require_trust_if_project(window)?;
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result =
|
||||
tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, &cancel)).await.map_err(join_err);
|
||||
@@ -360,7 +360,7 @@ pub async fn sdk_python_packages(
|
||||
|
||||
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn sdk_python_pip(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -371,7 +371,7 @@ pub async fn sdk_python_pip(
|
||||
request: RequestId,
|
||||
on_output: Channel<String>,
|
||||
) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
host.require_trust_if_project(window)?;
|
||||
let project_root = host.project(window).ok().map(|p| p.root.clone());
|
||||
let cancel = host.begin_project_request(window, request);
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
|
||||
@@ -15,6 +15,9 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
Some(doc) => (doc, false),
|
||||
None => (docs.open(path)?.id, true),
|
||||
};
|
||||
// A buffer without unsaved changes (open only for the search preview, or a clean
|
||||
// tab) is saved like a closed file; one the user is editing is left unsaved.
|
||||
let save = transient || !docs.is_dirty(doc)?;
|
||||
let result = (|| {
|
||||
// Recompute if the user typed between reading the text and applying.
|
||||
for _ in 0..3 {
|
||||
@@ -27,7 +30,7 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
continue;
|
||||
}
|
||||
docs.apply_edits(doc, &edits)?;
|
||||
if transient {
|
||||
if save {
|
||||
docs.save(doc)?;
|
||||
}
|
||||
return Ok(edits.len() as u32);
|
||||
@@ -46,8 +49,8 @@ impl ReplaceHost for DocumentsHost<'_> {
|
||||
///
|
||||
/// Edits go through the document layer as one patch per file, so open editors
|
||||
/// update live and undo the whole file's replacements in one step. Unsaved
|
||||
/// editor buffers are replaced in place and left unsaved; files that were not
|
||||
/// open are opened transiently, saved and closed.
|
||||
/// editor buffers are replaced in place and left unsaved; other open documents
|
||||
/// are saved, and files that were not open are opened transiently, saved and closed.
|
||||
///
|
||||
/// With `all_in_scope` (Replace All after the search hit its match limit) the
|
||||
/// scope is searched again without the limit and every match in it is replaced,
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::path::PathBuf;
|
||||
|
||||
/// The installer, reporting the executables chosen in the window's settings.
|
||||
fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
|
||||
host.require_trust(window)?;
|
||||
host.require_trust_if_project(window)?;
|
||||
let data = host.local_data_dir.clone();
|
||||
let (settings, root) = match host.project(window) {
|
||||
Ok(project) => (project.settings.effective(), project.root.clone()),
|
||||
@@ -56,7 +56,7 @@ fn reconfigure_servers(host: &Host) {
|
||||
}
|
||||
|
||||
/// Status of every known language server / debug adapter and the languages using it.
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
|
||||
let tools = tools(host, window)?;
|
||||
let langs = languages(host, window);
|
||||
@@ -65,7 +65,7 @@ pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
|
||||
|
||||
/// Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
|
||||
/// `on_event`. Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn tools_install(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
@@ -93,7 +93,7 @@ pub async fn tools_install(
|
||||
|
||||
/// Newer versions of the tools the IDE installed (release downloads and npm packages).
|
||||
/// Cancel with `cancel_request(request)`.
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<ToolUpdate>> {
|
||||
let tools = tools(host, window)?;
|
||||
let cancel = host.begin_request(request);
|
||||
@@ -103,7 +103,7 @@ pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> Ide
|
||||
}
|
||||
|
||||
/// Removes a tool the IDE installed.
|
||||
#[command(trust = trusted)]
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn tools_uninstall(host: &Host, window: &str, name: String) -> IdeResult<ToolInfo> {
|
||||
let tools = tools(host, window)?;
|
||||
let langs = languages(host, window);
|
||||
|
||||
@@ -47,12 +47,19 @@ pub async fn serves_page(url: &str) -> bool {
|
||||
response.status().is_success() && html
|
||||
}
|
||||
|
||||
/// The built-in server's URL for `path` (started on first use).
|
||||
/// The built-in server's URL for `path` (started on first use). A file whose language is
|
||||
/// HTML (Settings › File Types can make it so) is served as a page, whatever its extension.
|
||||
#[command(trust = always)]
|
||||
pub async fn web_url(host: &Host, window: &str, path: IpcPath) -> IdeResult<String> {
|
||||
// Under the window's project when it holds the file.
|
||||
let root = host.project(window).ok().map(|p| p.root.clone());
|
||||
host.web.url_for(root.as_deref(), &path).await
|
||||
let project = host.project(window).ok();
|
||||
let root = project.as_ref().map(|p| p.root.as_path());
|
||||
let languages = project.as_ref().map_or(&host.languages, |p| &p.languages);
|
||||
if matches!(languages.detect(&path, None).as_str(), "html" | "django-html") {
|
||||
host.web.page_url_for(root, &path).await
|
||||
} else {
|
||||
host.web.url_for(root, &path).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -272,6 +272,7 @@ impl Host {
|
||||
lombok.jar(),
|
||||
);
|
||||
ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective);
|
||||
ide_sdk::apply::configure_maven_sources(cfg, &effective);
|
||||
ide_sdk::jdtls::launch_directly(cfg);
|
||||
}
|
||||
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
|
||||
@@ -285,6 +286,8 @@ impl Host {
|
||||
effective.languages.java.gradle.linked_projects.as_deref(),
|
||||
build_files.as_deref(),
|
||||
);
|
||||
// After the import settings: they extend the workspace folder's name.
|
||||
ide_sdk::jdtls_workspaces::use_own_temp(cfg, &data_dir);
|
||||
}
|
||||
}));
|
||||
}
|
||||
@@ -321,7 +324,7 @@ impl Host {
|
||||
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
|
||||
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
|
||||
documents.add_observer(Arc::new(LspObserver(lsp.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver::new(history.clone())));
|
||||
documents.add_observer(Arc::new(DeployObserver {
|
||||
remote: self.remote.clone(),
|
||||
settings: settings.clone(),
|
||||
@@ -782,7 +785,7 @@ impl Host {
|
||||
lsp.set_servers_hook(Box::new(|_, _| Vec::new()));
|
||||
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
|
||||
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
|
||||
documents.add_observer(Arc::new(HistoryObserver::new(history.clone())));
|
||||
let watcher = match watch_dir {
|
||||
Some(dir) => light_watcher(dir, &sink, &documents, &history)?,
|
||||
// A quiet private folder stands in until the first save brings a
|
||||
@@ -1887,14 +1890,42 @@ impl DocumentObserver for SyntaxObserver {
|
||||
}
|
||||
}
|
||||
|
||||
struct HistoryObserver(Arc<LocalHistory>);
|
||||
struct HistoryObserver {
|
||||
history: Arc<LocalHistory>,
|
||||
/// Documents edited since they were opened: only the first edit looks for a missing original.
|
||||
edited: Mutex<HashSet<ide_core::DocId>>,
|
||||
}
|
||||
|
||||
impl HistoryObserver {
|
||||
fn new(history: Arc<LocalHistory>) -> Self {
|
||||
Self { history, edited: Mutex::default() }
|
||||
}
|
||||
}
|
||||
|
||||
impl DocumentObserver for HistoryObserver {
|
||||
fn saved(&self, _doc: ide_core::DocId, path: &Path, text: &str) {
|
||||
if let Err(e) = self.0.record(path, text, "Saved") {
|
||||
fn changed(
|
||||
&self,
|
||||
doc: ide_core::DocId,
|
||||
path: &Path,
|
||||
_version: u32,
|
||||
_changes: &[AppliedChange],
|
||||
_full_text: &dyn Fn() -> String,
|
||||
) {
|
||||
// The file on disk still has its content from before the edit.
|
||||
if self.edited.lock().insert(doc)
|
||||
&& let Err(e) = self.history.record_original(path)
|
||||
{
|
||||
tracing::warn!("local history: {e}");
|
||||
}
|
||||
}
|
||||
fn saved(&self, _doc: ide_core::DocId, path: &Path, text: &str) {
|
||||
if let Err(e) = self.history.record(path, text, "Saved") {
|
||||
tracing::warn!("local history: {e}");
|
||||
}
|
||||
}
|
||||
fn closed(&self, doc: ide_core::DocId, _path: &Path) {
|
||||
self.edited.lock().remove(&doc);
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads saved files: remote files' local copies, and automatic upload to the default server.
|
||||
|
||||
@@ -879,16 +879,15 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
|
||||
// Room for activation (about 3_100 on macOS, more on Windows). A background task gets ten
|
||||
// times it (5 s / 500 ms): enough for each step of `patient` with its CPU work (32_000 to
|
||||
// 80_000), not for the whole run without the refill on each report.
|
||||
let f = fixture(Limits {
|
||||
let limits = Limits {
|
||||
fuel: 40_000,
|
||||
timeout: Duration::from_millis(500),
|
||||
background: Duration::from_millis(5_000),
|
||||
..Limits::default()
|
||||
});
|
||||
};
|
||||
let f = fixture(limits);
|
||||
f.install(&misbehave_pkg());
|
||||
if f.host.set_capability("misbehave", "process:git", true).is_err() {
|
||||
return;
|
||||
}
|
||||
f.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
|
||||
// Warm up activation in its own call so `patient` starts with a fresh budget.
|
||||
assert_eq!(f.run("misbehave", "echo", Some("warm")).unwrap().as_deref(), Some("warm"));
|
||||
|
||||
@@ -897,6 +896,13 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
|
||||
|
||||
let err = f.run("misbehave", "spin", None).unwrap_err();
|
||||
assert!(err.contains("exceeded its CPU budget (40000 fuel per call)"), "{err}");
|
||||
|
||||
// Beginning a task alone must not renew its scaled budget.
|
||||
let quiet = fixture(limits);
|
||||
quiet.install(&misbehave_pkg());
|
||||
quiet.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
|
||||
let err = quiet.run("misbehave", "patient", Some("quiet:4000")).unwrap_err();
|
||||
assert!(err.contains("exceeded its CPU budget (400000 fuel per call)"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -146,3 +146,52 @@ async fn replace_all_covers_matches_past_the_limit() {
|
||||
host.close_project("main");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4202: a file the search preview holds open (no unsaved changes) is saved like a closed
|
||||
/// one; a buffer with unsaved edits is replaced in place and left for the editor to save.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn replace_all_saves_open_buffers_without_unsaved_changes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
for name in ["previewed.txt", "edited.txt", "closed.txt"] {
|
||||
std::fs::write(root.join(name), "TOKEN\n").unwrap();
|
||||
}
|
||||
let host = 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: |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();
|
||||
project.documents.open(&root.join("previewed.txt")).unwrap();
|
||||
let edited = project.documents.open(&root.join("edited.txt")).unwrap().id;
|
||||
project.documents.replace_all(edited, "TOKEN\nmore\n").unwrap();
|
||||
ops::search::replace_in_files(
|
||||
&host,
|
||||
"main",
|
||||
RequestId::next(),
|
||||
query("TOKEN", false),
|
||||
"DONE".into(),
|
||||
false,
|
||||
vec![],
|
||||
true,
|
||||
ops::Channel::new(|_| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let disk = |name: &str| std::fs::read_to_string(root.join(name)).unwrap();
|
||||
assert_eq!(disk("previewed.txt"), "DONE\n");
|
||||
assert_eq!(disk("closed.txt"), "DONE\n");
|
||||
assert_eq!(disk("edited.txt"), "TOKEN\n", "unsaved edits stay unsaved");
|
||||
assert_eq!(project.documents.text_snapshot(edited).unwrap().text, "DONE\nmore\n");
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -45,6 +45,9 @@ async fn a_commands_trust_class_decides_where_it_runs() {
|
||||
assert_eq!(allowed("main", class), in_restricted, "{class:?} in Restricted Mode");
|
||||
assert_eq!(allowed("welcome", class), without_project, "{class:?} without a project");
|
||||
}
|
||||
// Toolchain detection runs from Settings opened on the Welcome screen, but not in Restricted Mode.
|
||||
assert!(ide_host::ops::sdk::sdk_detect(&host, "welcome", ide_sdk::SdkKind::Zig).await.is_ok());
|
||||
assert!(ide_host::ops::sdk::sdk_detect(&host, "main", ide_sdk::SdkKind::Zig).await.is_err());
|
||||
// These requests validate the vendor before any network access, independently of project trust.
|
||||
let error = ide_host::ops::tools::jdk_download_releases(&host, "unknown-vendor".into(), ide_core::RequestId(901))
|
||||
.await
|
||||
|
||||
@@ -28,7 +28,7 @@ pub use syntax::{
|
||||
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility,
|
||||
set_external_syntax, shift_pos, shift_range,
|
||||
};
|
||||
pub use syntax::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
|
||||
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
|
||||
@@ -10,6 +10,7 @@ mod inheritance;
|
||||
pub(crate) mod lines;
|
||||
mod literals;
|
||||
mod outline;
|
||||
mod php_align;
|
||||
mod python_facts;
|
||||
mod rst;
|
||||
mod selection;
|
||||
@@ -28,6 +29,7 @@ pub use inheritance::ClassBases;
|
||||
pub use lines::{shift_pos, shift_range};
|
||||
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
|
||||
pub use outline::merge_visibility;
|
||||
pub use php_align::PhpAlignment;
|
||||
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
//! PHP Code Style › Align key-value pairs and Align consecutive assignments (PhpStorm's
|
||||
//! options of the same names), applied to text a formatter has already formatted.
|
||||
//!
|
||||
//! A block is a run of array elements, or of assignment statements, on consecutive lines of
|
||||
//! the same array or statement list, one per line and each on a single line. A blank line,
|
||||
//! a comment line, another statement or element, or one spanning several lines ends it.
|
||||
//! Within a block the operators line up one space after the longest left-hand side; nested
|
||||
//! arrays form blocks of their own. Only the whitespace before an operator token of the
|
||||
//! syntax tree changes, so `=>` and `=` inside strings and comments are never touched.
|
||||
|
||||
use crate::{LanguageId, Syntax};
|
||||
use tree_sitter::{Node, Tree};
|
||||
|
||||
/// Which alignments to apply.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PhpAlignment {
|
||||
/// `=>` of the elements of multi-line arrays.
|
||||
pub key_value_pairs: bool,
|
||||
/// `=` of consecutive assignment statements.
|
||||
pub assignments: bool,
|
||||
}
|
||||
|
||||
impl PhpAlignment {
|
||||
pub fn any(self) -> bool {
|
||||
self.key_value_pairs || self.assignments
|
||||
}
|
||||
}
|
||||
|
||||
impl Syntax {
|
||||
/// `text` with its PHP alignment applied, changing only lines `lines` (0-based, inclusive;
|
||||
/// `None`: all). A block reaching outside them still aligns with its lines there.
|
||||
/// `None` when nothing changes or `lang` is not parsed with the PHP grammar.
|
||||
pub fn align_php(
|
||||
&self,
|
||||
lang: &LanguageId,
|
||||
text: &str,
|
||||
lines: Option<(usize, usize)>,
|
||||
options: PhpAlignment,
|
||||
) -> Option<String> {
|
||||
if !options.any() {
|
||||
return None;
|
||||
}
|
||||
self.analyze(lang, text, |g, tree, text| (g.spec.name == "php").then(|| align(tree, text, lines, options)))
|
||||
.flatten()
|
||||
}
|
||||
}
|
||||
|
||||
/// One line's operator: the whitespace `gap` before it and the width of the line up to it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Entry {
|
||||
line: usize,
|
||||
gap: (usize, usize),
|
||||
/// Characters from the start of the line to the end of the left-hand side.
|
||||
width: usize,
|
||||
}
|
||||
|
||||
fn align(tree: &Tree, text: &str, lines: Option<(usize, usize)>, options: PhpAlignment) -> Option<String> {
|
||||
let mut gaps: Vec<(usize, usize, usize)> = Vec::new();
|
||||
let mut cursor = tree.walk();
|
||||
visit(&mut cursor, &mut |node| {
|
||||
// Error recovery can read string content as code, where whitespace matters.
|
||||
if node.is_error() {
|
||||
return;
|
||||
}
|
||||
let entries = match node.kind() {
|
||||
"array_creation_expression" if options.key_value_pairs => run(node, text, key_value),
|
||||
_ if options.assignments => run(node, text, assignment),
|
||||
_ => return,
|
||||
};
|
||||
for block in blocks(&entries) {
|
||||
let column = block.iter().map(|e| e.width).max().unwrap_or(0) + 1;
|
||||
for e in block {
|
||||
if lines.is_none_or(|(first, last)| (first..=last).contains(&e.line)) {
|
||||
gaps.push((e.gap.0, e.gap.1, column - e.width));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
gaps.sort_unstable();
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut at = 0;
|
||||
let mut changed = false;
|
||||
for (from, to, spaces) in gaps {
|
||||
if text[from..to].len() == spaces && text[from..to].bytes().all(|b| b == b' ') {
|
||||
continue;
|
||||
}
|
||||
out.push_str(&text[at..from]);
|
||||
out.extend(std::iter::repeat_n(' ', spaces));
|
||||
at = to;
|
||||
changed = true;
|
||||
}
|
||||
if !changed {
|
||||
return None;
|
||||
}
|
||||
out.push_str(&text[at..]);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// The named children of `parent` as alignment candidates in order: `None` breaks a block.
|
||||
/// A comment ending the line of the child before it (`'a' => 1, // why`) is skipped; two
|
||||
/// children sharing a line are both left alone.
|
||||
fn run(parent: Node, text: &str, entry: fn(Node, &str) -> Option<Entry>) -> Vec<Option<Entry>> {
|
||||
let mut out: Vec<Option<Entry>> = Vec::new();
|
||||
let mut previous_end: Option<usize> = None;
|
||||
let mut cursor = parent.walk();
|
||||
for child in parent.named_children(&mut cursor) {
|
||||
let start = child.start_position().row;
|
||||
let shares_line = previous_end == Some(start);
|
||||
if child.kind() == "comment" && shares_line {
|
||||
continue;
|
||||
}
|
||||
if shares_line && let Some(last) = out.last_mut() {
|
||||
*last = None;
|
||||
}
|
||||
out.push(if shares_line { None } else { entry(child, text) });
|
||||
previous_end = Some(child.end_position().row);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Runs of entries on consecutive lines.
|
||||
fn blocks(entries: &[Option<Entry>]) -> Vec<Vec<Entry>> {
|
||||
let mut out: Vec<Vec<Entry>> = Vec::new();
|
||||
let mut current: Vec<Entry> = Vec::new();
|
||||
for entry in entries {
|
||||
match entry {
|
||||
Some(e) if current.last().is_none_or(|last| last.line + 1 == e.line) => current.push(*e),
|
||||
Some(e) => out.push(std::mem::replace(&mut current, vec![*e])),
|
||||
None if current.is_empty() => {}
|
||||
None => out.push(std::mem::take(&mut current)),
|
||||
}
|
||||
}
|
||||
if !current.is_empty() {
|
||||
out.push(current);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `'key' => value` alone on one line.
|
||||
fn key_value(element: Node, text: &str) -> Option<Entry> {
|
||||
if element.kind() != "array_element_initializer" {
|
||||
return None;
|
||||
}
|
||||
let mut cursor = element.walk();
|
||||
let arrow = element.children(&mut cursor).find(|c| c.kind() == "=>")?;
|
||||
let key = arrow.prev_sibling()?;
|
||||
entry(element, key, arrow, text)
|
||||
}
|
||||
|
||||
/// `$left = value;` (or `= &value`) alone on one line.
|
||||
fn assignment(statement: Node, text: &str) -> Option<Entry> {
|
||||
if statement.kind() != "expression_statement" {
|
||||
return None;
|
||||
}
|
||||
let expression = statement.named_child(0)?;
|
||||
if !matches!(expression.kind(), "assignment_expression" | "reference_assignment_expression") {
|
||||
return None;
|
||||
}
|
||||
let left = expression.child_by_field_name("left")?;
|
||||
let mut cursor = expression.walk();
|
||||
let operator = expression.children(&mut cursor).find(|c| c.kind() == "=")?;
|
||||
entry(statement, left, operator, text)
|
||||
}
|
||||
|
||||
fn entry(whole: Node, left: Node, operator: Node, text: &str) -> Option<Entry> {
|
||||
let line = whole.start_position().row;
|
||||
if whole.has_error() || whole.end_position().row != line {
|
||||
return None;
|
||||
}
|
||||
let line_start = whole.start_byte() - whole.start_position().column;
|
||||
let starts_line = text[line_start..whole.start_byte()].bytes().all(|b| b == b' ' || b == b'\t');
|
||||
let gap = (left.end_byte(), operator.start_byte());
|
||||
let blank_gap = text[gap.0..gap.1].bytes().all(|b| b == b' ' || b == b'\t');
|
||||
(starts_line && blank_gap).then(|| Entry { line, gap, width: text[line_start..gap.0].chars().count() })
|
||||
}
|
||||
|
||||
fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) {
|
||||
loop {
|
||||
f(cursor.node());
|
||||
if cursor.goto_first_child() {
|
||||
continue;
|
||||
}
|
||||
loop {
|
||||
if cursor.goto_next_sibling() {
|
||||
break;
|
||||
}
|
||||
if !cursor.goto_parent() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
const BOTH: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true };
|
||||
const PAIRS: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: false };
|
||||
const ASSIGNMENTS: PhpAlignment = PhpAlignment { key_value_pairs: false, assignments: true };
|
||||
|
||||
fn syntax() -> &'static Syntax {
|
||||
static S: OnceLock<Syntax> = OnceLock::new();
|
||||
S.get_or_init(Syntax::new)
|
||||
}
|
||||
|
||||
fn aligned(text: &str, lines: Option<(usize, usize)>, options: PhpAlignment) -> String {
|
||||
let out = syntax().align_php(&LanguageId::new("php"), text, lines, options);
|
||||
let result = out.clone().unwrap_or_else(|| text.to_owned());
|
||||
let strip = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>();
|
||||
assert_eq!(strip(&result), strip(text), "only whitespace changes");
|
||||
assert_eq!(
|
||||
syntax().align_php(&LanguageId::new("php"), &result, lines, options),
|
||||
None,
|
||||
"aligning again changes nothing:\n{result}"
|
||||
);
|
||||
result
|
||||
}
|
||||
|
||||
fn check(options: PhpAlignment, before: &str, after: &str) {
|
||||
assert_eq!(aligned(before, None, options), after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aligns_the_arrows_of_a_multi_line_array() {
|
||||
check(
|
||||
PAIRS,
|
||||
"<?php\nreturn [\n 'name' => 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n",
|
||||
"<?php\nreturn [\n 'name' => 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n",
|
||||
);
|
||||
check(
|
||||
PAIRS,
|
||||
"<?php\n$a = array(\n 1 => 'a',\n 1234 => 'b',\n);\n",
|
||||
"<?php\n$a = array(\n 1 => 'a',\n 1234 => 'b',\n);\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_arrays_align_per_level_and_a_multi_line_value_ends_a_block() {
|
||||
check(
|
||||
PAIRS,
|
||||
"<?php\n$config = [\n 'a' => 1,\n 'bbb' => 2,\n 'nested' => [\n 'x' => 1,\n 'yyyy' => 2,\n ],\n 'c' => 3,\n 'dd' => 4,\n];\n",
|
||||
"<?php\n$config = [\n 'a' => 1,\n 'bbb' => 2,\n 'nested' => [\n 'x' => 1,\n 'yyyy' => 2,\n ],\n 'c' => 3,\n 'dd' => 4,\n];\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_lines_comment_lines_and_elements_without_a_key_end_a_block() {
|
||||
check(
|
||||
PAIRS,
|
||||
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n\n 'ccc' => 3,\n // section\n 'dddd' => 4,\n 'e' => 5,\n 6,\n 'ff' => 7,\n];\n",
|
||||
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n\n 'ccc' => 3,\n // section\n 'dddd' => 4,\n 'e' => 5,\n 6,\n 'ff' => 7,\n];\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_comment_at_the_end_of_a_line_keeps_the_block() {
|
||||
check(
|
||||
PAIRS,
|
||||
"<?php\n$a = [\n 'a' => 1, // first\n 'bb' => 2, /* second */\n 'ccc' => 3,\n];\n",
|
||||
"<?php\n$a = [\n 'a' => 1, // first\n 'bb' => 2, /* second */\n 'ccc' => 3,\n];\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_line_arrays_and_elements_sharing_a_line_stay_as_they_are() {
|
||||
for text in [
|
||||
"<?php\n$a = ['a' => 1, 'bbb' => 2];\n",
|
||||
"<?php\n$a = [\n 'a' => 1, 'bbb' => 2,\n 'cc' => 3,\n];\n",
|
||||
"<?php\n$a = ['a' => 1,\n 'bbb' => 2];\n",
|
||||
] {
|
||||
assert_eq!(aligned(text, None, BOTH), text);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_and_equals_signs_outside_arrays_and_assignments_are_not_touched() {
|
||||
let text = "<?php\n\
|
||||
$s = 'a => b';\n\
|
||||
$t = \"x = y\";\n\
|
||||
// 'k' => 1, $v = 2\n\
|
||||
/* 'kk' => 1 */\n\
|
||||
foreach ($items as $key => $value) {}\n\
|
||||
$f = fn($x) => $x;\n\
|
||||
$m = match ($x) {\n 1 => 'a',\n 100 => 'b',\n};\n\
|
||||
for ($i = 0; $i < 3; $i++) {}\n\
|
||||
function g($a = 1, $bbb = 2) {}\n\
|
||||
g(a: 1, bbb: 2);\n\
|
||||
$h = <<<EOT\n 'a' => 1,\n 'bbb' => 2,\nEOT;\n";
|
||||
let out = aligned(text, None, PAIRS);
|
||||
assert_eq!(out, text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aligns_consecutive_assignments() {
|
||||
check(
|
||||
ASSIGNMENTS,
|
||||
"<?php\n$y = foo($x);\n$i = foo($i);\n$result = $result . $y . $i;\n$this->name = 'n';\n$ref = &$y;\n",
|
||||
"<?php\n$y = foo($x);\n$i = foo($i);\n$result = $result . $y . $i;\n$this->name = 'n';\n$ref = &$y;\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_statements_blank_lines_and_multi_line_assignments_end_a_block() {
|
||||
check(
|
||||
ASSIGNMENTS,
|
||||
"<?php\nfunction f() {\n $a = 1;\n $bb = 2;\n echo $a;\n $ccc = 3;\n $d = 4;\n\n $eeeee = 5;\n $f = 6;\n $g .= 'x';\n $hh = 7;\n $i = [\n 1,\n ];\n $jjj = 8;\n $k = 9;\n}\n",
|
||||
"<?php\nfunction f() {\n $a = 1;\n $bb = 2;\n echo $a;\n $ccc = 3;\n $d = 4;\n\n $eeeee = 5;\n $f = 6;\n $g .= 'x';\n $hh = 7;\n $i = [\n 1,\n ];\n $jjj = 8;\n $k = 9;\n}\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assignments_sharing_a_line_and_declarations_stay_as_they_are() {
|
||||
let text = "<?php\n$a = 1; $bbb = 2;\n$cc = 3;\nclass C {\n public $x = 1;\n public $yyy = 2;\n const A = 1;\n const BBB = 2;\n}\n";
|
||||
assert_eq!(aligned(text, None, ASSIGNMENTS), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_option_aligns_only_its_operator() {
|
||||
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n";
|
||||
assert_eq!(
|
||||
aligned(text, None, PAIRS),
|
||||
"<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n"
|
||||
);
|
||||
assert_eq!(
|
||||
aligned(text, None, ASSIGNMENTS),
|
||||
"<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n"
|
||||
);
|
||||
assert_eq!(syntax().align_php(&LanguageId::new("php"), text, None, PhpAlignment::default()), None);
|
||||
assert_eq!(syntax().align_php(&LanguageId::new("javascript"), "a = {\n b: 1,\n};\n", None, BOTH), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_given_lines_change_and_they_align_with_the_whole_block() {
|
||||
let text = "<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n 'cccc' => 3,\n];\n";
|
||||
assert_eq!(
|
||||
aligned(text, Some((2, 3)), PAIRS),
|
||||
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n 'cccc' => 3,\n];\n"
|
||||
);
|
||||
assert_eq!(aligned(text, Some((5, 5)), PAIRS), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widths_count_characters_not_bytes() {
|
||||
check(
|
||||
PAIRS,
|
||||
"<?php\n$a = [\n '名前' => 1,\n 'name' => 2,\n];\n",
|
||||
"<?php\n$a = [\n '名前' => 1,\n 'name' => 2,\n];\n",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_with_syntax_errors_is_aligned_only_where_it_parses() {
|
||||
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => ,\n 'cc' => 3,\n];\n";
|
||||
let out = aligned(text, None, PAIRS);
|
||||
assert!(out.contains("'bbb' => ,"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn php_inside_html() {
|
||||
check(
|
||||
BOTH,
|
||||
"<html>\n<?php\n$a = 1;\n$bbb = 2;\n?>\n<p>x = y</p>\n",
|
||||
"<html>\n<?php\n$a = 1;\n$bbb = 2;\n?>\n<p>x = y</p>\n",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,28 @@ pub(crate) fn lenient_diagnostics(server: &str, items: Value) -> Vec<lsp::Diagno
|
||||
parsed
|
||||
}
|
||||
|
||||
/// rust-analyzer publishes its own analysis next to `cargo check`'s (flycheck): one type
|
||||
/// mismatch then arrives as `rust-analyzer(E0308)` and `rustc(E0308)`. Its own entry is
|
||||
/// dropped when the compiler reports the same code and severity over an overlapping range.
|
||||
fn drop_compiler_duplicates(diagnostics: &mut Vec<lsp::Diagnostic>) {
|
||||
let overlaps = |a: &lsp::Range, b: &lsp::Range| a.start <= b.end && b.start <= a.end;
|
||||
let compiler: Vec<(lsp::Range, Option<lsp::NumberOrString>, Option<lsp::DiagnosticSeverity>)> = diagnostics
|
||||
.iter()
|
||||
.filter(|d| d.source.as_deref() == Some("rustc") && d.code.is_some())
|
||||
.map(|d| (d.range, d.code.clone(), d.severity))
|
||||
.collect();
|
||||
if compiler.is_empty() {
|
||||
return;
|
||||
}
|
||||
diagnostics.retain(|d| {
|
||||
d.source.as_deref() != Some("rust-analyzer")
|
||||
|| d.code.is_none()
|
||||
|| !compiler
|
||||
.iter()
|
||||
.any(|(range, code, severity)| code == &d.code && severity == &d.severity && overlaps(range, &d.range))
|
||||
});
|
||||
}
|
||||
|
||||
impl ClientHandler {
|
||||
pub fn new(mgr: Weak<LspManager>, server: Arc<Server>, generation: u64) -> Self {
|
||||
Self { mgr, server, generation }
|
||||
@@ -293,11 +315,20 @@ impl ClientHandler {
|
||||
}
|
||||
};
|
||||
params.diagnostics = lenient_diagnostics(&self.server.name, raw.unwrap_or(Value::Null));
|
||||
drop_compiler_duplicates(&mut params.diagnostics);
|
||||
let Some(path) = uri_to_path(params.uri.as_str())
|
||||
.or_else(|| crate::notebook::is_cell_uri(params.uri.as_str()).then(|| PathBuf::from(params.uri.as_str())))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.server.name == crate::compose::SERVER {
|
||||
// Maven resource-filtering placeholders (`@profileActive@`) parse as invalid
|
||||
// YAML but are replaced before the file is ever read: their parser error is noise.
|
||||
let text = mgr.docs.lock().values().find(|d| d.path == path).map(|d| d.text.as_str().to_owned());
|
||||
if let Some(text) = text {
|
||||
params.diagnostics.retain(|d| !crate::maven_placeholder::false_positive(&text, d));
|
||||
}
|
||||
}
|
||||
if self.server.name == "jdtls"
|
||||
&& let Some(failure) = crate::jdtls::build_plan_failure(&path, &self.server.root, ¶ms.diagnostics)
|
||||
{
|
||||
@@ -435,6 +466,14 @@ impl ClientHandler {
|
||||
.find_map(|base| section.split('.').try_fold(base, |v, key| v.get(key)))
|
||||
.cloned()
|
||||
.unwrap_or(Value::Null),
|
||||
None if self.server.name == "eslint" => {
|
||||
let mut settings = options.clone();
|
||||
settings["workspaceFolder"] = json!({
|
||||
"uri": crate::uri::path_to_uri(&self.server.root),
|
||||
"name": self.server.root.file_name().map_or_else(|| "root".into(), |name| name.to_string_lossy().into_owned()),
|
||||
});
|
||||
settings
|
||||
}
|
||||
None => options.clone(),
|
||||
})
|
||||
.collect(),
|
||||
@@ -693,6 +732,28 @@ mod tests {
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[test]
|
||||
fn rust_analyzer_s_own_entry_yields_to_the_compiler_s_for_the_same_error() {
|
||||
let diagnostic = |source: &str, code: &str, line: u32, severity| lsp::Diagnostic {
|
||||
range: lsp::Range::new(lsp::Position::new(line, 21), lsp::Position::new(line, 27)),
|
||||
severity: Some(severity),
|
||||
code: Some(lsp::NumberOrString::String(code.into())),
|
||||
source: Some(source.into()),
|
||||
message: format!("{source} {code}"),
|
||||
..Default::default()
|
||||
};
|
||||
let error = lsp::DiagnosticSeverity::ERROR;
|
||||
let mut items = vec![
|
||||
diagnostic("rust-analyzer", "E0308", 1, error),
|
||||
diagnostic("rustc", "E0308", 1, error),
|
||||
diagnostic("rust-analyzer", "E0308", 5, error),
|
||||
diagnostic("rust-analyzer", "unused_variables", 1, lsp::DiagnosticSeverity::WARNING),
|
||||
];
|
||||
drop_compiler_duplicates(&mut items);
|
||||
let left: Vec<_> = items.iter().map(|d| (d.message.as_str(), d.range.start.line)).collect();
|
||||
assert_eq!(left, [("rustc E0308", 1), ("rust-analyzer E0308", 5), ("rust-analyzer unused_variables", 1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tsserver_aborts_are_out_of_memory() {
|
||||
assert!(tsserver_ran_out_of_memory("TSServer exited. Code: 134. Signal: null"));
|
||||
|
||||
+45
-14
@@ -25,6 +25,7 @@ mod kotlin_lsp;
|
||||
mod launch;
|
||||
mod library_source;
|
||||
mod loading;
|
||||
mod maven_placeholder;
|
||||
mod message_requests;
|
||||
mod notebook;
|
||||
mod phoxite;
|
||||
@@ -1833,8 +1834,11 @@ impl LspManager {
|
||||
/// the same class from its Java model instead, decompiled with method bodies and navigable.
|
||||
/// Its documents belong to jdtls ([`Self::virtual_document`] records it).
|
||||
async fn jdt_library_classes(&self, snap: &DocSnap, pos: Pos, locs: Vec<Location>) -> Vec<Location> {
|
||||
let jar_class = |l: &Location| l.uri.as_deref().is_some_and(|u| u.starts_with("jar:") && u.ends_with(".class"));
|
||||
if !locs.iter().any(jar_class)
|
||||
let lib_class = |u: &str| {
|
||||
(u.starts_with("jar:") && u.ends_with(".class"))
|
||||
|| (u.starts_with("jdt://contents/") && u.contains(".class"))
|
||||
};
|
||||
if !locs.iter().any(|l| l.uri.as_deref().is_some_and(lib_class))
|
||||
|| !self.servers.lock().iter().any(|s| s.name == jdtls::SERVER && s.running().is_some())
|
||||
{
|
||||
return locs;
|
||||
@@ -1842,27 +1846,54 @@ impl LspManager {
|
||||
let name = library_source::identifier_at(snap.text.line(pos.line as usize), pos.col).map(str::to_owned);
|
||||
let mut out = Vec::with_capacity(locs.len());
|
||||
for loc in locs {
|
||||
let entry = loc.uri.as_deref().filter(|_| jar_class(&loc)).and_then(library_source::parse);
|
||||
let Some(entry) = entry else {
|
||||
let Some(original) = loc.uri.as_deref().filter(|u| lib_class(u)) else {
|
||||
out.push(loc);
|
||||
continue;
|
||||
};
|
||||
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
|
||||
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
|
||||
// of that name.
|
||||
let uri = match self.archive_class(entry.jar, entry.entry, true).await {
|
||||
Ok(uri) => uri,
|
||||
Err(e) => {
|
||||
tracing::info!("library class stays a stub: {}", e.message);
|
||||
let jdt = original.starts_with("jdt:");
|
||||
let uri = if !jdt {
|
||||
let Some(entry) = library_source::parse(original) else {
|
||||
out.push(loc);
|
||||
continue;
|
||||
};
|
||||
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
|
||||
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
|
||||
// of that name.
|
||||
match self.archive_class(entry.jar, entry.entry, true).await {
|
||||
Ok(uri) => uri,
|
||||
Err(e) => {
|
||||
tracing::info!("library class stays a stub: {}", e.message);
|
||||
out.push(loc);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
original.to_owned()
|
||||
};
|
||||
let range = match (&name, self.virtual_document(&uri).await) {
|
||||
(Some(name), Ok(doc)) => library_source::declaration_range(&doc.text, name),
|
||||
let doc = self.virtual_document(&uri).await.ok();
|
||||
let range = match (&name, &doc) {
|
||||
// jdtls' own class: its range is exact (overloads included) unless it maps a
|
||||
// Lombok-generated member onto the annotation or class header, which doesn't
|
||||
// name the member; only then look the declaration up in the source.
|
||||
(Some(name), Some(doc)) if jdt => {
|
||||
let line = doc.text.lines().nth(loc.range.start.line as usize).unwrap_or_default();
|
||||
if library_source::identifier_at(line, loc.range.start.col) == Some(name.as_str()) {
|
||||
loc.range
|
||||
} else {
|
||||
Some(library_source::declaration_range(&doc.text, name))
|
||||
.filter(|r| *r != Range::default())
|
||||
.unwrap_or(loc.range)
|
||||
}
|
||||
}
|
||||
(Some(name), Some(doc)) => library_source::declaration_range(&doc.text, name),
|
||||
_ if jdt => loc.range,
|
||||
_ => Range::default(),
|
||||
};
|
||||
out.push(Location { path: uri.clone().into(), range, uri: Some(uri) });
|
||||
out.push(if jdt {
|
||||
Location { range, ..loc }
|
||||
} else {
|
||||
Location { path: uri.clone().into(), range, uri: Some(uri) }
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -180,6 +180,7 @@ pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
|
||||
const KEYWORDS: [&str; 9] = ["fun", "class", "interface", "object", "val", "var", "typealias", "enum", "record"];
|
||||
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
|
||||
let mut fallback = None;
|
||||
let mut field = None;
|
||||
let mut block_comment = false;
|
||||
for (line_no, line) in text.lines().enumerate() {
|
||||
let trimmed = line.trim_start();
|
||||
@@ -223,9 +224,40 @@ pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
|
||||
if java_member && fallback.is_none() {
|
||||
fallback = Some(range);
|
||||
}
|
||||
// A Java field (`private String name;`, `int age = 5;`): Lombok sources declare only
|
||||
// the field, the accessors exist solely in the compiled class. A method of that name
|
||||
// still wins, so a same-named local declared before it is not taken.
|
||||
let java_field = matches!(line[end..].trim_start().chars().next(), Some(';' | '=' | ','))
|
||||
&& !head.trim_end().ends_with('.')
|
||||
&& !head.trim().is_empty()
|
||||
&& !head.contains(['=', '('])
|
||||
&& !words.iter().any(|w| matches!(*w, "return" | "throw" | "new" | "yield" | "assert"));
|
||||
if java_field && field.is_none() {
|
||||
field = Some(range);
|
||||
}
|
||||
}
|
||||
}
|
||||
fallback.unwrap_or_default()
|
||||
if let Some(range) = fallback.or(field) {
|
||||
return range;
|
||||
}
|
||||
accessor_field(name).map(|field| declaration_range(text, &field)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The field a Lombok/bean accessor stands for (`getName`/`setName` → `name`,
|
||||
/// `isActive` → `active`); `None` for names that are not accessors.
|
||||
fn accessor_field(name: &str) -> Option<String> {
|
||||
let rest = ["get", "set", "is"]
|
||||
.iter()
|
||||
.find_map(|p| name.strip_prefix(p))
|
||||
.filter(|r| r.chars().next().is_some_and(|c| c.is_uppercase()))?;
|
||||
let mut chars = rest.chars();
|
||||
let first = chars.next()?;
|
||||
// Bean convention: `getURL` → `URL`, `getName` → `name`.
|
||||
if rest.chars().nth(1).is_some_and(|c| c.is_uppercase()) {
|
||||
Some(rest.to_owned())
|
||||
} else {
|
||||
Some(first.to_lowercase().collect::<String>() + chars.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier around `col` (UTF-16) of `line`.
|
||||
@@ -588,6 +620,35 @@ mod tests {
|
||||
assert_eq!(declared_package("class A"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lombok_accessors_and_java_fields_locate_the_field() {
|
||||
// Lombok sources declare only the field; the accessors exist only in the
|
||||
// compiled class, so navigation must fall back to the underlying field.
|
||||
let lombok = "package example.entity;\n\nimport lombok.Getter;\nimport lombok.Setter;\n\n@Getter\n@Setter\npublic class UserEntity {\n private String name;\n private int age;\n private boolean active;\n}\n";
|
||||
for (name, line, col) in [
|
||||
("getName", 8, 19),
|
||||
("setName", 8, 19),
|
||||
("name", 8, 19),
|
||||
("getAge", 9, 16),
|
||||
("isActive", 10, 20),
|
||||
("active", 10, 20),
|
||||
] {
|
||||
let r = declaration_range(lombok, name);
|
||||
assert_eq!((r.start.line, r.start.col), (line, col), "{name}");
|
||||
}
|
||||
// An explicitly declared accessor still wins over the field.
|
||||
let plain = "class Plain {\n private String name;\n public String getName() { return name; }\n}\n";
|
||||
assert_eq!(declaration_range(plain, "getName").start.line, 2);
|
||||
// Initialized fields count; a method beats a same-named local declared before it.
|
||||
let init = "class Init {\n private int count = 0;\n void a() {\n int size = 1;\n }\n int size() { return 2; }\n}\n";
|
||||
assert_eq!(declaration_range(init, "getCount").start.line, 1);
|
||||
assert_eq!(declaration_range(init, "size").start.line, 5);
|
||||
// Bean convention keeps acronyms; non-accessors are not remapped.
|
||||
assert_eq!(accessor_field("getURL").as_deref(), Some("URL"));
|
||||
assert_eq!(accessor_field("getter"), None);
|
||||
assert_eq!(declaration_range(lombok, "missing"), Range::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locates_declarations_in_kotlin_and_java_sources() {
|
||||
let at = |text: &str, name: &str| {
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! `@property@` placeholders in YAML resources: Maven resource filtering replaces
|
||||
//! them before the file is ever read as YAML, so Spring projects use them unquoted
|
||||
//! (`spring.profiles.active: @profileActive@`). The YAML spec reserves `@` and the
|
||||
//! `yaml` parser behind `yaml-language-server` therefore reports
|
||||
//! "Plain value cannot start with reserved character @" for every one of them.
|
||||
//! The diagnostic is dropped when the reported scalar is exactly a Maven
|
||||
//! placeholder; anything else the parser flags keeps showing.
|
||||
|
||||
use lsp_types as lsp;
|
||||
|
||||
const RESERVED_AT: &str = "Plain value cannot start with reserved character @";
|
||||
|
||||
/// Whether `diagnostic` is the reserved-`@` parser error on a scalar whose text in
|
||||
/// `text` is exactly a Maven placeholder (`@token@`).
|
||||
pub(crate) fn false_positive(text: &str, diagnostic: &lsp::Diagnostic) -> bool {
|
||||
diagnostic.message == RESERVED_AT && placeholder_at(text, &diagnostic.range).is_some()
|
||||
}
|
||||
|
||||
/// The name between the `@`s of the diagnostic range, when it covers one whole placeholder.
|
||||
fn placeholder_at(text: &str, range: &lsp::Range) -> Option<String> {
|
||||
if range.start.line != range.end.line {
|
||||
return None;
|
||||
}
|
||||
let line = text.split_inclusive('\n').nth(range.start.line as usize)?;
|
||||
let line = line.trim_end_matches(['\n', '\r']);
|
||||
let start = utf16_to_byte(line, range.start.character)?.min(line.len());
|
||||
// The parser's scalar range ends one past the line (its newline), so the end clamps.
|
||||
let end = utf16_to_byte(line, range.end.character).unwrap_or(line.len());
|
||||
if end < start {
|
||||
return None;
|
||||
}
|
||||
let inner = line[start..end].strip_prefix('@')?.strip_suffix('@')?;
|
||||
(!inner.is_empty() && inner.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')))
|
||||
.then(|| inner.to_owned())
|
||||
}
|
||||
|
||||
/// UTF-16 column → byte offset within one line, `None` inside a surrogate pair or past the line.
|
||||
fn utf16_to_byte(line: &str, col: u32) -> Option<usize> {
|
||||
let col = col as usize;
|
||||
let mut units = 0usize;
|
||||
for (byte, c) in line.char_indices() {
|
||||
if units == col {
|
||||
return Some(byte);
|
||||
}
|
||||
units += c.len_utf16();
|
||||
if units > col {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(units == col).then_some(line.len())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lsp_types::{Position, Range};
|
||||
|
||||
fn at(line: u32, from: u32, to: u32) -> Range {
|
||||
Range { start: Position::new(line, from), end: Position::new(line, to) }
|
||||
}
|
||||
|
||||
fn across(from: (u32, u32), to: (u32, u32)) -> Range {
|
||||
Range { start: Position::new(from.0, from.1), end: Position::new(to.0, to.1) }
|
||||
}
|
||||
|
||||
fn diagnostic(range: Range) -> lsp::Diagnostic {
|
||||
lsp::Diagnostic { range, message: RESERVED_AT.to_owned(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_maven_placeholder_placeholder_is_a_false_positive() {
|
||||
let text = "spring:\n profiles:\n active: @profileActive@\n";
|
||||
assert!(false_positive(text, &diagnostic(at(2, 12, 27))));
|
||||
// The parser ends the scalar's range one past the line (its newline): still caught.
|
||||
assert!(false_positive(text, &diagnostic(at(2, 12, 28))));
|
||||
// Columns also decode on a line with non-ASCII text before the scalar.
|
||||
let text = "name: 项目\nvalue: @profileActive@\n";
|
||||
assert!(false_positive(text, &diagnostic(at(1, 7, 22))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_reserved_character_errors_and_shapes_still_show() {
|
||||
let text = "active: @profileActive@\n";
|
||||
// Not the parser's message (a backtick, a different wording).
|
||||
assert!(!false_positive(
|
||||
text,
|
||||
&lsp::Diagnostic {
|
||||
message: "Plain value cannot start with reserved character `".to_owned(),
|
||||
..diagnostic(at(0, 8, 11))
|
||||
}
|
||||
));
|
||||
// The error's range is stale and no longer covers a placeholder.
|
||||
assert!(!false_positive(text, &diagnostic(at(0, 0, 10))));
|
||||
// A single `@`, an unpaired one or a name with spaces is no placeholder.
|
||||
assert!(!false_positive("active: @\n", &diagnostic(at(0, 8, 9))));
|
||||
assert!(!false_positive("active: @profile\n", &diagnostic(at(0, 8, 16))));
|
||||
assert!(!false_positive("active: @pro file@\n", &diagnostic(at(0, 8, 18))));
|
||||
// A range crossing lines is kept.
|
||||
assert!(!false_positive("a: @x@\nb: y\n", &diagnostic(across((0, 3), (1, 0)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_columns_decode_multi_byte_and_surrogate_pairs() {
|
||||
// "é" is one UTF-16 unit; "😀" is two, and a column inside it is out of range.
|
||||
let line = "é😀@token@";
|
||||
assert_eq!(utf16_to_byte(line, 0), Some(0));
|
||||
assert_eq!(utf16_to_byte(line, 1), Some(2));
|
||||
assert_eq!(utf16_to_byte(line, 2), None);
|
||||
assert_eq!(utf16_to_byte(line, 3), Some(6));
|
||||
assert_eq!(utf16_to_byte(line, 4), Some(7));
|
||||
assert_eq!(utf16_to_byte(line, 10), Some(line.len()));
|
||||
}
|
||||
}
|
||||
@@ -2568,6 +2568,35 @@ async fn configuration_answer_resyncs_open_documents_of_opted_in_servers() {
|
||||
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn eslint_configuration_includes_workspace_folder() {
|
||||
let h = harness_configured("mock", "mk", &[("eslint", incremental_caps()), ("mock", incremental_caps())], |cfg| {
|
||||
if cfg.name == "eslint" {
|
||||
cfg.settings = Some(json!({ "workingDirectory": { "mode": "auto" } }));
|
||||
}
|
||||
});
|
||||
h.open("a.mk", "x");
|
||||
h.wait_status("eslint", ServerStatus::Ready).await;
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let items = json!({ "items": [{ "section": "" }] });
|
||||
let eslint: Value =
|
||||
h.launcher.state("eslint").peer().request("workspace/configuration", items.clone(), None).await.unwrap();
|
||||
assert_eq!(
|
||||
eslint,
|
||||
json!([{
|
||||
"flag": true,
|
||||
"nested": { "deep": 1 },
|
||||
"workingDirectory": { "mode": "auto" },
|
||||
"workspaceFolder": {
|
||||
"uri": uri_of(&h.root),
|
||||
"name": h.root.file_name().unwrap().to_string_lossy(),
|
||||
},
|
||||
}])
|
||||
);
|
||||
let other: Value = h.launcher.state("mock").peer().request("workspace/configuration", items, None).await.unwrap();
|
||||
assert_eq!(other, json!([{ "flag": true, "nested": { "deep": 1 } }]));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn settings_changes_reach_servers_without_restarts() {
|
||||
let h = harness(&[("mock", incremental_caps()), ("extra", incremental_caps())]);
|
||||
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
1056d650117bc2216ac518aa26b27cf898f58db62369ae285b9d8925ada74dff
|
||||
b24fb8d5161006104698fb07a43432601b4f16fdc4a34cc70058cbef7e973066
|
||||
+9
-3
@@ -181,9 +181,13 @@ impl commands::Guest for Misbehave {
|
||||
};
|
||||
let child = process::start(&cmd, None)?;
|
||||
// CPU work per step (loop iterations), for fuel budget tests.
|
||||
let work: u64 = arg.as_deref().and_then(|a| a.parse().ok()).unwrap_or(0);
|
||||
let arg = arg.as_deref().unwrap_or("");
|
||||
let report = !arg.starts_with("quiet:");
|
||||
let work: u64 = arg.strip_prefix("quiet:").unwrap_or(arg).parse().unwrap_or(0);
|
||||
for step in 0..25 {
|
||||
task.report(step, Some(25), Some("waiting"));
|
||||
if report {
|
||||
task.report(step, Some(25), Some("waiting"));
|
||||
}
|
||||
let mut x: u64 = 0;
|
||||
for _ in 0..work {
|
||||
x = std::hint::black_box(x.wrapping_add(1));
|
||||
@@ -195,7 +199,9 @@ impl commands::Guest for Misbehave {
|
||||
// Let it finish on its own: no kill, no slow teardown.
|
||||
child.close_stdin()?;
|
||||
let _ = child.wait(5_000);
|
||||
task.report(25, Some(25), Some("done"));
|
||||
if report {
|
||||
task.report(25, Some(25), Some("done"));
|
||||
}
|
||||
Ok(Some("still here".into()))
|
||||
}
|
||||
// `editor.write` is not granted: an error, not a trap.
|
||||
|
||||
@@ -537,6 +537,16 @@ pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, bui
|
||||
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"import": {"gradle": gradle}}}));
|
||||
}
|
||||
|
||||
/// Settings › Build Tools › Maven › Automatically download sources → jdtls
|
||||
/// `java.maven.downloadSources`.
|
||||
pub fn configure_maven_sources(cfg: &mut LanguageServerConfig, s: &Settings) {
|
||||
if cfg.name != "jdtls" {
|
||||
return;
|
||||
}
|
||||
let download = s.languages.java.maven.download_sources;
|
||||
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"maven": {"downloadSources": download}}}));
|
||||
}
|
||||
|
||||
/// Maven options from settings, placed before the goals: `-s <settings.xml>`,
|
||||
/// `-t <toolchains.xml>`, `-Dmaven.repo.local=<dir>`, `-T <count>` and `-P <profiles>`.
|
||||
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
|
||||
@@ -2350,6 +2360,25 @@ mod maven_linkage_tests {
|
||||
assert_eq!(default_maven_repository_in(home), Some(home.join(".m2/repository")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_sources_download_follows_the_setting() {
|
||||
let mut settings = Settings::default();
|
||||
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
|
||||
cfg.settings = Some(json!({"java": {"maven": {"downloadSources": true, "updateSnapshots": false}}}));
|
||||
configure_maven_sources(&mut cfg, &settings);
|
||||
assert_eq!(
|
||||
cfg.settings,
|
||||
Some(json!({"java": {"maven": {"downloadSources": false, "updateSnapshots": false}}}))
|
||||
);
|
||||
settings.languages.java.maven.download_sources = true;
|
||||
configure_maven_sources(&mut cfg, &settings);
|
||||
assert_eq!(cfg.settings.unwrap()["java"]["maven"]["downloadSources"], json!(true));
|
||||
|
||||
let mut other = custom_server("kotlin", &LanguageServerSettings::default());
|
||||
configure_maven_sources(&mut other, &settings);
|
||||
assert_eq!(other.settings, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_import_runs_the_gradle_the_ide_builds_with() {
|
||||
let root = Path::new("/p");
|
||||
|
||||
@@ -21,10 +21,63 @@ fn root(data_dir: &Path) -> PathBuf {
|
||||
data_dir.join("lsp").join("jdtls")
|
||||
}
|
||||
|
||||
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
|
||||
/// jdtls' temporary folder, inside its workspace.
|
||||
const TEMP_DIR: &str = ".tmp";
|
||||
|
||||
fn workspace(cfg: &LanguageServerConfig) -> Option<&Path> {
|
||||
cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)).map(Path::new)
|
||||
}
|
||||
|
||||
fn temp_arg(workspace: &Path) -> String {
|
||||
format!("-Djava.io.tmpdir={}", workspace.join(TEMP_DIR).to_string_lossy())
|
||||
}
|
||||
|
||||
/// Gives jdtls a temporary folder inside a workspace of ours (`<workspace>/.tmp`) unless the
|
||||
/// user's JVM arguments choose one. JDT APT copies a project's annotation processor jars into a
|
||||
/// new `jdt-apt-*` folder for each processor class loader and deletes it only when the JVM exits
|
||||
/// normally — never on Windows, where the jars are still open then — so in the system temp
|
||||
/// folder they pile up with every start; [`mark_used`] empties this one before each start.
|
||||
pub fn use_own_temp(cfg: &mut LanguageServerConfig, data_dir: &Path) {
|
||||
if cfg.name != "jdtls" || cfg.args.iter().any(|a| a.contains("-Djava.io.tmpdir=")) {
|
||||
return;
|
||||
}
|
||||
let Some(arg) = workspace(cfg).filter(|w| w.starts_with(root(data_dir))).map(temp_arg) else { return };
|
||||
// Launched directly, JVM options go before `-jar`; through the script, as `--jvm-arg=`.
|
||||
match cfg.args.iter().position(|a| a == "-jar") {
|
||||
Some(jar) => cfg.args.insert(jar, arg),
|
||||
None => cfg.args.push(format!("--jvm-arg={arg}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Empties the temporary folder [`use_own_temp`] gave the workspace. Best effort: files a server
|
||||
/// still has open on Windows stay until a later start.
|
||||
fn clear_temp(cfg: &LanguageServerConfig, workspace: &Path) {
|
||||
let arg = temp_arg(workspace);
|
||||
if !cfg.args.iter().any(|a| a.strip_prefix("--jvm-arg=").unwrap_or(a) == arg) {
|
||||
return;
|
||||
}
|
||||
let temp = workspace.join(TEMP_DIR);
|
||||
for entry in std::fs::read_dir(&temp).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
let removed = if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
std::fs::remove_dir_all(&path)
|
||||
} else {
|
||||
std::fs::remove_file(&path)
|
||||
};
|
||||
if let Err(e) = removed {
|
||||
tracing::debug!("jdtls: cannot remove temporary {}: {e}", path.display());
|
||||
}
|
||||
}
|
||||
if let Err(e) = std::fs::create_dir_all(&temp) {
|
||||
tracing::warn!("jdtls: cannot create its temporary folder {}: {e}", temp.display());
|
||||
}
|
||||
}
|
||||
|
||||
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder), and empties
|
||||
/// the workspace's temporary folder.
|
||||
pub fn mark_used(cfg: &LanguageServerConfig) {
|
||||
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
|
||||
let dir = Path::new(dir);
|
||||
let Some(dir) = workspace(cfg) else { return };
|
||||
clear_temp(cfg, dir);
|
||||
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| {
|
||||
let marker = std::fs::File::create(dir.join(USED_MARKER))?;
|
||||
marker.set_modified(SystemTime::now())
|
||||
@@ -142,6 +195,43 @@ mod tests {
|
||||
assert!(ws.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jdtls_keeps_its_temporary_files_in_its_workspace_and_starts_with_none() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = root(tmp.path()).join("p");
|
||||
let temp = format!("-Djava.io.tmpdir={}", ws.join(TEMP_DIR).to_string_lossy());
|
||||
|
||||
// Through the launcher script.
|
||||
let mut script = cfg(&ws);
|
||||
use_own_temp(&mut script, tmp.path());
|
||||
assert_eq!(script.args.last(), Some(&format!("--jvm-arg={temp}")));
|
||||
// Launched directly: a JVM option, before `-jar`.
|
||||
let mut direct = cfg(&ws);
|
||||
direct.args.splice(0..0, ["-Xmx2G".to_owned(), "-jar".to_owned(), "launcher.jar".to_owned()]);
|
||||
use_own_temp(&mut direct, tmp.path());
|
||||
assert_eq!(direct.args[..3], ["-Xmx2G".to_owned(), temp.clone(), "-jar".to_owned()]);
|
||||
|
||||
let stale = ws.join(TEMP_DIR).join("jdt-apt-1");
|
||||
std::fs::create_dir_all(&stale).unwrap();
|
||||
std::fs::write(stale.join("0_processor.jar"), "").unwrap();
|
||||
std::fs::write(ws.join(TEMP_DIR).join("file.tmp"), "").unwrap();
|
||||
mark_used(&direct);
|
||||
assert!(ws.join(TEMP_DIR).is_dir());
|
||||
assert_eq!(std::fs::read_dir(ws.join(TEMP_DIR)).unwrap().count(), 0);
|
||||
|
||||
// The user's own choice, and a workspace that is not ours, are left alone.
|
||||
let mut own = cfg(&ws);
|
||||
own.args.push("--jvm-arg=-Djava.io.tmpdir=/elsewhere".into());
|
||||
use_own_temp(&mut own, tmp.path());
|
||||
assert_eq!(own.args.iter().filter(|a| a.contains("java.io.tmpdir")).count(), 1);
|
||||
let mut theirs = cfg(&tmp.path().join("their-workspace"));
|
||||
use_own_temp(&mut theirs, tmp.path());
|
||||
assert!(!theirs.args.iter().any(|a| a.contains("java.io.tmpdir")));
|
||||
std::fs::create_dir_all(ws.join(TEMP_DIR).join("kept")).unwrap();
|
||||
mark_used(&cfg(&ws));
|
||||
assert!(ws.join(TEMP_DIR).join("kept").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
|
||||
|
||||
@@ -86,5 +86,25 @@ fn excluded_subtrees(c: &mut Criterion) {
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(benches, bench, excluded_subtrees);
|
||||
// Lockfile-sized files with a hit on every line, one per folder so every walker
|
||||
// thread is inside its own dense file when the 10 000-match default limit is reached.
|
||||
fn dense_files(c: &mut Criterion) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for module in 0..24 {
|
||||
let sub = dir.path().join(format!("packages/p{module}"));
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
let mut text = String::with_capacity(2 << 20);
|
||||
for i in 0..40_000u32 {
|
||||
text.push_str(&format!(" \"version\": \"{}.{}.{module}\",\n", i / 100, i % 100));
|
||||
}
|
||||
std::fs::write(sub.join("package-lock.json"), text).unwrap();
|
||||
}
|
||||
let q = query("version", false);
|
||||
let mut group = c.benchmark_group("search_dense_files");
|
||||
group.sample_size(15);
|
||||
group.bench_function("24x40k_limit", |b| b.iter(|| black_box(run(dir.path(), &q))));
|
||||
group.finish();
|
||||
}
|
||||
|
||||
criterion_group!(benches, bench, excluded_subtrees, dense_files);
|
||||
criterion_main!(benches);
|
||||
+109
-20
@@ -22,6 +22,9 @@ pub(crate) const DEFAULT_MAX_MATCHES: u32 = 10_000;
|
||||
/// How many matched lines a sink handles between cancellation-token checks
|
||||
/// (reads from disk check on every buffer refill).
|
||||
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;
|
||||
|
||||
pub(crate) struct Request<'a> {
|
||||
pub root: &'a Path,
|
||||
@@ -87,6 +90,11 @@ impl Control<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns matches claimed for a file whose matches are then dropped.
|
||||
fn release(&self, n: u32) {
|
||||
self.matches.fetch_sub(n, Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
@@ -322,24 +330,16 @@ impl Ctx<'_> {
|
||||
None => self.search_disk(path, matcher, searcher, &mut sink),
|
||||
},
|
||||
};
|
||||
if let Err(err) = result {
|
||||
if !self.ctl.stopped() {
|
||||
tracing::debug!("search {}: {err}", path.display());
|
||||
}
|
||||
if sink.lines.is_empty() || self.ctl.cancelled.load(Relaxed) {
|
||||
return;
|
||||
}
|
||||
if let Err(err) = result
|
||||
&& !self.ctl.stopped()
|
||||
{
|
||||
tracing::debug!("search {}: {err}", path.display());
|
||||
}
|
||||
if sink.binary || sink.lines.is_empty() || self.ctl.cancelled.load(Relaxed) {
|
||||
self.ctl.release(sink.claimed);
|
||||
return;
|
||||
}
|
||||
let found = u32::try_from(sink.count).unwrap_or(u32::MAX);
|
||||
let granted = self.ctl.reserve(found);
|
||||
if granted < found {
|
||||
self.ctl.limit_hit.store(true, Relaxed);
|
||||
self.ctl.stop.store(true, Relaxed);
|
||||
truncate(&mut sink.lines, granted as usize);
|
||||
}
|
||||
sink.settle();
|
||||
if sink.lines.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -364,14 +364,17 @@ impl Ctx<'_> {
|
||||
} else {
|
||||
!reader.is_utf8()
|
||||
};
|
||||
if !decode || self.ctl.stopped() {
|
||||
// A stopped search needs the decoded text only to fill what the byte search claimed.
|
||||
if !decode || (self.ctl.stopped() && sink.claimed == 0) {
|
||||
return result;
|
||||
}
|
||||
let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else {
|
||||
sink.binary = true;
|
||||
return Ok(());
|
||||
};
|
||||
let claimed = sink.claimed;
|
||||
*sink = FileSink::new(matcher, &self.ctl, None);
|
||||
sink.claimed = claimed;
|
||||
searcher.search_slice(matcher, text.as_bytes(), sink)
|
||||
}
|
||||
}
|
||||
@@ -389,8 +392,11 @@ struct FileSink<'a> {
|
||||
matcher: &'a RegexMatcher,
|
||||
ctl: &'a Control<'a>,
|
||||
lines: Vec<LineMatch>,
|
||||
/// Match ranges collected so far.
|
||||
count: usize,
|
||||
/// Match ranges kept so far.
|
||||
count: u32,
|
||||
/// Matches claimed from the shared budget: up to `count`, or more while a decoded
|
||||
/// file is searched again under the claim of its byte search.
|
||||
claimed: u32,
|
||||
binary: bool,
|
||||
ticks: u32,
|
||||
/// Scratch buffers reused across lines.
|
||||
@@ -411,6 +417,7 @@ impl<'a> FileSink<'a> {
|
||||
ctl,
|
||||
lines: Vec::new(),
|
||||
count: 0,
|
||||
claimed: 0,
|
||||
binary: false,
|
||||
ticks: 0,
|
||||
found: Vec::new(),
|
||||
@@ -418,6 +425,36 @@ impl<'a> FileSink<'a> {
|
||||
context,
|
||||
}
|
||||
}
|
||||
|
||||
/// Claims the matches kept since the last claim. When the budget cannot take them
|
||||
/// all, keeps the ones it can, marks the limit hit and returns false.
|
||||
fn claim(&mut self) -> bool {
|
||||
if self.count <= self.claimed {
|
||||
return true;
|
||||
}
|
||||
let unclaimed = self.count - self.claimed;
|
||||
let granted = self.ctl.reserve(unclaimed);
|
||||
self.claimed += granted;
|
||||
if granted == unclaimed {
|
||||
return true;
|
||||
}
|
||||
self.ctl.limit_hit.store(true, Relaxed);
|
||||
self.ctl.stop.store(true, Relaxed);
|
||||
truncate(&mut self.lines, self.claimed as usize);
|
||||
self.count = self.claimed;
|
||||
false
|
||||
}
|
||||
|
||||
/// Makes the claim match the matches kept once the file is done: claims the rest, or
|
||||
/// gives back the part of a byte search's claim the decoded text did not use.
|
||||
fn settle(&mut self) {
|
||||
if self.count < self.claimed {
|
||||
self.ctl.release(self.claimed - self.count);
|
||||
self.claimed = self.count;
|
||||
} else {
|
||||
self.claim();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
|
||||
@@ -431,7 +468,9 @@ impl Sink for FileSink<'_> {
|
||||
|
||||
fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result<bool, io::Error> {
|
||||
self.ticks += 1;
|
||||
if self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop()) {
|
||||
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.
|
||||
if stop && (self.count >= self.claimed || self.ctl.cancelled.load(Relaxed)) {
|
||||
return Ok(false);
|
||||
}
|
||||
let buffer = m.buffer();
|
||||
@@ -475,7 +514,7 @@ impl Sink for FileSink<'_> {
|
||||
ranges.push((a - line_start, b - line_start));
|
||||
}
|
||||
if !ranges.is_empty() {
|
||||
self.count += ranges.len();
|
||||
self.count = self.count.saturating_add(u32::try_from(ranges.len()).unwrap_or(u32::MAX));
|
||||
let line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
|
||||
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
|
||||
}
|
||||
@@ -485,7 +524,8 @@ impl Sink for FileSink<'_> {
|
||||
self.found = found;
|
||||
self.ranges = ranges;
|
||||
// One match beyond the remaining budget is enough to know the limit is hit.
|
||||
Ok(self.count <= self.ctl.remaining() as usize)
|
||||
let unclaimed = self.count.saturating_sub(self.claimed);
|
||||
Ok(if unclaimed >= CLAIM_BATCH || unclaimed > self.ctl.remaining() { self.claim() } else { true })
|
||||
}
|
||||
|
||||
fn binary_data(&mut self, _searcher: &Searcher, _offset: u64) -> Result<bool, io::Error> {
|
||||
@@ -642,3 +682,52 @@ mod walk_tests {
|
||||
assert!(seen.lock().unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
|
||||
fn control(cancel: &CancellationToken, max: u32) -> Control<'_> {
|
||||
Control {
|
||||
cancel,
|
||||
stop: AtomicBool::new(false),
|
||||
cancelled: AtomicBool::new(false),
|
||||
limit_hit: AtomicBool::new(false),
|
||||
matches: AtomicU32::new(0),
|
||||
files: AtomicU32::new(0),
|
||||
max,
|
||||
}
|
||||
}
|
||||
|
||||
/// Searches `lines` matching lines without finishing the file, like a walker thread mid-file.
|
||||
fn scan<'a>(ctl: &'a Control<'a>, matcher: &'a RegexMatcher, lines: usize) -> FileSink<'a> {
|
||||
let mut sink = FileSink::new(matcher, ctl, None);
|
||||
let mut searcher = SearcherBuilder::new().line_number(true).build();
|
||||
searcher.search_slice(matcher, "x\n".repeat(lines).as_bytes(), &mut sink).unwrap();
|
||||
sink
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_in_flight_never_hold_more_matches_than_the_budget() {
|
||||
let cancel = CancellationToken::new();
|
||||
let ctl = control(&cancel, 100);
|
||||
let matcher = RegexMatcher::new("x").unwrap();
|
||||
let (first, second) = (scan(&ctl, &matcher, 150), scan(&ctl, &matcher, 150));
|
||||
assert_eq!((first.lines.len(), second.lines.len()), (100, 0));
|
||||
assert_eq!(ctl.matches.load(Relaxed), 100);
|
||||
assert!(ctl.limit_hit.load(Relaxed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unclaimed_matches_of_a_file_in_flight_stay_within_the_budget() {
|
||||
let cancel = CancellationToken::new();
|
||||
let ctl = control(&cancel, 1000);
|
||||
let matcher = RegexMatcher::new("x").unwrap();
|
||||
let mut first = scan(&ctl, &matcher, 40);
|
||||
let second = scan(&ctl, &matcher, 2000);
|
||||
assert_eq!((first.lines.len(), second.lines.len()), (40, 1000));
|
||||
assert!(!first.claim());
|
||||
assert_eq!((first.lines.len(), ctl.matches.load(Relaxed)), (0, 1000));
|
||||
assert!(ctl.limit_hit.load(Relaxed));
|
||||
}
|
||||
}
|
||||
@@ -314,6 +314,25 @@ fn match_limit() {
|
||||
assert_eq!(summary.matches, 14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_limit_across_parallel_files() {
|
||||
// One file per folder, so several walker threads search at once.
|
||||
let content = "x\n".repeat(50);
|
||||
let names: Vec<String> = (0..16).map(|i| format!("m{i}/a.txt")).collect();
|
||||
let files: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), content.as_bytes())).collect();
|
||||
let p = project(&files);
|
||||
for _ in 0..20 {
|
||||
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 800, ..query("x") });
|
||||
assert!(!summary.limit_hit);
|
||||
assert_eq!((total(&views), summary.matches, summary.files), (800, 800, 16));
|
||||
|
||||
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 799, ..query("x") });
|
||||
assert!(summary.limit_hit);
|
||||
assert_eq!((total(&views), summary.matches), (799, 799));
|
||||
assert_eq!(summary.files as usize, views.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_limit_is_ten_thousand() {
|
||||
let content = "a\n".repeat(10_050);
|
||||
@@ -775,6 +794,31 @@ fn non_utf8_files_are_searched_as_text() {
|
||||
assert_eq!(views[0].matches[0].ranges, [(13, 20), (21, 28), (29, 36)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropped_matches_give_back_their_budget() {
|
||||
// Matches claimed before a late NUL (binary) or late GBK bytes (searched again as text).
|
||||
let head = b"needle\n".repeat(100);
|
||||
let filler = b"a".repeat(200_000);
|
||||
let binary = [head.as_slice(), &filler, b"\0\n"].concat();
|
||||
let late_gbk = [head.as_slice(), &filler, b"\n", &gbk("中文\n")].concat();
|
||||
// One project each: a thread's searcher keeps its grown buffer for the next file.
|
||||
for (file, bytes, found) in [("bin.dat", binary, 0), ("late.txt", late_gbk, 100)] {
|
||||
let p = project(&[(file, &bytes)]);
|
||||
let (views, summary) = run(p.path(), &query("needle"));
|
||||
assert_eq!((total(&views), summary.matches), (found, found as u32), "{file}");
|
||||
assert!(!summary.limit_hit);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_utf8_files_past_the_limit_show_decoded_text() {
|
||||
let p = project(&[("a.txt", &gbk(&"x 中文\n".repeat(200)))]);
|
||||
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 100, ..query("x") });
|
||||
assert!(summary.limit_hit);
|
||||
assert_eq!((total(&views), summary.matches), (100, 100));
|
||||
assert!(views[0].matches.iter().all(|m| m.text == "x 中文"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_utf8_files_use_the_given_decoder() {
|
||||
// Text too short to detect reliably decodes with the configured encoding.
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
//! `cargo bench -p ide-text`: change sets and coordinate conversion on a 1 MB document.
|
||||
//! `cargo bench -p ide-text`: change sets and coordinate conversion on a 1 MB document
|
||||
//! (and a 5 MB one where whole-document copies would show).
|
||||
|
||||
use criterion::{BatchSize, Criterion, black_box, criterion_group, criterion_main};
|
||||
use ide_core::{ChangeSet, Pos, TextChange};
|
||||
use ide_text::Document;
|
||||
|
||||
/// ~1 MB of code-like text with some non-ASCII content.
|
||||
fn sample_text() -> String {
|
||||
let mut s = String::with_capacity(1 << 20);
|
||||
/// ~`bytes` of code-like text with some non-ASCII content.
|
||||
fn sample_text(bytes: usize) -> String {
|
||||
let mut s = String::with_capacity(bytes);
|
||||
let mut i = 0u32;
|
||||
while s.len() < 1 << 20 {
|
||||
while s.len() < bytes {
|
||||
s.push_str(&format!(" let value_{i} = compute(\"héllo 😀\", {i}) + other_{i};\n"));
|
||||
i += 1;
|
||||
}
|
||||
@@ -47,7 +48,7 @@ fn change_set(doc: &Document, rng: &mut Lcg, n: usize) -> ChangeSet {
|
||||
}
|
||||
|
||||
fn bench(c: &mut Criterion) {
|
||||
let text = sample_text();
|
||||
let text = sample_text(1 << 20);
|
||||
c.bench_function("text/open_1mb", |b| b.iter(|| Document::new(black_box(&text))));
|
||||
|
||||
let base = Document::new(&text);
|
||||
@@ -77,6 +78,11 @@ fn bench(c: &mut Criterion) {
|
||||
c.bench_function("text/diff_two_edits_1mb", |b| b.iter(|| base.diff(black_box(&two_edits))));
|
||||
let every_line = text.replace("compute", "calculate");
|
||||
c.bench_function("text/diff_every_line_1mb", |b| b.iter(|| base.diff(black_box(&every_line))));
|
||||
let large_text = sample_text(5 << 20);
|
||||
let large = Document::new(&large_text);
|
||||
let one_edit = large_text.replacen("value_40000 ", "renamed_40000 ", 1);
|
||||
assert_ne!(one_edit, large_text);
|
||||
c.bench_function("text/diff_one_edit_5mb", |b| b.iter(|| large.diff(black_box(&one_edit))));
|
||||
c.bench_function("text/offset_to_pos_round_trip", |b| {
|
||||
let mut rng = Lcg(3);
|
||||
let len = base.len_utf16();
|
||||
|
||||
+112
-4
@@ -93,6 +93,54 @@ fn common_ends(a: &str, b: &str) -> (usize, usize) {
|
||||
(prefix, suffix)
|
||||
}
|
||||
|
||||
/// [`common_ends`] of the rope's text and `b`, walking the rope's chunks instead
|
||||
/// of copying it: whole chunks compare as slices, bytes only around the mismatch.
|
||||
fn rope_common_ends(rope: &ropey::Rope, b: &str) -> (usize, usize) {
|
||||
let bb = b.as_bytes();
|
||||
let mut prefix = 0;
|
||||
for chunk in rope.chunks() {
|
||||
let n = common_prefix_len(chunk.as_bytes(), &bb[prefix..]);
|
||||
prefix += n;
|
||||
if n < chunk.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
prefix = rope.char_to_byte(rope.byte_to_char(prefix));
|
||||
let len = rope.len_bytes();
|
||||
let limit = len.min(bb.len()) - prefix;
|
||||
let mut suffix = 0;
|
||||
let mut chunks = rope.chunks_at_byte(len).0.reversed();
|
||||
while suffix < limit {
|
||||
let Some(chunk) = chunks.next() else { break };
|
||||
let n = common_suffix_len(chunk.as_bytes(), &bb[..bb.len() - suffix]).min(limit - suffix);
|
||||
suffix += n;
|
||||
if n < chunk.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let ch = rope.byte_to_char(len - suffix);
|
||||
if rope.char_to_byte(ch) < len - suffix {
|
||||
suffix = len - rope.char_to_byte(ch + 1);
|
||||
}
|
||||
(prefix, suffix)
|
||||
}
|
||||
|
||||
fn common_prefix_len(a: &[u8], b: &[u8]) -> usize {
|
||||
let n = a.len().min(b.len());
|
||||
if a[..n] == b[..n] {
|
||||
return n;
|
||||
}
|
||||
a.iter().zip(b).take_while(|(x, y)| x == y).count()
|
||||
}
|
||||
|
||||
fn common_suffix_len(a: &[u8], b: &[u8]) -> usize {
|
||||
let n = a.len().min(b.len());
|
||||
if a[a.len() - n..] == b[b.len() - n..] {
|
||||
return n;
|
||||
}
|
||||
a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count()
|
||||
}
|
||||
|
||||
/// Byte offset of each line, then the total length.
|
||||
fn line_starts(lines: &[&str]) -> Vec<usize> {
|
||||
let mut at = 0;
|
||||
@@ -396,9 +444,8 @@ impl Document {
|
||||
/// Past `deadline` the regions get coarser, never wrong.
|
||||
fn diff_until(&self, text: &str, deadline: Instant) -> ChangeSet {
|
||||
let new = normalize_line_endings(text);
|
||||
let old = self.rope.to_string();
|
||||
let (prefix, suffix) = common_ends(&old, &new);
|
||||
let old_rest = &old[prefix..old.len() - suffix];
|
||||
let (prefix, suffix) = rope_common_ends(&self.rope, &new);
|
||||
let old_rest = String::from(self.rope.byte_slice(prefix..self.rope.len_bytes() - suffix));
|
||||
let new_rest = &new[prefix..new.len() - suffix];
|
||||
|
||||
let old_lines: Vec<&str> = old_rest.split_inclusive('\n').collect();
|
||||
@@ -407,7 +454,7 @@ impl Document {
|
||||
let new_starts = line_starts(&new_lines);
|
||||
|
||||
let mut changes = Vec::new();
|
||||
let mut utf16_at = utf16_len(&old[..prefix]);
|
||||
let mut utf16_at = self.byte_to_offset(prefix);
|
||||
let mut old_at = 0;
|
||||
let mut region: Option<(LineRange, LineRange)> = None;
|
||||
let ops =
|
||||
@@ -710,6 +757,67 @@ mod tests {
|
||||
assert_eq!(set.changes, vec![tc(3, 6, "ONE"), tc(15, 18, "TWO")]);
|
||||
}
|
||||
|
||||
/// The rope scan must trim exactly what `common_ends` trims on the copied text.
|
||||
fn assert_rope_ends(old: &str, new: &str) {
|
||||
let doc = Document::new(old);
|
||||
let (prefix, suffix) = rope_common_ends(&doc.rope, new);
|
||||
assert_eq!((prefix, suffix), common_ends(old, new), "{old:?} -> {new:?}");
|
||||
assert_eq!(doc.byte_to_offset(prefix), utf16_len(&old[..prefix]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rope_common_ends_matches_common_ends() {
|
||||
let unit = "héllo 😀 wörld, ©\n";
|
||||
let base = unit.repeat(400);
|
||||
assert!(Document::new(&base).rope.chunks().count() > 4, "spans several chunks");
|
||||
for (old, new) in [("", ""), ("", "abc"), ("abc", ""), ("é", "è"), ("😀", "😁"), ("é", "©")] {
|
||||
assert_rope_ends(old, new);
|
||||
}
|
||||
assert_rope_ends(&base, &base);
|
||||
assert_rope_ends(&base, "");
|
||||
assert_rope_ends("", &base);
|
||||
assert_rope_ends(&base, &format!("{base}tail"));
|
||||
assert_rope_ends(&format!("{base}tail"), &base);
|
||||
assert_rope_ends(&base, &base[unit.len()..]);
|
||||
assert_rope_ends(&"a".repeat(5000), &"a".repeat(4999));
|
||||
assert_rope_ends(&"ab".repeat(3000), &"ab".repeat(3001));
|
||||
assert_rope_ends(&"😀".repeat(2000), &"😀".repeat(1999));
|
||||
let boundaries: Vec<usize> = base.char_indices().map(|(i, _)| i).step_by(7).collect();
|
||||
for at in boundaries {
|
||||
let c = base[at..].chars().next().unwrap();
|
||||
let rest = &base[at + c.len_utf8()..];
|
||||
let swapped = match c {
|
||||
'é' => 'è', // same lead byte
|
||||
'😀' => '😁', // differs in the last byte only
|
||||
'©' => 'é', // same trailing byte
|
||||
_ => 'X',
|
||||
};
|
||||
let swap = format!("{}{swapped}{rest}", &base[..at]);
|
||||
assert_rope_ends(&base, &swap);
|
||||
// Deleting a char further on stops the suffix scan far from the prefix.
|
||||
let mut far = at + (swap.len() - at) / 2;
|
||||
while !swap.is_char_boundary(far) {
|
||||
far += 1;
|
||||
}
|
||||
let gone = swap[far..].chars().next().unwrap().len_utf8();
|
||||
assert_rope_ends(&base, &format!("{}{}", &swap[..far], &swap[far + gone..]));
|
||||
assert_rope_ends(&base, &format!("{}{rest}", &base[..at]));
|
||||
assert_rope_ends(&base, &format!("{}é{c}{rest}", &base[..at]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_of_a_large_document_counts_utf16_and_normalizes_crlf() {
|
||||
let old = "😀 héllo\n".repeat(2000);
|
||||
let at = old.len() / 2;
|
||||
let new = format!("{}X{}", &old[..at], &old[at..]);
|
||||
let doc = Document::new(&old);
|
||||
let expected = vec![tc(utf16_len(&old[..at]), utf16_len(&old[..at]), "X")];
|
||||
assert_eq!(doc.diff(&new).changes, expected);
|
||||
assert_eq!(doc.diff(&new.replace('\n', "\r\n")).changes, expected);
|
||||
assert!(doc.diff(&old.replace('\n', "\r\n")).changes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_past_its_deadline_is_coarser_but_still_correct() {
|
||||
let old = numbered_lines(5000);
|
||||
|
||||
+257
-9
@@ -239,7 +239,7 @@ fn event_handler(state: Weak<DirState>, polled: bool) -> impl FnMut(notify::Resu
|
||||
Ok(event) if !is_change_event(&event) => {}
|
||||
Ok(event) if polled && is_dir_touch(&event) => {}
|
||||
Ok(event) => {
|
||||
state.queue.lock().push((event, Instant::now()));
|
||||
state.queue.lock().push(event, Instant::now());
|
||||
state.wake.notify_one();
|
||||
}
|
||||
Err(e) => tracing::warn!("file watcher: {e}"),
|
||||
@@ -280,13 +280,53 @@ fn watcher_error(what: &str, error: notify::Error) -> IdeError {
|
||||
}
|
||||
}
|
||||
|
||||
/// Only adjacent identical file modifications are redundant before classification.
|
||||
/// Keep the arrival window separately so compaction cannot extend MAX_DELAY.
|
||||
#[derive(Default)]
|
||||
struct PendingEvents {
|
||||
events: Vec<Event>,
|
||||
first: Option<Instant>,
|
||||
last: Option<Instant>,
|
||||
received: usize,
|
||||
}
|
||||
|
||||
impl PendingEvents {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.events.is_empty()
|
||||
}
|
||||
|
||||
fn push(&mut self, event: Event, now: Instant) {
|
||||
self.first.get_or_insert(now);
|
||||
self.last = Some(now);
|
||||
self.received += 1;
|
||||
let redundant = event.paths.len() == 1
|
||||
&& event.flag().is_none()
|
||||
&& matches!(event.kind, EventKind::Modify(ModifyKind::Any | ModifyKind::Data(_) | ModifyKind::Metadata(_)))
|
||||
&& self.events.last().is_some_and(|previous| {
|
||||
// Reject different spellings before Path's component-wise equality.
|
||||
// Keeping a normalized alias is safe; only exact duplicates compact.
|
||||
previous.paths.len() == 1
|
||||
&& previous.paths[0].as_os_str() == event.paths[0].as_os_str()
|
||||
&& previous == &event
|
||||
&& previous.attrs.process_id() == event.attrs.process_id()
|
||||
});
|
||||
if !redundant {
|
||||
self.events.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
fn deadline(&self) -> Option<Instant> {
|
||||
Some((self.last? + DEBOUNCE).min(self.first? + MAX_DELAY))
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared with the notify callback (weakly) and the debounce thread.
|
||||
struct DirState {
|
||||
filter: EventFilter,
|
||||
mode: WatchMode,
|
||||
watcher: Mutex<Option<Box<dyn notify::Watcher + Send>>>,
|
||||
watched: Mutex<HashSet<PathBuf>>,
|
||||
queue: Mutex<Vec<(notify::Event, Instant)>>,
|
||||
queue: Mutex<PendingEvents>,
|
||||
wake: Condvar,
|
||||
stop: AtomicBool,
|
||||
/// Set when a `watch()` call reports the OS watch limit (inotify
|
||||
@@ -317,34 +357,48 @@ impl DirState {
|
||||
if self.stopped() {
|
||||
return;
|
||||
}
|
||||
let first = q[0].1;
|
||||
|
||||
loop {
|
||||
let last = q.last().map_or(first, |e| e.1);
|
||||
let deadline = q.deadline().expect("nonempty event queue");
|
||||
let now = Instant::now();
|
||||
if self.stopped() {
|
||||
return;
|
||||
}
|
||||
if now >= last + DEBOUNCE || now >= first + MAX_DELAY {
|
||||
if now >= deadline {
|
||||
break;
|
||||
}
|
||||
let wait = (last + DEBOUNCE).min(first + MAX_DELAY) - now;
|
||||
let wait = deadline - now;
|
||||
self.wake.wait_for(&mut q, wait);
|
||||
}
|
||||
std::mem::take(&mut *q)
|
||||
};
|
||||
// A scan may publish a path before its create event is delivered:
|
||||
// keep create + remove pairs so the consumer still sees the removal.
|
||||
let events: Vec<Event> = events.into_iter().map(|(e, _)| e).collect();
|
||||
let (mut batch, rule_dirs) = self.filter.batch_detailed(&events);
|
||||
let processing = Instant::now();
|
||||
let queue_age_ms = processing.duration_since(events.first.expect("nonempty event queue")).as_millis();
|
||||
let received = events.received;
|
||||
let queued = events.events.len();
|
||||
let (mut batch, rule_dirs) = self.filter.batch_detailed(&events.events);
|
||||
if self.mode == WatchMode::PerDirectory {
|
||||
self.update_watches(&mut batch, &rule_dirs);
|
||||
// Again once polling: a refused directory was not read, and
|
||||
// the poller won't report what is already in it.
|
||||
polled = polled || self.poll_if_exhausted(|| self.update_watches(&mut batch, &rule_dirs));
|
||||
}
|
||||
let processing_ms = processing.elapsed().as_millis();
|
||||
let callback = Instant::now();
|
||||
if !batch.is_empty() && !self.stopped() {
|
||||
emit(&batch);
|
||||
}
|
||||
tracing::debug!(
|
||||
received,
|
||||
queued,
|
||||
coalesced = received - queued,
|
||||
queue_age_ms,
|
||||
processing_ms,
|
||||
callback_ms = callback.elapsed().as_millis(),
|
||||
"file watcher batch"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -785,6 +839,10 @@ impl EventFilter {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "watch_pipeline_tests.rs"]
|
||||
mod pipeline_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -794,6 +852,196 @@ mod tests {
|
||||
Event { kind, paths, attrs: Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_modifications_keep_the_original_debounce_window() {
|
||||
let start = Instant::now();
|
||||
// ReadDirectoryChangesW reports ordinary Windows writes as Modify(Any).
|
||||
let event = ev(EventKind::Modify(ModifyKind::Any), vec!["file.rs".into()]);
|
||||
let mut pending = PendingEvents::default();
|
||||
assert_eq!(pending.deadline(), None);
|
||||
for n in 0..10_000 {
|
||||
pending.push(event.clone(), start + Duration::from_micros(n * 95));
|
||||
}
|
||||
assert_eq!(pending.received, 10_000);
|
||||
assert_eq!(pending.events.len(), 1);
|
||||
assert_eq!(pending.first, Some(start));
|
||||
assert_eq!(pending.last, Some(start + Duration::from_micros(9_999 * 95)));
|
||||
assert_eq!(pending.deadline(), Some(start + MAX_DELAY));
|
||||
let drained = std::mem::take(&mut pending);
|
||||
assert_eq!(drained.events, vec![event.clone()]);
|
||||
assert!(pending.is_empty());
|
||||
assert_eq!(pending.deadline(), None);
|
||||
pending.push(event, start + MAX_DELAY);
|
||||
assert_eq!(pending.received, 1);
|
||||
assert_eq!(pending.deadline(), Some(start + MAX_DELAY + DEBOUNCE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_events_preserve_boundaries_and_attributes() {
|
||||
let now = Instant::now();
|
||||
let modify = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec!["a".into()]);
|
||||
let variants = [
|
||||
modify.clone().set_tracker(1),
|
||||
modify.clone().set_info("backend detail"),
|
||||
modify.clone().set_process_id(2),
|
||||
modify.clone().set_flag(notify::event::Flag::Rescan),
|
||||
modify.clone().add_path("b".into()),
|
||||
ev(EventKind::Create(CreateKind::File), vec!["a".into()]),
|
||||
ev(EventKind::Remove(RemoveKind::File), vec!["a".into()]),
|
||||
ev(EventKind::Modify(ModifyKind::Name(RenameMode::Both)), vec!["a".into(), "b".into()]),
|
||||
ev(EventKind::Modify(ModifyKind::Name(RenameMode::From)), vec!["a".into()]),
|
||||
ev(EventKind::Modify(ModifyKind::Name(RenameMode::To)), vec!["a".into()]),
|
||||
ev(EventKind::Any, vec!["a".into()]),
|
||||
];
|
||||
for middle in variants {
|
||||
let events = vec![modify.clone(), middle, modify.clone()];
|
||||
let mut pending = PendingEvents::default();
|
||||
for event in &events {
|
||||
pending.push(event.clone(), now);
|
||||
}
|
||||
assert_eq!(pending.events, events);
|
||||
}
|
||||
let mut interleaved = PendingEvents::default();
|
||||
for event in [
|
||||
modify.clone(),
|
||||
modify.clone().set_kind(EventKind::Create(CreateKind::File)).add_path("b".into()),
|
||||
modify.clone(),
|
||||
] {
|
||||
interleaved.push(event, now);
|
||||
}
|
||||
assert_eq!(interleaved.events.len(), 3);
|
||||
let mut interleaved = PendingEvents::default();
|
||||
for event in [modify.clone(), ev(modify.kind, vec!["b".into()]), modify.clone()] {
|
||||
interleaved.push(event, now);
|
||||
}
|
||||
assert_eq!(interleaved.events.len(), 3);
|
||||
for event in [
|
||||
modify.set_flag(notify::event::Flag::Rescan),
|
||||
ev(EventKind::Modify(ModifyKind::Name(RenameMode::From)), vec!["a".into()]),
|
||||
] {
|
||||
let mut pending = PendingEvents::default();
|
||||
pending.push(event.clone(), now);
|
||||
pending.push(event, now);
|
||||
assert_eq!(pending.events.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_keeps_different_spellings_of_the_same_path() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir(root.join("src")).unwrap();
|
||||
std::fs::write(root.join("src/a.rs"), "x").unwrap();
|
||||
let paths = [root.join("src/a.rs"), root.join("src/./a.rs"), root.join("src//a.rs")];
|
||||
assert_eq!(paths[0], paths[1]);
|
||||
assert_ne!(paths[0].as_os_str(), paths[1].as_os_str());
|
||||
let events: Vec<_> =
|
||||
paths.into_iter().map(|path| Event::new(EventKind::Modify(ModifyKind::Any)).add_path(path)).collect();
|
||||
let mut pending = PendingEvents::default();
|
||||
for event in &events {
|
||||
pending.push(event.clone(), Instant::now());
|
||||
}
|
||||
assert_eq!(pending.events.len(), events.len());
|
||||
assert_same_batch(
|
||||
&EventFilter::new(root.clone(), &[]).batch(&events),
|
||||
&EventFilter::new(root, &[]).batch(&pending.events),
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_same_batch(left: &FsBatch, right: &FsBatch) {
|
||||
assert_eq!(left.created, right.created);
|
||||
assert_eq!(left.modified, right.modified);
|
||||
assert_eq!(left.removed, right.removed);
|
||||
assert_eq!(left.vcs, right.vcs);
|
||||
assert_eq!(left.excluded_dirs, right.excluded_dirs);
|
||||
assert_eq!(left.ignored, right.ignored);
|
||||
assert_eq!(left.ignore_rules, right.ignore_rules);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_compaction_matches_uncompressed_change_sequences() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir(root.join(".git")).unwrap();
|
||||
std::fs::create_dir(root.join("excluded")).unwrap();
|
||||
std::fs::write(root.join(".gitignore"), "*.ignored\n").unwrap();
|
||||
let excludes = vec!["excluded".to_owned()];
|
||||
let kinds = [
|
||||
EventKind::Create(CreateKind::File),
|
||||
EventKind::Remove(RemoveKind::File),
|
||||
EventKind::Modify(ModifyKind::Any),
|
||||
EventKind::Modify(ModifyKind::Data(DataChange::Content)),
|
||||
EventKind::Modify(ModifyKind::Metadata(MetadataKind::WriteTime)),
|
||||
EventKind::Modify(ModifyKind::Name(RenameMode::From)),
|
||||
EventKind::Modify(ModifyKind::Name(RenameMode::To)),
|
||||
];
|
||||
// All four-event histories, with both present and absent final state.
|
||||
for rel in ["source.rs", "file.ignored", "excluded/source.rs", ".git/HEAD"] {
|
||||
let path = root.join(rel);
|
||||
for exists in [false, true] {
|
||||
if exists {
|
||||
std::fs::write(&path, "x").unwrap();
|
||||
}
|
||||
for code in 0..kinds.len().pow(4) {
|
||||
let mut code = code;
|
||||
let mut events = Vec::new();
|
||||
let mut pending = PendingEvents::default();
|
||||
for _ in 0..4 {
|
||||
let event = ev(kinds[code % kinds.len()], vec![path.clone()]);
|
||||
code /= kinds.len();
|
||||
// Each event is repeated to exercise compaction after transitions.
|
||||
for _ in 0..2 {
|
||||
events.push(event.clone());
|
||||
pending.push(event.clone(), Instant::now());
|
||||
}
|
||||
}
|
||||
let plain = EventFilter::new(root.clone(), &excludes).batch(&events);
|
||||
let compact = EventFilter::new(root.clone(), &excludes).batch(&pending.events);
|
||||
assert_same_batch(&plain, &compact);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_compaction_keeps_rule_reload_and_rename_endpoints() {
|
||||
let excludes = vec!["excluded".to_owned()];
|
||||
for rule in [".gitignore", ".ignore", ".git/info/exclude"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join(".git/info")).unwrap();
|
||||
std::fs::create_dir(root.join("excluded")).unwrap();
|
||||
std::fs::write(root.join(rule), "").unwrap();
|
||||
std::fs::write(root.join("file.ignored"), "x").unwrap();
|
||||
let plain = EventFilter::new(root.clone(), &excludes);
|
||||
let compact = EventFilter::new(root.clone(), &excludes);
|
||||
let touch = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec![root.join("file.ignored")]);
|
||||
for filter in [&plain, &compact] {
|
||||
assert_eq!(filter.batch(std::slice::from_ref(&touch)).modified, vec![root.join("file.ignored")]);
|
||||
}
|
||||
std::fs::write(root.join(rule), "*.ignored\n").unwrap();
|
||||
let mut events = Vec::new();
|
||||
for path in ["file.ignored", rule] {
|
||||
let event = ev(EventKind::Modify(ModifyKind::Data(DataChange::Content)), vec![root.join(path)]);
|
||||
events.extend([event.clone(), event]);
|
||||
}
|
||||
events.push(ev(
|
||||
EventKind::Modify(ModifyKind::Name(RenameMode::Both)),
|
||||
vec![root.join("excluded/old.rs"), root.join("new.rs")],
|
||||
));
|
||||
std::fs::write(root.join("new.rs"), "x").unwrap();
|
||||
let mut pending = PendingEvents::default();
|
||||
for event in &events {
|
||||
pending.push(event.clone(), Instant::now());
|
||||
}
|
||||
let expected = plain.batch(&events);
|
||||
assert_eq!(expected.ignore_rules, vec![root.clone()]);
|
||||
assert_eq!(expected.ignored, vec![root.join("file.ignored")]);
|
||||
assert!(!expected.modified.contains(&root.join("file.ignored")));
|
||||
assert_same_batch(&expected, &compact.batch(&pending.events));
|
||||
}
|
||||
}
|
||||
|
||||
const TRANSIENT_PATHS: &[&str] = &["fresh.txt", "src/fresh.rs", "src/tasks/fresh.py"];
|
||||
|
||||
/// Delivers a whole debounce window without depending on OS scheduling.
|
||||
@@ -1530,7 +1778,7 @@ mod tests {
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, "x").unwrap();
|
||||
let created = Event::new(EventKind::Create(notify::event::CreateKind::Folder)).add_path(root.join("new"));
|
||||
inner.state.queue.lock().push((created, Instant::now()));
|
||||
inner.state.queue.lock().push(created, Instant::now());
|
||||
inner.state.wake.notify_all();
|
||||
// Written before polling took over, so the poller never reports it.
|
||||
assert!(wait_for(&batches, |b| all_paths(b).contains(&file)), "{:?}", batches.lock());
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
//! Queue-to-filter correctness comparisons, without timing or OS delivery.
|
||||
|
||||
use super::*;
|
||||
use notify::event::{CreateKind, Flag, RemoveKind};
|
||||
|
||||
fn compare_batches(left: &FsBatch, right: &FsBatch) {
|
||||
assert_eq!(
|
||||
(
|
||||
&left.created,
|
||||
&left.modified,
|
||||
&left.removed,
|
||||
&left.vcs,
|
||||
&left.excluded_dirs,
|
||||
&left.ignored,
|
||||
&left.ignore_rules
|
||||
),
|
||||
(
|
||||
&right.created,
|
||||
&right.modified,
|
||||
&right.removed,
|
||||
&right.vcs,
|
||||
&right.excluded_dirs,
|
||||
&right.ignored,
|
||||
&right.ignore_rules
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Preserve the pre-change queue and drain operation for the comparison.
|
||||
fn original(input: &[Event], filter: &EventFilter) -> (usize, FsBatch) {
|
||||
let mut queue = Vec::new();
|
||||
for event in input {
|
||||
queue.push((event.clone(), Instant::now()));
|
||||
}
|
||||
let retained = queue.len();
|
||||
let events: Vec<Event> = std::mem::take(&mut queue).into_iter().map(|(event, _)| event).collect();
|
||||
(retained, filter.batch(&events))
|
||||
}
|
||||
|
||||
fn compact(input: &[Event], filter: &EventFilter) -> (usize, FsBatch) {
|
||||
let mut queue = PendingEvents::default();
|
||||
for event in input {
|
||||
queue.push(event.clone(), Instant::now());
|
||||
}
|
||||
let events = std::mem::take(&mut queue);
|
||||
(events.events.len(), filter.batch(&events.events))
|
||||
}
|
||||
|
||||
fn event(kind: EventKind, root: &Path, rel: &str) -> Event {
|
||||
Event::new(kind).add_path(root.join(rel))
|
||||
}
|
||||
|
||||
fn modify(root: &Path, n: usize) -> Event {
|
||||
event(EventKind::Modify(ModifyKind::Any), root, &format!("src/{n}.rs"))
|
||||
}
|
||||
|
||||
fn fixture(files: usize) -> tempfile::TempDir {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for dir in ["src", "excluded", ".git/info", "renamed"] {
|
||||
std::fs::create_dir_all(tmp.path().join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(tmp.path().join(".gitignore"), "*.ignored\n").unwrap();
|
||||
std::fs::write(tmp.path().join("file.ignored"), "x").unwrap();
|
||||
for n in 0..files {
|
||||
std::fs::write(tmp.path().join(format!("src/{n}.rs")), "x").unwrap();
|
||||
if n % 8 == 4 {
|
||||
std::fs::write(tmp.path().join(format!("excluded/{n}.js")), "x").unwrap();
|
||||
}
|
||||
}
|
||||
tmp
|
||||
}
|
||||
|
||||
fn cases(root: &Path, count: usize) -> Vec<(&'static str, Vec<Event>)> {
|
||||
let repeated = vec![modify(root, 0); count];
|
||||
let distinct = (0..count).map(|n| modify(root, n)).collect();
|
||||
let interleaved = (0..count).map(|n| modify(root, n % 2)).collect();
|
||||
let pairs = (0..count).map(|n| modify(root, n / 2)).collect();
|
||||
let runs = (0..count).map(|n| modify(root, n / 10)).collect();
|
||||
let mixed = (0..count)
|
||||
.map(|n| match n % 8 {
|
||||
0 | 1 => modify(root, n / 8),
|
||||
2 => event(EventKind::Create(CreateKind::File), root, &format!("src/{}.rs", n / 8)),
|
||||
3 => event(EventKind::Remove(RemoveKind::File), root, &format!("gone/{n}.rs")),
|
||||
4 => event(EventKind::Create(CreateKind::File), root, &format!("excluded/{n}.js")),
|
||||
5 => event(EventKind::Remove(RemoveKind::File), root, &format!("excluded/{n}.js")),
|
||||
6 => event(EventKind::Modify(ModifyKind::Any), root, "file.ignored"),
|
||||
_ => event(EventKind::Modify(ModifyKind::Any), root, ".git/HEAD"),
|
||||
})
|
||||
.collect();
|
||||
vec![
|
||||
("repeated", repeated),
|
||||
("distinct", distinct),
|
||||
("interleaved", interleaved),
|
||||
("pairs", pairs),
|
||||
("runs10", runs),
|
||||
("mixed", mixed),
|
||||
]
|
||||
}
|
||||
|
||||
fn pair(input: &[Event], root: &Path, warm: bool, reverse: bool) -> (usize, usize) {
|
||||
let excludes = vec!["excluded".to_owned()];
|
||||
let a = EventFilter::new(root.to_path_buf(), &excludes);
|
||||
let b = EventFilter::new(root.to_path_buf(), &excludes);
|
||||
if warm {
|
||||
compare_batches(&a.batch(input), &b.batch(input));
|
||||
}
|
||||
let (a_retained, a_batch, b_retained, b_batch) = if reverse {
|
||||
let (b_retained, b_batch) = compact(input, &b);
|
||||
let (a_retained, a_batch) = original(input, &a);
|
||||
(a_retained, a_batch, b_retained, b_batch)
|
||||
} else {
|
||||
let (a_retained, a_batch) = original(input, &a);
|
||||
let (b_retained, b_batch) = compact(input, &b);
|
||||
(a_retained, a_batch, b_retained, b_batch)
|
||||
};
|
||||
compare_batches(&a_batch, &b_batch);
|
||||
(a_retained, b_retained)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipeline_comparison_preserves_batches_and_rule_changes() {
|
||||
let tmp = fixture(32);
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for (name, input) in cases(&root, 32) {
|
||||
for warm in [false, true] {
|
||||
for reverse in [false, true] {
|
||||
let (old, new) = pair(&input, &root, warm, reverse);
|
||||
assert_eq!(old, 32);
|
||||
let expected = match name {
|
||||
"repeated" => 1,
|
||||
"distinct" | "interleaved" => 32,
|
||||
"pairs" => 16,
|
||||
"runs10" => 4,
|
||||
"mixed" => 28,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
assert_eq!(new, expected, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut special = vec![
|
||||
modify(&root, 0).set_flag(Flag::Rescan),
|
||||
modify(&root, 0).set_flag(Flag::Rescan),
|
||||
modify(&root, 0).set_tracker(1),
|
||||
modify(&root, 0).set_tracker(2),
|
||||
modify(&root, 0).set_process_id(1),
|
||||
modify(&root, 0).set_process_id(2),
|
||||
modify(&root, 0).add_path(root.join("src/1.rs")),
|
||||
];
|
||||
for mode in [RenameMode::Both, RenameMode::From, RenameMode::To] {
|
||||
let rename = event(EventKind::Modify(ModifyKind::Name(mode)), &root, "old.rs");
|
||||
special.push(if mode == RenameMode::Both { rename.add_path(root.join("src/0.rs")) } else { rename });
|
||||
}
|
||||
let (old, new) = pair(&special, &root, true, false);
|
||||
assert_eq!(old, special.len());
|
||||
assert_eq!(new, special.len());
|
||||
for rule in [".gitignore", ".ignore", ".git/info/exclude"] {
|
||||
let tmp = fixture(1);
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(root.join(".gitignore"), "").unwrap();
|
||||
std::fs::write(root.join(rule), "").unwrap();
|
||||
let a = EventFilter::new(root.clone(), &[]);
|
||||
let b = EventFilter::new(root.clone(), &[]);
|
||||
let touch = event(EventKind::Modify(ModifyKind::Any), &root, "file.ignored");
|
||||
for filter in [&a, &b] {
|
||||
assert_eq!(filter.batch(std::slice::from_ref(&touch)).modified, vec![root.join("file.ignored")]);
|
||||
}
|
||||
std::fs::write(root.join(rule), "*.ignored\n").unwrap();
|
||||
let change = event(EventKind::Modify(ModifyKind::Any), &root, rule);
|
||||
let input = [touch.clone(), touch, change.clone(), change];
|
||||
let (_, old) = original(&input, &a);
|
||||
let (_, new) = compact(&input, &b);
|
||||
compare_batches(&old, &new);
|
||||
assert_eq!(new.ignored, vec![root.join("file.ignored")]);
|
||||
assert_eq!(new.ignore_rules, vec![root]);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
@@ -42,6 +42,9 @@ struct Root {
|
||||
dir: PathBuf,
|
||||
port: u16,
|
||||
serves: Serves,
|
||||
/// Files handed out by [`WebServer::page_url_for`], as requested. They stay here until
|
||||
/// the app quits, even if the file stops being HTML: only its content type depends on it.
|
||||
pages: Mutex<HashSet<PathBuf>>,
|
||||
}
|
||||
|
||||
/// What of its directory a root serves.
|
||||
@@ -87,6 +90,18 @@ impl WebServer {
|
||||
/// A project that is the home folder, or holds it, is no boundary to serve whole: its
|
||||
/// files are served like files outside a project.
|
||||
pub async fn url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
|
||||
Ok(self.locate(root, file).await?.1)
|
||||
}
|
||||
|
||||
/// [`Self::url_for`] of a file that is an HTML page whatever its name (Settings › File
|
||||
/// Types): it is served as HTML from now on.
|
||||
pub async fn page_url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
|
||||
let (served, url) = self.locate(root, file).await?;
|
||||
served.pages.lock().unwrap_or_else(PoisonError::into_inner).insert(file.to_path_buf());
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
async fn locate(&self, root: Option<&Path>, file: &Path) -> IdeResult<(Arc<Root>, String)> {
|
||||
let (base, serves) = match root {
|
||||
Some(r) if file.starts_with(r) && file != r && self.holds_home(r).await != Some(true) => (r, Serves::All),
|
||||
_ => {
|
||||
@@ -102,7 +117,7 @@ impl WebServer {
|
||||
url.push('/');
|
||||
url.push_str(&enc(&c.as_os_str().to_string_lossy()));
|
||||
}
|
||||
Ok(url)
|
||||
Ok((root, url))
|
||||
}
|
||||
|
||||
/// Whether `dir` is the home folder or lies above it; `None` when that cannot be told.
|
||||
@@ -153,6 +168,7 @@ impl WebServer {
|
||||
dir: dir.to_path_buf(),
|
||||
port,
|
||||
serves,
|
||||
pages: Mutex::default(),
|
||||
});
|
||||
tokio::spawn(accept(listener, root.clone()));
|
||||
tracing::info!("built-in web server on 127.0.0.1:{} for {}", root.port, dir.display());
|
||||
@@ -320,7 +336,9 @@ async fn resolve(root: &Root, target: &str) -> Response {
|
||||
_ => NOT_FOUND,
|
||||
};
|
||||
}
|
||||
Response::File { path: real, len: meta.len(), mime: content_type(&file) }
|
||||
let page = root.pages.lock().unwrap_or_else(PoisonError::into_inner).contains(&file);
|
||||
let mime = if page { HTML } else { content_type(&file) };
|
||||
Response::File { path: real, len: meta.len(), mime }
|
||||
}
|
||||
|
||||
/// `path` with every symlink resolved, if `root` serves it: it lies inside `real_root`
|
||||
@@ -343,10 +361,12 @@ fn dec(s: &str) -> Option<String> {
|
||||
percent_decode_str(s).decode_utf8().ok().map(|s| s.into_owned())
|
||||
}
|
||||
|
||||
const HTML: &str = "text/html; charset=utf-8";
|
||||
|
||||
fn content_type(path: &Path) -> &'static str {
|
||||
let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
match ext.as_str() {
|
||||
"html" | "htm" | "xhtml" => "text/html; charset=utf-8",
|
||||
"html" | "htm" | "xhtml" => HTML,
|
||||
"css" => "text/css; charset=utf-8",
|
||||
"js" | "mjs" | "cjs" => "text/javascript; charset=utf-8",
|
||||
"json" | "map" | "webmanifest" => "application/json; charset=utf-8",
|
||||
@@ -395,6 +415,25 @@ mod tests {
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_page_is_html_whatever_its_name() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("site");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(root.join("page.foo"), "<h1>hi</h1>").unwrap();
|
||||
std::fs::write(root.join("other.foo"), "<h1>no</h1>").unwrap();
|
||||
let server = server();
|
||||
|
||||
let plain = server.url_for(Some(&root), &root.join("page.foo")).await.unwrap();
|
||||
assert!(get(&plain, None).await.contains("application/octet-stream"));
|
||||
|
||||
let page = server.page_url_for(Some(&root), &root.join("page.foo")).await.unwrap();
|
||||
assert_eq!(page, plain);
|
||||
assert!(get(&page, None).await.contains("Content-Type: text/html"));
|
||||
let other = page.replace("page.foo", "other.foo");
|
||||
assert!(get(&other, None).await.contains("application/octet-stream"), "only the named file");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn serves_project_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -172,6 +172,9 @@ struct DocState {
|
||||
/// Disk state we last loaded or wrote; changes matching it are our own.
|
||||
disk_mtime: f64,
|
||||
disk_len: u64,
|
||||
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
|
||||
/// alone until the user saves explicitly or the buffer is reloaded.
|
||||
disk_conflict: bool,
|
||||
closed: bool,
|
||||
/// URI of a virtual document (no file behind it).
|
||||
uri: Option<String>,
|
||||
@@ -264,6 +267,7 @@ impl Documents {
|
||||
st.native_to_ascii = enabled;
|
||||
st.disk_mtime = loaded.mtime_ms;
|
||||
st.disk_len = disk_len(&st.path);
|
||||
st.disk_conflict = false;
|
||||
Ok(())
|
||||
});
|
||||
if let Err(e) = result {
|
||||
@@ -457,6 +461,7 @@ impl Documents {
|
||||
encoding_chosen: false,
|
||||
disk_mtime: loaded.mtime_ms,
|
||||
disk_len: disk_len(path),
|
||||
disk_conflict: false,
|
||||
closed: false,
|
||||
uri: None,
|
||||
};
|
||||
@@ -529,6 +534,7 @@ impl Documents {
|
||||
encoding_chosen: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
closed: false,
|
||||
uri: Some(uri.to_owned()),
|
||||
};
|
||||
@@ -587,6 +593,7 @@ impl Documents {
|
||||
encoding_chosen: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
closed: false,
|
||||
uri: Some(key.to_string_lossy().into_owned()),
|
||||
};
|
||||
@@ -653,6 +660,8 @@ impl Documents {
|
||||
};
|
||||
let mut st = slot.lock();
|
||||
st.closed = true;
|
||||
// A buffer closed with changes (Don't Save) has nothing left to save.
|
||||
self.set_dirty(doc, &mut st, false);
|
||||
if st.observed {
|
||||
for o in self.observers() {
|
||||
o.closed(doc, &st.path);
|
||||
@@ -810,7 +819,22 @@ impl Documents {
|
||||
/// Writes the document with its original encoding, BOM and line ending.
|
||||
/// A clean document is not rewritten.
|
||||
pub fn save(&self, doc: DocId) -> IdeResult<()> {
|
||||
self.with_doc(doc, |st| self.write(doc, st))
|
||||
}
|
||||
|
||||
/// An automatic save (switching tabs, the window losing focus): `false` when the file changed
|
||||
/// on disk after this buffer was edited, which only an explicit save may overwrite.
|
||||
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
|
||||
self.with_doc(doc, |st| {
|
||||
if st.dirty && st.disk_conflict {
|
||||
return Ok(false);
|
||||
}
|
||||
self.write(doc, st).map(|()| true)
|
||||
})
|
||||
}
|
||||
|
||||
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
|
||||
{
|
||||
if !st.dirty || st.uri.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -822,6 +846,7 @@ impl Documents {
|
||||
};
|
||||
st.disk_mtime = mtime;
|
||||
st.disk_len = disk_len(&st.path);
|
||||
st.disk_conflict = false;
|
||||
self.set_dirty(doc, st, false);
|
||||
if st.observed {
|
||||
let text = st.doc.text();
|
||||
@@ -830,7 +855,7 @@ impl Documents {
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Save As for an untitled buffer: writes it to `target` (creating missing
|
||||
@@ -1090,6 +1115,7 @@ impl Documents {
|
||||
st.has_bom = loaded.has_bom;
|
||||
st.disk_mtime = loaded.mtime_ms;
|
||||
st.disk_len = disk_len(&st.path);
|
||||
st.disk_conflict = false;
|
||||
self.replace_locked(doc, st, &loaded.text)?;
|
||||
// Reloading is not an edit: the buffer matches the file again.
|
||||
self.set_dirty(doc, st, false);
|
||||
@@ -1262,13 +1288,14 @@ impl Documents {
|
||||
if st.dirty {
|
||||
st.disk_mtime = mtime;
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
let name = st.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
self.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Warning,
|
||||
title: format!("{name} changed on disk"),
|
||||
body: Some(format!(
|
||||
"{} was modified externally but has unsaved changes in the editor. \
|
||||
Saving will overwrite the external changes.",
|
||||
Saving explicitly will overwrite the external changes; autosave leaves the file alone.",
|
||||
st.path.display()
|
||||
)),
|
||||
});
|
||||
@@ -1289,6 +1316,7 @@ impl Documents {
|
||||
};
|
||||
st.disk_mtime = loaded.mtime_ms;
|
||||
st.disk_len = disk_len(&st.path);
|
||||
st.disk_conflict = false;
|
||||
if loaded.binary || st.binary {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -92,6 +92,8 @@ pub const DEFAULT_MAX_AGE_DAYS: u32 = 5;
|
||||
pub const DEFAULT_MAX_BYTES: u64 = 512 * 1024 * 1024;
|
||||
/// Label of the snapshot taken before a file is deleted.
|
||||
pub const DELETED: &str = "Deleted";
|
||||
/// The label of a file's content from before its first edit ([`LocalHistory::record_original`]).
|
||||
pub const ORIGINAL: &str = "Original";
|
||||
/// Files larger than this are not snapshotted automatically (watcher, deletes, VCS).
|
||||
const AUTO_SNAPSHOT_LIMIT: u64 = 2 * 1024 * 1024;
|
||||
const DAY_MS: f64 = 86_400_000.0;
|
||||
@@ -121,7 +123,14 @@ fn read_snapshot_text(path: &Path) -> Option<String> {
|
||||
if bytes.iter().take(8192).any(|b| *b == 0) {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(bytes).ok()
|
||||
String::from_utf8(bytes).ok().map(|text| document_text(&text).into_owned())
|
||||
}
|
||||
|
||||
/// `text` as a document holds it: without the UTF-8 BOM and with `\n` line endings. Saves
|
||||
/// record the document's text, so a file read from disk must match it to dedupe, and
|
||||
/// Revert writes it back through the document, which adds the file's BOM and line endings.
|
||||
fn document_text(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
ide_text::normalize_line_endings(text.strip_prefix('\u{feff}').unwrap_or(text))
|
||||
}
|
||||
|
||||
impl LocalHistory {
|
||||
@@ -188,6 +197,18 @@ impl LocalHistory {
|
||||
if !force && state.last.get(path) == Some(&id) {
|
||||
return Ok(());
|
||||
}
|
||||
self.store_locked(&mut state, path, id, content, label, now_ms())
|
||||
}
|
||||
|
||||
fn store_locked(
|
||||
&self,
|
||||
state: &mut HistoryState,
|
||||
path: &Path,
|
||||
id: String,
|
||||
content: &str,
|
||||
label: &str,
|
||||
timestamp_ms: f64,
|
||||
) -> IdeResult<()> {
|
||||
let blob = self.blob_path(&id);
|
||||
if !blob.exists() {
|
||||
fs::create_dir_all(blob.parent().expect("blob has a parent"))?;
|
||||
@@ -196,12 +217,12 @@ impl LocalHistory {
|
||||
let entry = HistoryEntry {
|
||||
id,
|
||||
path: path.into(),
|
||||
timestamp_ms: now_ms(),
|
||||
timestamp_ms,
|
||||
label: label.to_owned(),
|
||||
size: content.len() as u64,
|
||||
kind: HistoryKind::Snapshot,
|
||||
};
|
||||
self.append(&mut state, entry)
|
||||
self.append(state, entry)
|
||||
}
|
||||
|
||||
/// Records a snapshot unless it equals the latest one recorded for `path`.
|
||||
@@ -223,6 +244,31 @@ impl LocalHistory {
|
||||
}
|
||||
}
|
||||
|
||||
/// Before the first edit of a file with no history: its content on disk, so a label put
|
||||
/// before the edit can be reverted to. Dated by the file's modification time, since it
|
||||
/// has had that content from then on, but not before the oldest entry kept, so it neither
|
||||
/// adds a working day of its own nor falls to retention first. Returns whether one was recorded.
|
||||
pub fn record_original(&self, path: &Path) -> IdeResult<bool> {
|
||||
let Some(text) = read_snapshot_text(path) else { return Ok(false) };
|
||||
let modified = fs::metadata(path)
|
||||
.and_then(|m| m.modified())
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs_f64() * 1000.0);
|
||||
let mut state = self.state.lock();
|
||||
if state.entries.iter().any(|e| e.kind == HistoryKind::Snapshot && e.path == path) {
|
||||
return Ok(false);
|
||||
}
|
||||
let now = now_ms();
|
||||
let oldest = state.entries.iter().map(|e| e.timestamp_ms).reduce(f64::min);
|
||||
let timestamp = match (modified, oldest) {
|
||||
(Some(modified), Some(oldest)) => modified.max(oldest - 1.0).min(now),
|
||||
_ => now,
|
||||
};
|
||||
let id = blake3::hash(text.as_bytes()).to_hex().to_string();
|
||||
self.store_locked(&mut state, path, id, &text, ORIGINAL, timestamp).map(|()| true)
|
||||
}
|
||||
|
||||
/// Snapshots `path`, or every file below it when it is a folder (at most `limit`
|
||||
/// files), before it is deleted. Returns how many files were recorded.
|
||||
pub fn record_deletion(&self, path: &Path, limit: usize) -> usize {
|
||||
@@ -338,7 +384,10 @@ impl LocalHistory {
|
||||
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
|
||||
}
|
||||
match fs::read(self.blob_path(id)) {
|
||||
Ok(bytes) => Ok(String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into())),
|
||||
Ok(bytes) => {
|
||||
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
|
||||
Ok(document_text(&text).into_owned())
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
Err(IdeError::not_found(format!("history snapshot {id} not found")))
|
||||
}
|
||||
@@ -532,6 +581,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_read_from_disk_matches_the_saved_document_text() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let a = root.join("a.txt");
|
||||
// A save records the document's text; the file on disk has a BOM and CRLF.
|
||||
fs::write(&a, b"\xEF\xBB\xBFheader\r\nbody\r\n").unwrap();
|
||||
h.record(&a, "header\nbody\n", "Saved").unwrap();
|
||||
assert!(h.record_file(&a, "External change", false).unwrap());
|
||||
let list = h.list(&a).unwrap();
|
||||
assert_eq!(list.iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["Saved"], "no second revision");
|
||||
// A snapshot stored with its BOM before reads back as document text.
|
||||
h.record(&a, "\u{feff}old\r\n", "External change").unwrap();
|
||||
let old = &h.list(&a).unwrap()[0];
|
||||
assert_eq!(h.content(&old.id).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn events_labels_and_deletions() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -630,4 +698,42 @@ mod tests {
|
||||
assert_eq!(h.list(Path::new("/p/a")).unwrap().len(), 1);
|
||||
assert_eq!(h.content(&old).unwrap_err().kind, ide_core::error::ErrorKind::NotFound);
|
||||
}
|
||||
#[test]
|
||||
fn a_files_original_content_is_there_at_a_label_put_before_its_first_edit() {
|
||||
use std::time::{Duration, SystemTime};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let h = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let set_modified = |path: &Path, at: SystemTime| {
|
||||
std::fs::File::options().write(true).open(path).unwrap().set_modified(at).unwrap();
|
||||
};
|
||||
let old = root.join("old.txt");
|
||||
std::fs::write(&old, "as it was").unwrap();
|
||||
set_modified(&old, SystemTime::now() - Duration::from_secs(3600));
|
||||
h.record(&root.join("other.txt"), "x", "Saved").unwrap();
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
h.put_label(&root, "checkpoint").unwrap();
|
||||
// Written after the label: it didn't have this content at the label.
|
||||
let new = root.join("new.txt");
|
||||
std::fs::write(&new, "fresh").unwrap();
|
||||
set_modified(&new, SystemTime::now() + Duration::from_secs(1));
|
||||
|
||||
assert!(h.record_original(&old).unwrap());
|
||||
assert!(h.record_original(&new).unwrap());
|
||||
// Only a file without history gets one.
|
||||
assert!(!h.record_original(&old).unwrap());
|
||||
h.record(&old, "edited", "Saved").unwrap();
|
||||
|
||||
let entries = h.list(&old).unwrap();
|
||||
let label = entries.iter().find(|e| e.kind == HistoryKind::Label).unwrap();
|
||||
let original = entries.iter().find(|e| e.label == ORIGINAL).unwrap();
|
||||
assert!(original.timestamp_ms < label.timestamp_ms);
|
||||
assert_eq!(h.content(&original.id).unwrap(), "as it was");
|
||||
// Not dated before the oldest entry kept: no working day of its own.
|
||||
let oldest = h.list(&root.join("other.txt")).unwrap().last().unwrap().timestamp_ms;
|
||||
assert!(original.timestamp_ms >= oldest - 1.0);
|
||||
let fresh = h.list(&new).unwrap().into_iter().find(|e| e.label == ORIGINAL).unwrap();
|
||||
assert!(fresh.timestamp_ms > label.timestamp_ms);
|
||||
}
|
||||
}
|
||||
@@ -228,6 +228,39 @@ fn dirty_events(events: &[IdeEvent]) -> Vec<bool> {
|
||||
events.iter().filter_map(|e| if let IdeEvent::DocDirty { dirty, .. } = e { Some(*dirty) } else { None }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
fs::write(&path, "alpha\nbeta external\n").unwrap();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
|
||||
assert!(!f.docs.autosave(info.id).unwrap());
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta external\n");
|
||||
assert!(f.docs.snapshot(info.id).unwrap().dirty);
|
||||
|
||||
// An explicit save overwrites, as the warning says; autosave works again after it.
|
||||
f.docs.save(info.id).unwrap();
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
|
||||
f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap();
|
||||
assert!(f.docs.autosave(info.id).unwrap());
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "xedited\nbeta\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_modified_buffer_reports_it_clean() {
|
||||
let f = fixture();
|
||||
let info = f.docs.open_untitled(None).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 0, "draft")).unwrap();
|
||||
assert_eq!(dirty_events(&f.events.lock()), vec![true]);
|
||||
f.docs.close(info.id);
|
||||
assert_eq!(dirty_events(&f.events.lock()), vec![true, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_edit_save_close() {
|
||||
let f = fixture();
|
||||
|
||||
@@ -96,7 +96,7 @@ Once an agent has run a task, new tasks start in its mode that approves everythi
|
||||
|
||||
### Review the changes
|
||||
|
||||
Click **Show changes** in the task header to list the files the task changed. A task in the project's own checkout lists only the files that changed while the agent was working, not what you or another task changed while it was idle. Click a file to open a diff between the task's starting point and now. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it.
|
||||
Click **Show changes** in the task header to list the files the task changed. A task in the project's own checkout lists only the files that changed while the agent was working, not what you or another task changed while it was idle. Click a file to open a diff between the task's starting point and now. Switch the list from **Whole Task** to **Last Turn** to see only what the last turn changed, against the files as that turn started; rolling back then undoes only that turn. For a worktree task, the changes live on its `agent/…` branch: open a terminal there with **Open in Terminal**, and merge or cherry-pick the branch with the Git tools (see [Version control](/en/guide/vcs)) when you are happy with it.
|
||||
|
||||
Drag the pane's left edge to resize it. The width applies to every task and is remembered across restarts.
|
||||
|
||||
@@ -131,7 +131,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
- **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.
|
||||
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
|
||||
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
|
||||
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
|
||||
|
||||
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
|
||||
|
||||
@@ -97,6 +97,7 @@ Open **Run › Edit Configurations…** (also in the run widget menu). The **Run
|
||||
| **Gradle** / **Maven** | Gradle tasks or Maven goals, optionally through the wrapper |
|
||||
| **Application** / **JAR Application** / **Spring Boot** | A Java main class, an executable JAR, a Spring Boot application |
|
||||
| **Tomcat Server** | A WAR application in a local Tomcat |
|
||||
| **Python** | A Python script or `-m` module |
|
||||
| **pytest** / **Django tests** | pytest tests, `manage.py test` |
|
||||
| **Ruby** / **Rake** / **RSpec** | A Ruby script, a Rake task, RSpec examples |
|
||||
| **PHPUnit** | PHPUnit tests |
|
||||
|
||||
@@ -57,6 +57,7 @@ In a Composer project without `vendor/`, or whose installed packages differ from
|
||||
|
||||
- **PHPStan**: when the project has `vendor/bin/phpstan`, saved files are checked with it and its findings appear as diagnostics. The **PHPStan › Configuration file** setting picks the config; empty uses `phpstan.neon`, `phpstan.neon.dist` or `phpstan.dist.neon` in the project root.
|
||||
- **PHP-CS-Fixer**: when a folder above the file has `.php-cs-fixer.php` or `.php-cs-fixer.dist.php` and the project has `vendor/bin/php-cs-fixer`, **Reformat Code** (`⌥⌘L` / `Ctrl+Alt+L`) uses PHP-CS-Fixer instead of the language server.
|
||||
- **Alignment**: **Settings › Editor › Code Style › PHP › Alignment** has PhpStorm's **Align key-value pairs** (`=>` in multi-line arrays) and **Align consecutive assignments** (`=` in assignment statements on consecutive lines), both off by default. They apply after the language server or PHP-CS-Fixer formats, on save too; for a selection, only to its lines. A blank line, a comment line, another statement or a value spanning several lines starts a new group, and nested arrays align on their own.
|
||||
|
||||
## Run and test
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ In the editor, gutter icons run or debug:
|
||||
|
||||
A test file runs with pytest even when the project declares no test setup (`python -m pytest` with the project interpreter, so pytest must be installed there). In a Django project, `TestCase` tests can also run with `manage.py test`. Results of pytest and of Django's unittest runner appear in the test tree, where **Rerun Failed Tests** runs only the failures.
|
||||
|
||||
You can also create **pytest** and **Django tests** configurations in **Run › Edit Configurations…**. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing).
|
||||
You can also create **Python** (a script or module), **pytest** and **Django tests** configurations in **Run › Edit Configurations…**. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing).
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
| --------------------------- | ----- | ---------------- |
|
||||
|
||||
@@ -238,7 +238,8 @@ The full table is `UI_KEYS` in
|
||||
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
|
||||
| `--syn-rainbow-1` … `--syn-rainbow-5` (Semantic highlighting) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
|
||||
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES` (effect colour) |
|
||||
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
|
||||
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
|
||||
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
|
||||
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
|
||||
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
|
||||
| `--ansi-*` | `CONSOLE_*_OUTPUT` (`CONSOLE_DARKGRAY_OUTPUT` is bright black, `CONSOLE_GRAY_OUTPUT` white) |
|
||||
@@ -519,6 +520,8 @@ conventionally go in the theme file, groups marked _editor scheme_ in the scheme
|
||||
| `--fg-unused` | `#6f737a` | `#8c8c8c` |
|
||||
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
|
||||
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
|
||||
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
|
||||
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
|
||||
| `--fg-inlay` | `#868a91` | `#73767c` |
|
||||
| `--bg-inlay` | `#393b40` | `#00000012` |
|
||||
| `--wave-error` | `#fa6675` | `#f50000` |
|
||||
|
||||
@@ -45,14 +45,16 @@ If navigation, search or highlighting doesn't match the files, rebuild the cache
|
||||
|
||||
The Windows packages aren't code-signed yet, so Microsoft Defender SmartScreen may show an unknown-publisher warning. Choose **More info**, then **Run anyway**. See [Install](/en/guide/install#windows).
|
||||
|
||||
## The window stays blank on Linux
|
||||
## The window stays blank or stops responding on Linux
|
||||
|
||||
WebKitGTK's DMA-BUF renderer fails on Wayland with the NVIDIA driver. OpenIDEA detects this combination and sets `WEBKIT_DISABLE_DMABUF_RENDERER=1` itself. If you see a blank or broken window in another setup, quit OpenIDEA and start it from a terminal with that variable set, for example:
|
||||
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal with the DMA-BUF renderer turned off, for example:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
The page is then drawn without the GPU, so dragging large panels can be slower. To keep the setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line to `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`.
|
||||
|
||||
## OpenIDEA exits at startup with a data directory error
|
||||
|
||||
`OPENIDEA_LOCAL_DATA_DIR` is set to a relative path or to a folder that can't be written. Fix or remove the variable. See [Move the local data](/en/reference/data-directories#move-the-local-data).
|
||||
|
||||
@@ -96,7 +96,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
### 查看改动
|
||||
|
||||
在任务标题栏中单击 **显示更改**,列出任务改动过的文件。直接在项目中运行的任务只列出 agent 工作期间改动的文件,不包括它空闲时你自己或其他任务做的修改。单击文件可以打开它从任务开始到现在的 diff。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。
|
||||
在任务标题栏中单击 **显示更改**,列出任务改动过的文件。直接在项目中运行的任务只列出 agent 工作期间改动的文件,不包括它空闲时你自己或其他任务做的修改。单击文件可以打开它从任务开始到现在的 diff。把列表从 **整个任务** 切换到 **最近一轮**,就只列出最近一轮的改动,对比的是这一轮开始时的文件;此时回滚也只撤销这一轮的改动。worktree 任务的改动在它的 `agent/…` 分支上:用 **在终端中打开** 在那里打开终端,满意后用 Git 工具合并或 cherry-pick 这个分支(见 [版本控制](/zh/guide/vcs))。
|
||||
|
||||
拖动改动面板的左边缘可以调整宽度。宽度对所有任务生效,重启后保留。
|
||||
|
||||
@@ -131,7 +131,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
|
||||
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
|
||||
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
|
||||
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
|
||||
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
|
||||
|
||||
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
|
||||
|
||||
@@ -93,6 +93,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
|
||||
| **Gradle** / **Maven** | Gradle 任务或 Maven 目标,可选择通过 wrapper 运行 |
|
||||
| **应用程序** / **JAR 应用程序** / **Spring Boot** | Java 主类、可执行 JAR、Spring Boot 应用 |
|
||||
| **Tomcat 服务器** | 在本地 Tomcat 里运行 WAR 应用 |
|
||||
| **Python** | Python 脚本或 `-m` 模块 |
|
||||
| **pytest** / **Django 测试** | pytest 测试、`manage.py test` |
|
||||
| **Ruby 语言** / **Rake 任务** / **RSpec 测试** | Ruby 脚本、Rake 任务、RSpec 用例 |
|
||||
| **PHPUnit** | PHPUnit 测试 |
|
||||
|
||||
@@ -57,6 +57,7 @@ Composer 项目没有 `vendor/`,或已安装的包与 `composer.lock` 不一
|
||||
|
||||
- **PHPStan**:项目中有 `vendor/bin/phpstan` 时,保存的文件会交给它检查,结果显示为诊断。**PHPStan › 配置文件** 用于指定配置;留空则使用项目根目录下的 `phpstan.neon`、`phpstan.neon.dist` 或 `phpstan.dist.neon`。
|
||||
- **PHP-CS-Fixer**:当文件上层目录中有 `.php-cs-fixer.php` 或 `.php-cs-fixer.dist.php`,且项目有 `vendor/bin/php-cs-fixer` 时,**重新格式化代码**(`⌥⌘L` / `Ctrl+Alt+L`)改用 PHP-CS-Fixer,而不是语言服务器。
|
||||
- **对齐**:**设置 › 编辑器 › 代码样式 › PHP › 对齐** 提供与 PhpStorm 相同的 **对齐键值对**(多行数组中的 `=>`)和 **对齐连续赋值**(相邻行赋值语句中的 `=`),默认都关闭。它们在语言服务器或 PHP-CS-Fixer 格式化之后生效,保存时格式化也一样;格式化选区时只作用于选中的行。空行、注释行、其他语句或跨多行的值会开始新的一组,嵌套数组单独对齐。
|
||||
|
||||
## 运行与测试
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
|
||||
|
||||
即使项目没有声明任何测试配置,测试文件也可以用 pytest 运行(用项目解释器执行 `python -m pytest`,因此该解释器里要装有 pytest)。在 Django 项目中,`TestCase` 测试也可以用 `manage.py test` 运行。pytest 和 Django unittest 运行器的结果显示在测试树中,**重新运行失败的测试** 只重跑失败的用例。
|
||||
|
||||
也可以在 **运行 › 编辑配置…** 中新建 **pytest** 和 **Django 测试** 配置。详见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。
|
||||
也可以在 **运行 › 编辑配置…** 中新建 **Python**(脚本或模块)、**pytest** 和 **Django 测试** 配置。详见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。
|
||||
|
||||
| 操作 | macOS | Windows / Linux |
|
||||
| -------------- | ----- | ---------------- |
|
||||
|
||||
@@ -211,7 +211,8 @@ pnpm theme:import-intellij path/to/MyTheme.theme.json path/to/MyTheme.icls --out
|
||||
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
|
||||
| `--syn-rainbow-1` … `--syn-rainbow-5`(语义高亮) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
|
||||
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES`(效果颜色) |
|
||||
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
|
||||
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
|
||||
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
|
||||
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
|
||||
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
|
||||
| `--ansi-*` | `CONSOLE_*_OUTPUT`(`CONSOLE_DARKGRAY_OUTPUT` 为亮黑,`CONSOLE_GRAY_OUTPUT` 为白色) |
|
||||
@@ -485,6 +486,8 @@ VS Code 主题(扩展中的 `themes/*.json`)包含 `type`(`dark` / `light`
|
||||
| `--fg-unused` | `#6f737a` | `#8c8c8c` |
|
||||
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
|
||||
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
|
||||
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
|
||||
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
|
||||
| `--fg-inlay` | `#868a91` | `#73767c` |
|
||||
| `--bg-inlay` | `#393b40` | `#00000012` |
|
||||
| `--wave-error` | `#fa6675` | `#f50000` |
|
||||
|
||||
@@ -45,14 +45,16 @@ Java 语言服务器(jdtls)会分析它导入的每个模块,所以大型
|
||||
|
||||
Windows 安装包目前还没有代码签名,Microsoft Defender SmartScreen 可能提示“未知发布者”。点击 **更多信息**,再点击 **仍要运行**。参见[安装](/zh/guide/install)。
|
||||
|
||||
## Linux 上窗口一片空白
|
||||
## Linux 上窗口空白或无响应
|
||||
|
||||
在使用 NVIDIA 驱动的 Wayland 会话中,WebKitGTK 的 DMA-BUF 渲染器会出错。OpenIDEA 检测到这种组合时会自动设置 `WEBKIT_DISABLE_DMABUF_RENDERER=1`。如果在其他环境下也出现空白或显示异常的窗口,先退出 OpenIDEA,再在终端中带上这个变量启动,例如:
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中关闭 DMA-BUF 渲染器启动,例如:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上这个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并把其中的 `Exec=` 一行改成 `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`。
|
||||
|
||||
## 启动时提示数据目录错误并退出
|
||||
|
||||
`OPENIDEA_LOCAL_DATA_DIR` 被设成了相对路径或不可写的文件夹。修正或删除这个变量即可。参见[数据目录与日志](/zh/reference/data-directories)。
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import type { AgentTask } from "../src/bindings";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const task: AgentTask = {
|
||||
id: "composer-popup",
|
||||
title: "Composer popup task",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
isolation: "local",
|
||||
model: null,
|
||||
cwd: "/dev/acme-api",
|
||||
branch: null,
|
||||
base: null,
|
||||
baseCommit: null,
|
||||
error: null,
|
||||
createdMs: 0,
|
||||
updatedMs: 0,
|
||||
config: [],
|
||||
commands: [],
|
||||
usage: null,
|
||||
queue: [],
|
||||
};
|
||||
|
||||
async function openTask(page: Page, delayFiles = false) {
|
||||
await page.evaluate(
|
||||
async ({ task, delayFiles }) => {
|
||||
// Load the workbench modules in Vite's browser realm, not the Playwright runner.
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const store = await import(storePath);
|
||||
const { commands } = await import(ipcPath);
|
||||
const { promise: filesReady, resolve } = Promise.withResolvers<void>();
|
||||
if (delayFiles) window.addEventListener("test:release-composer-files", () => resolve(), { once: true });
|
||||
else resolve();
|
||||
const file = (name: string) => ({ path: `${task.cwd}/${name}`, relPath: name, score: 1, indices: [] });
|
||||
commands.agentChanges = async () => ({ status: "ok", data: [] });
|
||||
commands.findFiles = async (query: string) => {
|
||||
if (!query) await filesReady;
|
||||
return {
|
||||
status: "ok",
|
||||
data: query ? [file("a.ts")] : Array.from({ length: 12 }, (_, i) => file(`file${i}.ts`)),
|
||||
};
|
||||
};
|
||||
commands.findDirs = async () => ({ status: "ok", data: [] });
|
||||
store.useAgents.setState({
|
||||
loaded: true,
|
||||
error: null,
|
||||
providers: [],
|
||||
tasks: new Map([[task.id, task]]),
|
||||
entries: new Map([[task.id, [{ type: "agent", text: "Reply" }]]]),
|
||||
composers: new Map(),
|
||||
unread: new Set(),
|
||||
docked: null,
|
||||
homeOpen: false,
|
||||
sessionLocation: "editor",
|
||||
});
|
||||
store.openTask(task.id);
|
||||
},
|
||||
{ task, delayFiles },
|
||||
);
|
||||
const editor = page.getByRole("textbox", { name: "Message", exact: true });
|
||||
await editor.click();
|
||||
return { editor, list: page.getByRole("listbox", { name: "Files", exact: true }) };
|
||||
}
|
||||
|
||||
function geometry(list: Locator) {
|
||||
return list.evaluate((list) => {
|
||||
const popup = list.closest<HTMLElement>("[data-popup]")!;
|
||||
const rect = popup.getBoundingClientRect();
|
||||
const caret = getSelection()!.getRangeAt(0).getBoundingClientRect();
|
||||
const footer = popup.querySelector("span:last-child > kbd")!.getBoundingClientRect();
|
||||
return {
|
||||
side: rect.bottom <= caret.top ? "above" : rect.top >= caret.bottom ? "below" : "overlap",
|
||||
height: popup.offsetHeight,
|
||||
listHeight: list.clientHeight,
|
||||
inViewport: rect.top >= 0 && rect.bottom <= innerHeight && rect.left >= 0 && rect.right <= innerWidth,
|
||||
footerVisible: footer.height > 0 && footer.top >= rect.top && footer.bottom <= rect.bottom,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const fullList = { side: "above", listHeight: 300, inViewport: true, footerVisible: true };
|
||||
|
||||
test("erasing the @ filter restores the popup's fitting side and height", async ({ workbench: page }) => {
|
||||
const { editor, list } = await openTask(page);
|
||||
await editor.pressSequentially("@");
|
||||
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toMatchObject(fullList);
|
||||
const initial = await geometry(list);
|
||||
|
||||
await editor.pressSequentially("a");
|
||||
await expect(list.getByText("a.ts", { exact: true })).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true });
|
||||
await editor.press("Backspace");
|
||||
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toEqual(initial);
|
||||
await expect(editor).toBeFocused();
|
||||
await expect(editor).toHaveText("@");
|
||||
});
|
||||
|
||||
test("first-open @ results can grow and flip after asynchronous file search", async ({ workbench: page }) => {
|
||||
const { editor, list } = await openTask(page, true);
|
||||
for (let i = 0; i < 3; i++) await editor.press("Shift+Enter");
|
||||
await editor.press("ArrowUp");
|
||||
await editor.press("ArrowUp");
|
||||
await editor.press("ArrowUp");
|
||||
await editor.pressSequentially("@");
|
||||
await expect(list.getByRole("option").first()).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toMatchObject({ side: "below", footerVisible: true });
|
||||
await expect(list.getByText("file0.ts", { exact: true })).toHaveCount(0);
|
||||
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("test:release-composer-files")));
|
||||
await expect(list.getByText("file0.ts", { exact: true })).toBeVisible();
|
||||
await expect.poll(() => geometry(list)).toMatchObject(fullList);
|
||||
await expect(editor).toBeFocused();
|
||||
});
|
||||
@@ -416,6 +416,7 @@ test("dragging the Changes pane's edge resizes it for the next session too", asy
|
||||
|
||||
// The next session starts with the dragged width.
|
||||
await page.reload();
|
||||
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
|
||||
await seedTasks(page, "editor");
|
||||
await seedChanges(page);
|
||||
await expect.poll(async () => Math.round((await changes.boundingBox())!.width)).toBe(Math.round(widened));
|
||||
|
||||
@@ -1024,3 +1024,37 @@ test("aligns Mermaid diagrams in replies to their container align attribute", as
|
||||
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
|
||||
});
|
||||
|
||||
test("renders LaTeX math formulas with KaTeX and keeps wide equations scrollable", async ({ page }) => {
|
||||
const reply = await openReply(
|
||||
page,
|
||||
[
|
||||
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\), prices $5 and $10 stay plain.",
|
||||
"",
|
||||
"$$",
|
||||
"\\int_{-\\infty}^{\\infty} e^{-x^2} \\, dx = \\sqrt{\\pi}",
|
||||
"$$",
|
||||
"",
|
||||
"```math",
|
||||
"\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2} + a_1 + a_2 + a_3 + a_4 + a_5 + a_6 + a_7 + a_8 + a_9 + a_{10}",
|
||||
"```",
|
||||
].join("\n"),
|
||||
);
|
||||
await expect(reply.locator(".katex")).toHaveCount(4);
|
||||
await expect(reply.locator(".katex-display")).toHaveCount(2);
|
||||
await expect(reply).toContainText("prices $5 and $10 stay plain.");
|
||||
|
||||
const layout = await reply.evaluate((el) => {
|
||||
const firstKatex = el.querySelector<HTMLElement>(".katex")!;
|
||||
const display = el.querySelectorAll<HTMLElement>(".katex-display");
|
||||
const font = getComputedStyle(firstKatex).fontFamily;
|
||||
return {
|
||||
font,
|
||||
height: firstKatex.getBoundingClientRect().height,
|
||||
overflowX: getComputedStyle(display[1]!).overflowX,
|
||||
};
|
||||
});
|
||||
expect(layout.font).toContain("KaTeX_Main");
|
||||
expect(layout.height).toBeGreaterThan(10);
|
||||
expect(layout.overflowX).toBe("auto");
|
||||
});
|
||||
@@ -102,7 +102,7 @@ test("stripe themes inherit base tooltip tokens and keep shortcut text readable"
|
||||
delete root.dataset.colorTheme;
|
||||
root.dataset.theme = kind;
|
||||
root.dataset.pluginTheme = "test/base-tooltip";
|
||||
const path = "/src/features/plugins/bridge.ts";
|
||||
const path = "/src/features/plugins/themeRuntime.ts";
|
||||
const { pluginThemeCss } = await import(/* @vite-ignore */ path);
|
||||
const style = document.createElement("style");
|
||||
style.id = "test-plugin-theme";
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ moveRefactoringSupport = true
|
||||
[language-servers.initialization-options.settings.java]
|
||||
autobuild = { enabled = true }
|
||||
contentProvider = { preferred = "fernflowerContentProvider" }
|
||||
maven = { downloadSources = true, updateSnapshots = false }
|
||||
maven = { downloadSources = false, updateSnapshots = false }
|
||||
eclipse = { downloadSources = true }
|
||||
references = { includeDecompiledSources = true }
|
||||
# The editor's usage lenses count usages; the server's own lenses would search every
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
"dompurify": "^3.4.17",
|
||||
"emmet": "2.4.11",
|
||||
"immer": "^11.1.21",
|
||||
"katex": "^0.19.1",
|
||||
"marked": "^18.1.1",
|
||||
"mermaid": "12.1.0",
|
||||
"react": "^19.1.0",
|
||||
|
||||
@@ -116,6 +116,7 @@
|
||||
"text/apply_100_changes_1mb": 1000,
|
||||
"text/diff_two_edits_1mb": 10000,
|
||||
"text/diff_every_line_1mb": 100000,
|
||||
"text/diff_one_edit_5mb": 2000,
|
||||
"text/offset_to_pos_round_trip": 5,
|
||||
"text/pos_to_byte": 5,
|
||||
"text/text_for_save_crlf_1mb": 1000,
|
||||
@@ -141,6 +142,7 @@
|
||||
"search_5k/literal": 100000,
|
||||
"search_5k/regex": 100000,
|
||||
"search_5k/dense_limit": 20000,
|
||||
"search_dense_files/24x40k_limit": 20000,
|
||||
|
||||
"plugins/load_50": 20000,
|
||||
"plugins/cold_activation": 30000,
|
||||
|
||||
@@ -104,6 +104,8 @@
|
||||
"--fg-deprecated": "#8c8f95",
|
||||
"--bg-identifier-under-caret": "#2e353f",
|
||||
"--bg-identifier-under-caret-write": "#402f33",
|
||||
"--fg-identifier-under-caret": "inherit",
|
||||
"--fg-identifier-under-caret-write": "inherit",
|
||||
"--fg-inlay": "#75869d",
|
||||
"--bg-inlay": "#303944",
|
||||
"--wave-typo": "#59a869",
|
||||
|
||||
+5
-2
@@ -232,7 +232,8 @@ The full table is `UI_KEYS` in [`src/features/plugins/intellijTheme.ts`](../src/
|
||||
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
|
||||
| `--syn-rainbow-1` … `--syn-rainbow-5` (Semantic highlighting, rainbow indent guides) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
|
||||
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES` (effect colour) |
|
||||
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
|
||||
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
|
||||
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
|
||||
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
|
||||
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
|
||||
| `--ansi-*` | `CONSOLE_*_OUTPUT` (`CONSOLE_DARKGRAY_OUTPUT` is bright black, `CONSOLE_GRAY_OUTPUT` white) |
|
||||
@@ -332,7 +333,7 @@ a token.
|
||||
|
||||
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
|
||||
|
||||
269 themeable tokens: 125 in the UI theme file, 144 in the editor colour scheme file.
|
||||
271 themeable tokens: 125 in the UI theme file, 146 in the editor colour scheme file.
|
||||
|
||||
### Surfaces (UI theme)
|
||||
|
||||
@@ -528,6 +529,8 @@ a token.
|
||||
| `--fg-deprecated` | `#8c8f95` | `#6c707e` |
|
||||
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
|
||||
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
|
||||
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
|
||||
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
|
||||
| `--fg-inlay` | `#868a91` | `#73767c` |
|
||||
| `--bg-inlay` | `#393b40` | `#00000012` |
|
||||
| `--wave-error` | `#fa6675` | `#f50000` |
|
||||
|
||||
Generated
+11
@@ -119,6 +119,9 @@ importers:
|
||||
immer:
|
||||
specifier: ^11.1.21
|
||||
version: 11.1.21
|
||||
katex:
|
||||
specifier: ^0.19.1
|
||||
version: 0.19.1
|
||||
marked:
|
||||
specifier: ^18.1.1
|
||||
version: 18.1.1
|
||||
@@ -1799,6 +1802,10 @@ packages:
|
||||
resolution: {integrity: sha512-/B6p9eY9DX7aHBfpkHdpirDTZ5QH9xTwL9y837PWuzuv41O5jFdqNQwVQEQsimY0/iVNkwBY4+4hMfhQ7d4Dbw==}
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==}
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
|
||||
|
||||
@@ -3792,6 +3799,10 @@ snapshots:
|
||||
dependencies:
|
||||
commander: 15.1.0
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
commander: 15.1.0
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
|
||||
+19
-5
@@ -136,34 +136,48 @@
|
||||
window.removeEventListener("unhandledrejection", onRejection);
|
||||
window.removeEventListener("openidea:boot-error", onBootError);
|
||||
window.removeEventListener("openidea:boot-ready", onReady);
|
||||
window.removeEventListener("openidea:boot-question", onQuestion);
|
||||
window.removeEventListener("openidea:boot-answer", onAnswer);
|
||||
document.removeEventListener("visibilitychange", onVisibility);
|
||||
};
|
||||
// The timeout counts only while the window shows: a hidden or covered window gets no
|
||||
// animation frames, and the splash waits for those to finish startup.
|
||||
// The timeout counts only while the window shows and nothing waits for the user: a hidden
|
||||
// or covered window gets no animation frames, and the splash waits for those to finish
|
||||
// startup; a question asked over the splash (Trust Project) holds it until answered.
|
||||
let remaining = 60_000;
|
||||
let armedAt = 0;
|
||||
let timer;
|
||||
let questions = 0;
|
||||
const arm = () => {
|
||||
if (failed || ready || timer !== undefined || document.hidden) return;
|
||||
if (failed || ready || timer !== undefined || document.hidden || questions > 0) return;
|
||||
armedAt = Date.now();
|
||||
timer = window.setTimeout(
|
||||
() => show(rejection === undefined ? text.timeout : `${text.timeout}\n\nUnhandled rejection: ${rejection}`),
|
||||
remaining,
|
||||
);
|
||||
};
|
||||
const onVisibility = () => {
|
||||
if (!document.hidden) return arm();
|
||||
const pause = () => {
|
||||
if (timer === undefined) return;
|
||||
window.clearTimeout(timer);
|
||||
timer = undefined;
|
||||
remaining -= Date.now() - armedAt;
|
||||
};
|
||||
const onVisibility = () => (document.hidden ? pause() : arm());
|
||||
const onQuestion = () => {
|
||||
questions += 1;
|
||||
pause();
|
||||
};
|
||||
const onAnswer = () => {
|
||||
questions = Math.max(0, questions - 1);
|
||||
arm();
|
||||
};
|
||||
arm();
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
window.addEventListener("error", onError, true);
|
||||
window.addEventListener("unhandledrejection", onRejection);
|
||||
window.addEventListener("openidea:boot-error", onBootError);
|
||||
window.addEventListener("openidea:boot-ready", onReady);
|
||||
window.addEventListener("openidea:boot-question", onQuestion);
|
||||
window.addEventListener("openidea:boot-answer", onAnswer);
|
||||
})();
|
||||
|
||||
// Runs before the app's CSS loads: restores the last theme (theme.ts stores it)
|
||||
|
||||
@@ -170,6 +170,23 @@ describe("IntelliJ theme import", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("maps the caret identifier foregrounds (#4109)", () => {
|
||||
const s = convertIcls(`<scheme name="Caret" version="142" parent_scheme="Darcula"><attributes>
|
||||
<option name="IDENTIFIER_UNDER_CARET_ATTRIBUTES"><value>
|
||||
<option name="FOREGROUND" value="aa0000" /><option name="BACKGROUND" value="220000" />
|
||||
</value></option>
|
||||
<option name="WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES"><value>
|
||||
<option name="FOREGROUND" value="00aa00" /><option name="BACKGROUND" value="002200" />
|
||||
</value></option>
|
||||
</attributes></scheme>`);
|
||||
expect(s.tokens).toMatchObject({
|
||||
"--fg-identifier-under-caret": "#aa0000",
|
||||
"--bg-identifier-under-caret": "#220000",
|
||||
"--fg-identifier-under-caret-write": "#00aa00",
|
||||
"--bg-identifier-under-caret-write": "#002200",
|
||||
});
|
||||
});
|
||||
|
||||
it("only targets tokens that exist in tokens.css", () => {
|
||||
const declared = new Set([...css.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((m) => m[1]!));
|
||||
// Read with a fallback by the editor (no tokens.css default), still themeable.
|
||||
|
||||
@@ -93,10 +93,12 @@ db_connect trusted project_host bin
|
||||
db_connected trusted project_host bindings sync
|
||||
db_console_path always project_host bindings sync
|
||||
db_consoles always project_host bindings sync
|
||||
db_create_database trusted project_host bindings async
|
||||
db_database_catalog trusted project_host bindings async
|
||||
db_databases trusted project_host bindings async
|
||||
db_ddl trusted project_host bindings async
|
||||
db_disconnect trusted project_host bindings async
|
||||
db_drop_database trusted project_host bindings async
|
||||
db_dump_info trusted desktop bindings async
|
||||
db_execute trusted project_host bindings async
|
||||
db_explain trusted project_host bindings async
|
||||
@@ -194,6 +196,7 @@ deploy_sync trusted project_host bin
|
||||
deploy_test_connection always project_host bindings async
|
||||
deploy_upload trusted project_host bindings async
|
||||
diff_external_tool always desktop bindings async
|
||||
doc_autosave always project_host bindings async
|
||||
doc_close always project_host bindings async
|
||||
doc_edit always project_host bindings async
|
||||
doc_folding always project_host bindings async
|
||||
@@ -536,7 +539,7 @@ scaffold_options always project_host bin
|
||||
scaffold_requirements always project_host bindings async
|
||||
sdk_container_python trusted project_host bindings sync
|
||||
sdk_container_python_refresh trusted project_host bindings async
|
||||
sdk_detect trusted project_host bindings async
|
||||
sdk_detect outside_restricted project_host bindings async
|
||||
sdk_jdk_at trusted project_host bindings async
|
||||
sdk_locate_tools trusted project_host bindings async
|
||||
sdk_php_composer_install trusted project_host bindings async
|
||||
@@ -544,12 +547,12 @@ sdk_php_effective trusted project_host bin
|
||||
sdk_php_language_level trusted project_host bindings async
|
||||
sdk_php_xdebug trusted project_host bindings async
|
||||
sdk_project_libraries trusted project_host bindings async
|
||||
sdk_python_create_venv trusted project_host bindings async
|
||||
sdk_python_create_venv outside_restricted project_host bindings async
|
||||
sdk_python_effective trusted project_host bindings sync
|
||||
sdk_python_interpreter trusted project_host bindings async
|
||||
sdk_python_packages trusted project_host bindings async
|
||||
sdk_python_pip trusted project_host bindings async
|
||||
sdk_python_project_interpreters trusted project_host bindings async
|
||||
sdk_python_interpreter outside_restricted project_host bindings async
|
||||
sdk_python_packages outside_restricted project_host bindings async
|
||||
sdk_python_pip outside_restricted project_host bindings async
|
||||
sdk_python_project_interpreters outside_restricted project_host bindings async
|
||||
search_start always project_host bindings async
|
||||
search_validate always project_host bindings sync
|
||||
set_recent_project_groups always desktop bindings sync
|
||||
@@ -595,10 +598,10 @@ term_resize always project_host bin
|
||||
term_spawn always project_host bindings async
|
||||
term_store_image always project_host bindings async
|
||||
term_write always project_host bindings sync
|
||||
tools_install trusted project_host bindings async
|
||||
tools_list trusted project_host bindings async
|
||||
tools_uninstall trusted project_host bindings async
|
||||
tools_updates trusted project_host bindings async
|
||||
tools_install outside_restricted project_host bindings async
|
||||
tools_list outside_restricted project_host bindings async
|
||||
tools_uninstall outside_restricted project_host bindings async
|
||||
tools_updates outside_restricted project_host bindings async
|
||||
undo_workspace_edit always project_host bindings async
|
||||
user_font_data always desktop - async
|
||||
vcs_add_to_ignore trusted project_host bindings async
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { AuxKind } from "./platform/auxWindow";
|
||||
import { mountWindowRoot } from "./windowBoot";
|
||||
import { activateSecondaryWindow } from "./workbench/activateSecondary";
|
||||
|
||||
export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string }): Promise<void> {
|
||||
activateSecondaryWindow();
|
||||
switch (aux.kind) {
|
||||
case "settings": {
|
||||
const { bootSettingsWindow } = await import("./settingsWindowBoot");
|
||||
mountWindowRoot(bootSettingsWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
case "comparison": {
|
||||
const { bootComparisonWindow } = await import("./comparisonWindowBoot");
|
||||
mountWindowRoot(bootComparisonWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
case "diff": {
|
||||
const { bootDiffWindow } = await import("./diffWindowBoot");
|
||||
mountWindowRoot(bootDiffWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
case "deployment": {
|
||||
const { bootDeploymentWindow } = await import("./deploymentWindowBoot");
|
||||
mountWindowRoot(bootDeploymentWindow(aux.parent));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
-8
@@ -15,11 +15,24 @@ export const commands = {
|
||||
/** Answers a non-blocking question, without cancelling the current turn. */
|
||||
agentAnswerQuestion: (task: string, question: string, answer: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_answer_question", { task, question, answer })),
|
||||
agentArchive: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_archive", { task })),
|
||||
/** Content of `path` when the task started (left side of its diff). */
|
||||
agentBaseText: (task: string, path: IpcPath) => typedError<string | null, IdeError>(__TAURI_INVOKE("agent_base_text", { task, path })),
|
||||
/** Content of `path` as `view` compares it (without: when the task started), the left side of its diff. */
|
||||
agentBaseText: (task: string, path: IpcPath, view:
|
||||
/** Everything since the commit the task started from. */
|
||||
"sinceStart" |
|
||||
/** The uncommitted files against `HEAD`; commits made since the start stay. */
|
||||
"group" |
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn" | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("agent_base_text", { task, path, view })),
|
||||
/** Stops the task's current turn, or with `subagent` only that subagent's work. */
|
||||
agentCancel: (task: string, subagent: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_cancel", { task, subagent })),
|
||||
agentChanges: (task: string) => typedError<AgentChange[], IdeError>(__TAURI_INVOKE("agent_changes", { task })),
|
||||
/** The task's changed files as `view` compares them (without: since it started). */
|
||||
agentChanges: (task: string, view:
|
||||
/** Everything since the commit the task started from. */
|
||||
"sinceStart" |
|
||||
/** The uncommitted files against `HEAD`; commits made since the start stay. */
|
||||
"group" |
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn" | null) => typedError<AgentChange[], IdeError>(__TAURI_INVOKE("agent_changes", { task, view })),
|
||||
/**
|
||||
* Slash commands to complete for `provider` in `task`'s directory, or in the project
|
||||
* before a task exists (skills and custom commands on disk included).
|
||||
@@ -103,7 +116,9 @@ export const commands = {
|
||||
/** Everything since the commit the task started from. */
|
||||
"sinceStart" |
|
||||
/** The uncommitted files against `HEAD`; commits made since the start stay. */
|
||||
"group" | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })),
|
||||
"group" |
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn" | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })),
|
||||
/** Sends a queued message now, interrupting the current turn. */
|
||||
agentSendQueuedNow: (task: string, queued: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_send_queued_now", { task, queued })),
|
||||
/**
|
||||
@@ -272,10 +287,12 @@ export const commands = {
|
||||
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_console_path", { id })),
|
||||
/** The query consoles of data source `id`; `create` adds the next one first. */
|
||||
dbConsoles: (id: string, create: boolean) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
|
||||
dbCreateDatabase: (id: string, template: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_create_database", { id, template, statement })),
|
||||
dbDatabaseCatalog: (id: string, database: string) => typedError<DbCatalogSchema[], IdeError>(__TAURI_INVOKE("db_database_catalog", { id, database })),
|
||||
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
|
||||
dbDdl: (id: string, schema: string, table: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_ddl", { id, schema, table })),
|
||||
dbDisconnect: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_disconnect", { id })),
|
||||
dbDropDatabase: (id: string, database: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_drop_database", { id, database, statement })),
|
||||
/** What made the dump at `path` and whether it creates its own database (from its first bytes). */
|
||||
dbDumpInfo: (path: string) => typedError<DbDumpInfo, IdeError>(__TAURI_INVOKE("db_dump_info", { path })),
|
||||
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })),
|
||||
@@ -452,6 +469,11 @@ export const commands = {
|
||||
* (a remote window passes the sides as text).
|
||||
*/
|
||||
diffExternalTool: (left: ExternalDiffSide, right: ExternalDiffSide, title: string) => typedError<null, IdeError>(__TAURI_INVOKE("diff_external_tool", { left, right, title })),
|
||||
/**
|
||||
* An automatic save: `false` (nothing written) when the file changed on disk after the
|
||||
* buffer was edited, which only an explicit save overwrites.
|
||||
*/
|
||||
docAutosave: (doc: DocId) => typedError<boolean, IdeError>(__TAURI_INVOKE("doc_autosave", { doc })),
|
||||
docClose: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_close", { doc })),
|
||||
/**
|
||||
* Applies a CodeMirror change set; returns the new version. Rejects with
|
||||
@@ -1288,8 +1310,8 @@ export const commands = {
|
||||
*
|
||||
* Edits go through the document layer as one patch per file, so open editors
|
||||
* update live and undo the whole file's replacements in one step. Unsaved
|
||||
* editor buffers are replaced in place and left unsaved; files that were not
|
||||
* open are opened transiently, saved and closed.
|
||||
* editor buffers are replaced in place and left unsaved; other open documents
|
||||
* are saved, and files that were not open are opened transiently, saved and closed.
|
||||
*
|
||||
* With `all_in_scope` (Replace All after the search hit its match limit) the
|
||||
* scope is searched again without the limit and every match in it is replaced,
|
||||
@@ -1810,7 +1832,10 @@ export const commands = {
|
||||
webServesPage: (url: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("web_serves_page", { url })),
|
||||
/** Paths in an HTML document or stylesheet that name no existing file. */
|
||||
webUnresolvedReferences: (doc: DocId) => typedError<FileReference[], IdeError>(__TAURI_INVOKE("web_unresolved_references", { doc })),
|
||||
/** The built-in server's URL for `path` (started on first use). */
|
||||
/**
|
||||
* The built-in server's URL for `path` (started on first use). A file whose language is
|
||||
* HTML (Settings › File Types can make it so) is served as a page, whatever its extension.
|
||||
*/
|
||||
webUrl: (path: IpcPath) => typedError<string, IdeError>(__TAURI_INVOKE("web_url", { path })),
|
||||
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
|
||||
/** Release the opening window's reservation after navigation or cancellation. */
|
||||
@@ -2061,7 +2086,9 @@ export type AgentChangesView =
|
||||
/** Everything since the commit the task started from. */
|
||||
"sinceStart" |
|
||||
/** The uncommitted files against `HEAD`; commits made since the start stay. */
|
||||
"group";
|
||||
"group" |
|
||||
/** What the last turn changed, against the checkout as that turn started. */
|
||||
"lastTurn";
|
||||
|
||||
export type AgentCommand = {
|
||||
/** Without the leading `/`. */
|
||||
@@ -7417,6 +7444,10 @@ export type LanguageCodeStyle_Deserialize = {
|
||||
lineCommentAtFirstColumn?: boolean | null,
|
||||
/** Comment Code › Add a space at line comment start. */
|
||||
lineCommentAddSpace?: boolean | null,
|
||||
/** PHP: align `=>` in multi-line arrays after formatting (other languages ignore it). */
|
||||
alignKeyValuePairs?: boolean | null,
|
||||
/** PHP: align `=` of consecutive assignment statements after formatting. */
|
||||
alignConsecutiveAssignments?: boolean | null,
|
||||
};
|
||||
|
||||
/** Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit). */
|
||||
@@ -7433,6 +7464,10 @@ export type LanguageCodeStyle_Serialize = {
|
||||
lineCommentAtFirstColumn?: boolean | null,
|
||||
/** Comment Code › Add a space at line comment start. */
|
||||
lineCommentAddSpace?: boolean | null,
|
||||
/** PHP: align `=>` in multi-line arrays after formatting (other languages ignore it). */
|
||||
alignKeyValuePairs?: boolean | null,
|
||||
/** PHP: align `=` of consecutive assignment statements after formatting. */
|
||||
alignConsecutiveAssignments?: boolean | null,
|
||||
};
|
||||
|
||||
/** Language identifier, e.g. `rust`, `typescript`, `kotlin`. Matches LSP `languageId`. */
|
||||
@@ -8087,6 +8122,12 @@ export type MavenSettings = {
|
||||
activeProfiles?: string,
|
||||
/** Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ). */
|
||||
delegateBuild?: boolean,
|
||||
/**
|
||||
* Download `-sources.jar` of dependencies when the Java language server imports the
|
||||
* project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
|
||||
* from a library class's Download Sources banner.
|
||||
*/
|
||||
downloadSources?: boolean,
|
||||
};
|
||||
|
||||
/** Summary of one server discovered inside an external MCP configuration file. */
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { activate as editor } from "./editor/core";
|
||||
import { confirmLeave } from "./features/app/closeGuard";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { installMenuBridge } from "./features/app/menuBridge";
|
||||
import { trackRuntimeSettings } from "./features/settings/runtime";
|
||||
import { activate as vcs } from "./features/vcs";
|
||||
import { activateComparisonWindow, ComparisonWindow } from "./features/vcs/ComparisonWindow";
|
||||
import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/**
|
||||
* Comparison window of project window `parent`: changed files between two
|
||||
* revisions and their diffs, with the editor and Git but no workbench.
|
||||
*/
|
||||
export function bootComparisonWindow(parent: string): ComponentType {
|
||||
activateList("comparison window", [
|
||||
["locale", installLocaleSync],
|
||||
["settings", trackRuntimeSettings],
|
||||
["menu", installMenuBridge],
|
||||
["editor", editor],
|
||||
["vcs", vcs],
|
||||
["comparison", () => activateComparisonWindow(parent, (project) => confirmLeave(undefined, project))],
|
||||
]);
|
||||
installKeyboardDispatcher();
|
||||
return ComparisonWindow;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { activateDeploymentWindow, DeploymentWindow } from "./features/deployment/window";
|
||||
import { trackRuntimeSettings } from "./features/settings/runtime";
|
||||
import { activateDiffViewer } from "./features/vcs/diffViewer";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/**
|
||||
* Sync with Deployed window of project window `parent`: local files next to
|
||||
* their copies on a deployment server, with the diff viewer but no workbench.
|
||||
*/
|
||||
export function bootDeploymentWindow(parent: string): ComponentType {
|
||||
activateList("deployment window", [
|
||||
["locale", installLocaleSync],
|
||||
["settings", trackRuntimeSettings],
|
||||
["diff", activateDiffViewer],
|
||||
["deployment", () => activateDeploymentWindow(parent)],
|
||||
]);
|
||||
return DeploymentWindow;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { installMenuBridge } from "./features/app/menuBridge";
|
||||
import { trackRuntimeSettings } from "./features/settings/runtime";
|
||||
import { activate as vcs } from "./features/vcs";
|
||||
import { activateDiffWindow, DiffWindow } from "./features/vcs/DiffWindow";
|
||||
import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/**
|
||||
* Diff window of project window `parent`: one file's diff, with Git and its own
|
||||
* documents but no workbench.
|
||||
*/
|
||||
export function bootDiffWindow(parent: string): ComponentType {
|
||||
activateList("diff window", [
|
||||
["locale", installLocaleSync],
|
||||
["settings", trackRuntimeSettings],
|
||||
["menu", installMenuBridge],
|
||||
["vcs", vcs],
|
||||
["diff", () => activateDiffWindow(parent)],
|
||||
]);
|
||||
installKeyboardDispatcher();
|
||||
return DiffWindow;
|
||||
}
|
||||
@@ -49,6 +49,8 @@ export interface DocBackend {
|
||||
close(doc: DocId): Promise<void>;
|
||||
edit(doc: DocId, baseVersion: number, changes: TextChange[]): Promise<number>;
|
||||
save(doc: DocId): Promise<void>;
|
||||
/** An automatic save; `false` when the file changed on disk after the buffer was edited (nothing written). */
|
||||
autosave?(doc: DocId): Promise<boolean>;
|
||||
/** Re-check every open file for external changes missed by file watchers. */
|
||||
syncFromDisk?(): Promise<void>;
|
||||
snapshot(doc: DocId): Promise<DocumentInfo>;
|
||||
@@ -92,6 +94,7 @@ export const ipcBackend: DocBackend = {
|
||||
close: async (doc) => void (await call(commands.docClose(doc))),
|
||||
edit: (doc, baseVersion, changes) => call(commands.docEdit(doc, baseVersion, { changes })),
|
||||
save: async (doc) => void (await call(commands.docSave(doc))),
|
||||
autosave: (doc) => call(commands.docAutosave(doc)),
|
||||
syncFromDisk: async () => void (await call(commands.docSyncFromDisk())),
|
||||
snapshot: (doc) => call(commands.docSnapshot(doc)),
|
||||
setLineEnding: async (doc, le) => void (await call(commands.docSetLineEnding(doc, le))),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerEditorKind, type EditorKindContribution } from "@/workbench/contributions";
|
||||
import { registerEditorKind, setFileDecorations, type EditorKindContribution } from "@/workbench/contributions";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
@@ -166,3 +166,18 @@ describe("editor kinds' isBusy on tab-limit eviction", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Close non-modified files first", () => {
|
||||
it("keeps a tab with a VCS change, as Close Unmodified Tabs does", async () => {
|
||||
controller = new EditorController(createMemoryBackend({ "/p/a.ts": "a", "/p/b.ts": "b", "/p/c.ts": "c" }));
|
||||
controller.start();
|
||||
useProject.setState({ settings: { editor: { tabs: { tabLimit: 2, closingPolicy: "unchanged" } } } as never });
|
||||
setFileDecorations("vcs", new Map([["/p/a.ts", { color: "modified" }]]));
|
||||
try {
|
||||
for (const path of ["/p/a.ts", "/p/b.ts", "/p/c.ts"]) await controller.openFile(path);
|
||||
expect(pane().tabs.map((tab) => tab.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
|
||||
} finally {
|
||||
setFileDecorations("vcs", new Map());
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,11 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { EditorSelection, EditorState, Prec } from "@codemirror/state";
|
||||
import { Decoration, EditorView } from "@codemirror/view";
|
||||
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
|
||||
import { setSearchQuery } from "@codemirror/search";
|
||||
import { StreamLanguage } from "@codemirror/language";
|
||||
import { literalKindAt } from "./literals";
|
||||
import { selectionMarks } from "./selectionMarks";
|
||||
import { findStyles, markWidgetStyles } from "./theme";
|
||||
import {
|
||||
countMatches,
|
||||
findResultLines,
|
||||
@@ -41,6 +42,49 @@ function make(doc: string, o: Partial<FindOptions>, scope?: { from: number; to:
|
||||
|
||||
const sel = (v: EditorView) => [v.state.selection.main.from, v.state.selection.main.to];
|
||||
|
||||
class TextWidget extends WidgetType {
|
||||
toDOM() {
|
||||
const el = document.createElement("span");
|
||||
el.className = "widget";
|
||||
el.textContent = "hint";
|
||||
return el;
|
||||
}
|
||||
}
|
||||
|
||||
describe("widgets inside find matches", () => {
|
||||
it.each([
|
||||
["before the cursor side", Decoration.widget({ widget: new TextWidget(), side: -1 }).range(3)],
|
||||
["after the cursor side", Decoration.widget({ widget: new TextWidget(), side: 1 }).range(3)],
|
||||
["replacing text", Decoration.replace({ widget: new TextWidget() }).range(2, 4)],
|
||||
])("keep their own colour %s", (_name, widget) => {
|
||||
const view = new EditorView({
|
||||
parent: document.body,
|
||||
doc: "Session",
|
||||
extensions: [
|
||||
// At the top precedence, as only then does the match wrap the widget.
|
||||
Prec.highest(EditorView.decorations.of(Decoration.set(widget))),
|
||||
findExtension(),
|
||||
],
|
||||
});
|
||||
views.push(view);
|
||||
view.dispatch({
|
||||
effects: [
|
||||
setFindOpen.of(true),
|
||||
setSearchQuery.of(
|
||||
makeQuery({ search: "Session", caseSensitive: true, wholeWord: false, regexp: false, replace: "" }),
|
||||
),
|
||||
],
|
||||
});
|
||||
const el = view.contentDOM.querySelector<HTMLElement>(".cm-openidea-findMatch .widget")!;
|
||||
// Browsers reflect this property to the attribute; jsdom does not.
|
||||
el.setAttribute("contenteditable", el.contentEditable);
|
||||
expect(el.matches(Object.keys(markWidgetStyles)[0]!)).toBe(true);
|
||||
expect(Object.values(markWidgetStyles)[0]!.WebkitTextFillColor).toBe("currentcolor");
|
||||
// A text fill of `--fg-search-match` here would reach every widget in the match.
|
||||
expect(findStyles[".cm-openidea-findMatch"].WebkitTextFillColor).toBe("currentcolor");
|
||||
});
|
||||
});
|
||||
|
||||
describe("find backgrounds", () => {
|
||||
it.each([
|
||||
["semantic", Prec.highest],
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { codeFolding, foldEffect, foldService, foldedRanges } from "@codemirror/language";
|
||||
import { codeFolding, foldEffect, foldService, foldable, foldedRanges } from "@codemirror/language";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import {
|
||||
backendFoldingChanged,
|
||||
backendFolds,
|
||||
enclosingFoldRange,
|
||||
expandToLevelEffects,
|
||||
foldSelectionEffects,
|
||||
foldToExpand,
|
||||
foldsFromRanges,
|
||||
foldingExtension,
|
||||
foldToExpand,
|
||||
setBackendFolds,
|
||||
} from "./folding";
|
||||
|
||||
/** Folds `{ … }` blocks whose header line ends with `{`. */
|
||||
@@ -68,6 +73,29 @@ describe("foldToExpand", () => {
|
||||
describe("foldsFromRanges", () => {
|
||||
const fold = (start_line: number, end_line: number) => ({ start_line, end_line, kind: "region" as const });
|
||||
|
||||
it("collapses an import group beginning with a multiline statement to import only", () => {
|
||||
const s = EditorState.create({
|
||||
doc: [
|
||||
"import Widget, {",
|
||||
" Formatter,",
|
||||
" parseValue,",
|
||||
"} from './format.js';",
|
||||
"import { render } from './view.js';",
|
||||
"",
|
||||
].join("\n"),
|
||||
extensions: [foldingExtension(false)],
|
||||
});
|
||||
const ranges = [{ start_line: 0, end_line: 4, kind: "imports" as const }];
|
||||
const [f] = foldsFromRanges(s, ranges);
|
||||
expect(f).toEqual({ from: "import ".length, to: s.doc.line(5).to, kind: "imports" });
|
||||
const state = s.update({ effects: setBackendFolds.of(ranges) }).state;
|
||||
expect(foldable(state, state.doc.line(1).from, state.doc.line(1).to)).toEqual({ from: f!.from, to: f!.to });
|
||||
const view = new EditorView({ state, parent: document.createElement("div") });
|
||||
view.dispatch({ effects: foldEffect.of({ from: f!.from, to: f!.to }) });
|
||||
expect(view.dom.querySelector(".cm-line")?.textContent).toBe("import …");
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it("starts an Allman block's fold on its declaration line", () => {
|
||||
const s = EditorState.create({ doc: "namespace Demo\n{\n class A\n {\n }\n}\n" });
|
||||
const folds = foldsFromRanges(s, [fold(1, 5), fold(3, 4)]);
|
||||
@@ -159,3 +187,95 @@ describe("expandToLevelEffects", () => {
|
||||
expect(folded(s.update({ effects: expandToLevelEffects(s, 2) }).state)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fold gutter chevrons", () => {
|
||||
const doc = ["def f():", ' """doc', " more", ' """', " pass"].join("\n");
|
||||
|
||||
it("backendFoldingChanged fires when backend folds arrive, not on selection moves", () => {
|
||||
let changed = false;
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
extensions: [
|
||||
foldingExtension(true),
|
||||
// The same predicate the fold gutter's foldingChanged hook uses.
|
||||
EditorView.updateListener.of((u) => {
|
||||
if (backendFoldingChanged(u)) changed = true;
|
||||
}),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
|
||||
expect(changed).toBe(true);
|
||||
changed = false;
|
||||
view.dispatch({ selection: { anchor: 0 } });
|
||||
expect(changed).toBe(false);
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it("the gutter shows a chevron after backend folds arrive", () => {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, extensions: [foldingExtension(true)] }),
|
||||
parent: document.body,
|
||||
});
|
||||
const markers = () =>
|
||||
Array.from(view.dom.querySelectorAll<HTMLElement>(".cm-foldGutter .cm-gutterElement")).map(
|
||||
(el) => el.firstElementChild?.className ?? "",
|
||||
);
|
||||
const before = markers();
|
||||
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
|
||||
const after = markers();
|
||||
expect(after.join("|")).not.toBe(before.join("|"));
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("fold placeholder chip", () => {
|
||||
const doc = ["def f():", ' """doc', " more", ' """', " pass"].join("\n");
|
||||
|
||||
function foldedView() {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, extensions: [foldingExtension(true)] }),
|
||||
parent: document.body,
|
||||
});
|
||||
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
|
||||
return view;
|
||||
}
|
||||
|
||||
function folded(view: ReturnType<typeof foldedView>) {
|
||||
const out: Array<[number, number]> = [];
|
||||
foldedRanges(view.state).between(0, view.state.doc.length, (a, b) => void out.push([a, b]));
|
||||
return out;
|
||||
}
|
||||
|
||||
function fold(view: ReturnType<typeof foldedView>) {
|
||||
const [f] = view.state.field(backendFolds);
|
||||
view.dispatch({ effects: foldEffect.of({ from: f!.from, to: f!.to }) });
|
||||
}
|
||||
|
||||
it("clicking the chip expands the fold, repeatedly", () => {
|
||||
const view = foldedView();
|
||||
for (let i = 0; i < 3; i++) {
|
||||
fold(view);
|
||||
const chip = view.dom.querySelector<HTMLElement>(".cm-foldPlaceholder");
|
||||
expect(chip, `iteration ${i}`).not.toBeNull();
|
||||
chip!.click();
|
||||
expect(folded(view), `iteration ${i}`).toEqual([]);
|
||||
}
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it("a chip whose position is the fold's start line still expands", () => {
|
||||
const view = foldedView();
|
||||
const [f] = view.state.field(backendFolds);
|
||||
// A docstring fold starts at the end of its header line: a chip resolved
|
||||
// through the line block would land on that line and find no fold.
|
||||
expect(view.state.doc.lineAt(f!.from).to).toBe(f!.from);
|
||||
fold(view);
|
||||
const chip = view.dom.querySelector<HTMLElement>(".cm-foldPlaceholder")!;
|
||||
chip.click();
|
||||
expect(folded(view)).toEqual([]);
|
||||
view.destroy();
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
type Extension,
|
||||
type Line,
|
||||
} from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import type { EditorView, ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
codeFolding,
|
||||
foldEffect,
|
||||
@@ -64,12 +64,14 @@ export function foldsFromRanges(state: EditorState, ranges: readonly FoldRange[]
|
||||
continue;
|
||||
}
|
||||
const start = allmanHeader(state, first);
|
||||
const importHead = r.kind === "imports" && /^\s*import\s+/.exec(first.text);
|
||||
const from = importHead && /(?:\{|,)\s*$/.test(first.text) ? first.from + importHead[0].length : start.to;
|
||||
const trimmed = end.text.trimStart();
|
||||
// `}` / `)` / `]` on the last line stays visible after the placeholder, like IDEA. An import
|
||||
// run ending in `} from '…'` hides that whole statement; a bare `)` / `};` still shows.
|
||||
const delimiter = r.kind === "imports" ? /^[}\])]+[;,]?$/.test(trimmed.trimEnd()) : /^[}\])]/.test(trimmed);
|
||||
const to = delimiter ? end.from + (end.text.length - trimmed.length) : end.to;
|
||||
if (to > start.to) out.push({ from: start.to, to, kind: r.kind });
|
||||
if (to > from) out.push({ from, to, kind: r.kind });
|
||||
}
|
||||
return out.sort((a, b) => a.from - b.from || b.to - a.to);
|
||||
}
|
||||
@@ -101,8 +103,8 @@ function foldAtLine(folds: readonly BackendFold[], lineStart: number, lineEnd: n
|
||||
let best: BackendFold | null = null;
|
||||
for (let i = lo; i < folds.length && folds[i]!.from <= lineEnd; i++) {
|
||||
const f = folds[i]!;
|
||||
// Only folds whose header ends on this line (custom regions: on this line); keep the widest.
|
||||
if ((f.from === lineEnd || f.custom) && (!best || f.to > best.to)) best = f;
|
||||
// Multiline import groups and custom regions can start within their header line.
|
||||
if ((f.from === lineEnd || f.custom || f.kind === "imports") && (!best || f.to > best.to)) best = f;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -392,22 +394,40 @@ function chevron(open: boolean): HTMLElement {
|
||||
return span;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backend folds arrive asynchronously (`setBackendFolds`) and are not a document,
|
||||
* viewport or language change, so CodeMirror's fold gutter keeps the chevrons it
|
||||
* built before they arrived. A click then hits a gutter element at a stale line
|
||||
* and silently does nothing. Rebuild the markers whenever the backend field changes.
|
||||
*/
|
||||
export function backendFoldingChanged(update: ViewUpdate): boolean {
|
||||
return update.startState.field(backendFolds, false) !== update.state.field(backendFolds, false);
|
||||
}
|
||||
|
||||
export function foldingExtension(showOutline = true): Extension {
|
||||
return [
|
||||
// The chevron column sits right of contributed icon gutters (IDEA new UI).
|
||||
showOutline ? Prec.lowest(foldGutter({ markerDOM: chevron })) : [],
|
||||
showOutline ? Prec.lowest(foldGutter({ markerDOM: chevron, foldingChanged: backendFoldingChanged })) : [],
|
||||
backendFolds,
|
||||
backendFoldService,
|
||||
codeFolding({
|
||||
// A folded custom region shows its name, as in IDEA.
|
||||
preparePlaceholder: (state, range) => regionNameAt(state, range.from),
|
||||
placeholderDOM: (_view, onclick, name: string | null) => {
|
||||
placeholderDOM: (view, onclick, name: string | null) => {
|
||||
const el = document.createElement("span");
|
||||
el.className = "cm-foldPlaceholder";
|
||||
el.textContent = name ?? "…";
|
||||
el.title = "Expand";
|
||||
el.setAttribute("aria-label", "folded code");
|
||||
el.onclick = onclick;
|
||||
el.onclick = (event) => {
|
||||
// CodeMirror's own handler resolves the fold through the clicked line
|
||||
// block, which can miss a fold starting at a line boundary (docstring,
|
||||
// Allman header). Resolving at the chip's own position cannot miss.
|
||||
const folded = foldToExpand(view.state, view.posAtDOM(el));
|
||||
if (folded) view.dispatch({ effects: unfoldEffect.of(folded) });
|
||||
else onclick(event);
|
||||
event.preventDefault();
|
||||
};
|
||||
return el;
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -46,6 +46,7 @@ const theme = EditorView.baseTheme({
|
||||
boxDecorationBreak: "clone",
|
||||
// Unset (the default `inherit`): the declaration drops and the syntax colours show through.
|
||||
color: "var(--fg-editor-selection)",
|
||||
WebkitTextFillColor: "var(--fg-editor-selection)",
|
||||
},
|
||||
"&.cm-focused .cm-openidea-selected": {
|
||||
"--openidea-selected-bg": "var(--editor-selection, var(--bg-editor-selection))",
|
||||
|
||||
@@ -24,6 +24,8 @@ export const findStyles = {
|
||||
".cm-openidea-findMatch": {
|
||||
backgroundColor: "var(--editor-search)",
|
||||
color: "var(--fg-search-match, inherit)",
|
||||
// Its own colour, over the text fill of an identifier highlight around the match.
|
||||
WebkitTextFillColor: "currentcolor",
|
||||
borderRadius: "2px",
|
||||
},
|
||||
".cm-openidea-findExcluded": {
|
||||
@@ -40,6 +42,11 @@ export const findStyles = {
|
||||
},
|
||||
};
|
||||
|
||||
/** Marks colour text with an inherited text fill; widgets inside them keep their own colours. */
|
||||
export const markWidgetStyles = {
|
||||
'.cm-content [contenteditable="false"]': { WebkitTextFillColor: "currentcolor" },
|
||||
};
|
||||
|
||||
/** The caret and Settings › Editor › General › Appearance caret options (`caretExtension`), also for viewers. */
|
||||
export const caretStyles = {
|
||||
".cm-cursor, .cm-dropCursor": {
|
||||
@@ -219,6 +226,8 @@ export const openideaTheme = EditorView.theme({
|
||||
".cm-selectionMatch": {
|
||||
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
|
||||
},
|
||||
// IDEA paints these with IDENTIFIER_UNDER_CARET_ATTRIBUTES, except the selection itself.
|
||||
".cm-selectionMatch:not(.cm-selectionMatch-main)": { WebkitTextFillColor: "var(--fg-identifier-under-caret)" },
|
||||
// IDEA's MATCHED_BRACE_ATTRIBUTES (bold in dark schemes only) and MATCHED_TAG_NAME (never bold).
|
||||
".cm-matchingBracket, &.cm-focused .cm-matchingBracket": {
|
||||
backgroundColor: "var(--editor-brace)",
|
||||
@@ -343,6 +352,7 @@ export const openideaTheme = EditorView.theme({
|
||||
|
||||
// Find in file (cm/find.ts)
|
||||
...findStyles,
|
||||
...markWidgetStyles,
|
||||
// Find in Files preview matches (search/find/parts.tsx)
|
||||
".cm-openidea-searchResult": { backgroundColor: "var(--bg-search-result)" },
|
||||
|
||||
|
||||
@@ -272,6 +272,14 @@ export function tabTrailing(input: EditorInput, kinds: EditorKinds): ReactNode {
|
||||
}
|
||||
}
|
||||
|
||||
/** Unsaved changes or a VCS status: what Close Unmodified Tabs and the tab limit's policy keep. */
|
||||
function tabModified(tab: Tab): boolean {
|
||||
return (
|
||||
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
|
||||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color))
|
||||
);
|
||||
}
|
||||
|
||||
export class EditorController implements SlotHost {
|
||||
manager: DocumentManager;
|
||||
readonly slots = new Map<string, EditorSlot>();
|
||||
@@ -387,10 +395,11 @@ export class EditorController implements SlotHost {
|
||||
// Untitled buffers belong to the window, not a project: their tabs
|
||||
// survive the switch (the backend carries them into the new
|
||||
// registry) and their slots rebuild against the carried documents.
|
||||
// Closing to Welcome drops them; the leave guard already asked about them.
|
||||
const carriedUntitled: Tab[] = [];
|
||||
let carriedActive: string | null = null;
|
||||
const cs = useTabs.getState();
|
||||
for (const pane of Object.values(cs.panes)) {
|
||||
for (const pane of root || s.lightEdit ? Object.values(cs.panes) : []) {
|
||||
for (const tab of pane.tabs) {
|
||||
if (isUntitledUri(tab.input.path ?? "")) {
|
||||
carriedUntitled.push(tab);
|
||||
@@ -1440,8 +1449,7 @@ export class EditorController implements SlotHost {
|
||||
paneId,
|
||||
prefs.tabLimit,
|
||||
prefs.closingPolicy,
|
||||
(tab) =>
|
||||
inputDirty(tab.input, kinds) ?? !!(tab.input.path && useDocMeta.getState()[tab.input.path]?.dirty),
|
||||
tabModified,
|
||||
keep ?? current.panes[paneId]?.active ?? undefined,
|
||||
protect,
|
||||
)
|
||||
@@ -1725,13 +1733,10 @@ export class EditorController implements SlotHost {
|
||||
protect: (tab) => tab.pinned,
|
||||
});
|
||||
}
|
||||
/** Keeps tabs with unsaved changes or a VCS status (IDEA: tabs shown as modified). */
|
||||
/** Keeps tabs with unsaved changes or a VCS status (tabs shown as modified). */
|
||||
closeUnmodified(paneId: string): Promise<boolean> {
|
||||
const modified = (tab: Tab) =>
|
||||
(inputDirty(tab.input, useContributions.getState().editorKinds) ?? false) ||
|
||||
!!(tab.input.path && (useDocMeta.getState()[tab.input.path]?.dirty || getFileDecoration(tab.input.path)?.color));
|
||||
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, modified) : s), {
|
||||
protect: (tab) => tab.pinned || modified(tab),
|
||||
return this.removeGuarded((s) => (s.panes[paneId] ? closeUnmodified(s, paneId, tabModified) : s), {
|
||||
protect: (tab) => tab.pinned || tabModified(tab),
|
||||
});
|
||||
}
|
||||
closeReadOnly(paneId: string): Promise<boolean> {
|
||||
|
||||
Loaded 100 of 318 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user