дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 13:32:29 +02:00
Порівняти коміти
30
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
ced8655afe | ||
|
|
f2a372428c | ||
|
|
89524bd583 | ||
|
|
f90d94538d | ||
|
|
a4ad387085 | ||
|
|
f8a148c06d | ||
|
|
aa1a027162 | ||
|
|
b30716e22c | ||
|
|
7fb21003f3 | ||
|
|
ad8d32d9c7 | ||
|
|
08aef06844 | ||
|
|
3d5ec8a147 | ||
|
|
0f14314156 | ||
|
|
2413cc4b43 | ||
|
|
30291971e1 | ||
|
|
9f3d75976f | ||
|
|
72d9aad715 | ||
|
|
7264e7d66d | ||
|
|
10379a54f7 | ||
|
|
6564b9e6cb | ||
|
|
d437cd46f5 | ||
|
|
925d474274 | ||
|
|
89463afc18 | ||
|
|
c884aa4cc6 | ||
|
|
09108e02e3 | ||
|
|
2b6ca90457 | ||
|
|
3c3681ef2b | ||
|
|
b0d7bfef24 | ||
|
|
527add030a | ||
|
|
81c2fc9ace |
No files matched your search
@@ -156,6 +156,44 @@ jobs:
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- name: Restore Maven artifacts for Java build tests
|
||||
id: jbuild-maven-cache
|
||||
if: runner.environment == 'github-hosted'
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
|
||||
- name: Prepare Maven artifacts for Java build tests
|
||||
id: jbuild-maven
|
||||
if: runner.environment == 'github-hosted'
|
||||
timeout-minutes: 5
|
||||
shell: bash
|
||||
env:
|
||||
CACHE_HIT: ${{ steps.jbuild-maven-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
if [[ -z "${JAVA_HOME:-}" || ! -d "$JAVA_HOME/bin" ]] || ! command -v mvn >/dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
export MAVEN_OPTS="${MAVEN_OPTS:+$MAVEN_OPTS }-Dmaven.repo.local=$RUNNER_TEMP/jbuild-maven-repository"
|
||||
echo "MAVEN_OPTS=$MAVEN_OPTS" >> "$GITHUB_ENV"
|
||||
if [[ "$CACHE_HIT" == true ]]; then
|
||||
exit 0
|
||||
fi
|
||||
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
|
||||
for delay in 0 10 30; do
|
||||
sleep "$delay"
|
||||
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
|
||||
echo "prepared=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
exit 1
|
||||
- name: Save Maven artifacts for Java build tests
|
||||
if: steps.jbuild-maven.outputs.prepared == 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
name: Homebrew
|
||||
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Published stable release to write the cask for (e.g. v0.1.51)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: homebrew-tap
|
||||
|
||||
jobs:
|
||||
cask:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and token
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download DMGs
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p '*.dmg' -D assets
|
||||
- name: Write the cask
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: node scripts/homebrew-cask.ts "$TAG" assets tap/Casks/openidea.rb
|
||||
- name: Push to the tap
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
working-directory: tap
|
||||
run: |
|
||||
git add Casks/openidea.rb
|
||||
if git diff --cached --quiet; then
|
||||
echo "the cask is already at ${TAG#v}"
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git commit -m "openidea ${TAG#v}"
|
||||
git push
|
||||
@@ -178,3 +178,10 @@ jobs:
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
Створено
@@ -6745,6 +6745,7 @@ dependencies = [
|
||||
"objc2-web-kit 0.3.2",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"reqwest",
|
||||
"security-framework",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -33,6 +33,12 @@ its search-everything habits — to a native app with a Rust core.
|
||||
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
|
||||
On macOS you can also install it with Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Benchmark
|
||||
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
|
||||
|
||||
@@ -33,6 +33,12 @@ her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir
|
||||
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
|
||||
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
|
||||
|
||||
macOS'ta Homebrew ile de kurabilirsiniz:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Performans karşılaştırması
|
||||
|
||||
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
|
||||
|
||||
@@ -35,6 +35,12 @@ OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处
|
||||
编辑器、代码洞察、调试器、Git、终端、数据库客户端和 HTTP 客户端,支持 60 多种语言。
|
||||
提供 macOS、Windows 和 Linux 版本。
|
||||
|
||||
在 macOS 上也可以用 Homebrew 安装:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## 性能对比
|
||||
|
||||
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),
|
||||
|
||||
@@ -18,15 +18,9 @@ fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
Some((home, mvn))
|
||||
}
|
||||
|
||||
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
|
||||
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
|
||||
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
|
||||
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
|
||||
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
|
||||
const ROOT_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/pom.xml");
|
||||
const LIB_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/lib/pom.xml");
|
||||
const APP_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/app/pom.xml");
|
||||
|
||||
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
|
||||
struct Fixture {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>app</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,9 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>lib</artifactId>
|
||||
</project>
|
||||
@@ -0,0 +1,35 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>lib</module>
|
||||
<module>app</module>
|
||||
</modules>
|
||||
<properties>
|
||||
<maven.compiler.release>11</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<parameters>true</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
||||
@@ -260,8 +260,8 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
/// may be larger than the text, and a malformed one may lack the NUL.
|
||||
#[cfg(any(windows, test))]
|
||||
fn unicode_text(bytes: &[u8]) -> String {
|
||||
let units: Vec<u16> =
|
||||
bytes.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|&unit| unit != 0).collect();
|
||||
let (pairs, _) = bytes.as_chunks::<2>();
|
||||
let units: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).take_while(|&unit| unit != 0).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ pub enum ErrorData {
|
||||
JavaBuildProblems {
|
||||
problems: Vec<String>,
|
||||
},
|
||||
/// A remote backend of another OpenIDEA build still serves the project and refused to retire.
|
||||
RemoteBackendBusy,
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
|
||||
@@ -308,6 +308,14 @@ pub struct SessionInfo {
|
||||
pub parent: Option<DebugSessionId>,
|
||||
}
|
||||
|
||||
/// One owner's breakpoints, kept without a session and sent when one of its sessions starts.
|
||||
#[derive(Default)]
|
||||
struct OwnerBreakpoints {
|
||||
lines: BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
functions: Vec<FunctionBreakpoint>,
|
||||
data: Vec<DataBreakpoint>,
|
||||
}
|
||||
|
||||
/// Who started a session. Every event of the session, and of the child sessions
|
||||
/// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes
|
||||
/// listings such as [`DebugManager::sessions`].
|
||||
@@ -336,13 +344,12 @@ pub struct DebugManager {
|
||||
sessions: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
/// Session start order, for "the first session" semantics.
|
||||
order: Mutex<Vec<DebugSessionId>>,
|
||||
breakpoints: Mutex<BTreeMap<PathBuf, Vec<Breakpoint>>>,
|
||||
/// Breakpoints by owner (window): each window's sessions get only its own.
|
||||
breakpoints: Mutex<HashMap<String, OwnerBreakpoints>>,
|
||||
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
|
||||
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
|
||||
exception_choices: Mutex<BTreeMap<String, bool>>,
|
||||
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
|
||||
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
|
||||
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
|
||||
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
|
||||
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
jvm_finder: Mutex<jvm_memory::JvmFinder>,
|
||||
@@ -818,8 +825,6 @@ impl DebugManager {
|
||||
states: Mutex::default(),
|
||||
exception_choices: Mutex::default(),
|
||||
exception_classes: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)),
|
||||
})
|
||||
@@ -839,8 +844,24 @@ impl DebugManager {
|
||||
self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn stored_breakpoints(&self, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(path).cloned().unwrap_or_default()
|
||||
pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn function_breakpoints(&self, owner: &str) -> Vec<FunctionBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn data_breakpoints(&self, owner: &str) -> Vec<DataBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `owner`'s sessions that take breakpoint requests.
|
||||
fn configured_sessions(&self, owner: &str) -> Vec<Arc<Session>> {
|
||||
self.live_sessions()
|
||||
.into_iter()
|
||||
.filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Live sessions of `owner` (all owners when `None`).
|
||||
@@ -1291,8 +1312,10 @@ impl DebugManager {
|
||||
let (files, idle): (Vec<_>, Vec<_>) = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(p, b)| (p.clone(), b.clone()))
|
||||
.get(&s.owner.key)
|
||||
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
// Breakpoint states follow the owner's first session.
|
||||
@@ -1310,14 +1333,14 @@ impl DebugManager {
|
||||
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&s.owner.key);
|
||||
if !functions.is_empty()
|
||||
&& s.supports("supportsFunctionBreakpoints")
|
||||
&& let Err(e) = s.send_function_breakpoints(&functions).await
|
||||
{
|
||||
tracing::debug!("setFunctionBreakpoints failed: {e}");
|
||||
}
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&s.owner.key);
|
||||
if !data.is_empty()
|
||||
&& s.supports("supportsDataBreakpoints")
|
||||
&& let Err(e) = s.send_data_breakpoints(&data).await
|
||||
@@ -1470,26 +1493,59 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Breakpoints are kept per file even without a session and sent on start.
|
||||
/// Returns states from the first live session, or unverified states when none.
|
||||
/// `owner`'s breakpoints are kept per file even without a session and sent when one of
|
||||
/// its sessions starts. Returns states from its first live session, or unverified states.
|
||||
pub async fn set_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
{
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
if breakpoints.is_empty() {
|
||||
store.remove(&path);
|
||||
lines.remove(&path);
|
||||
} else {
|
||||
store.insert(path.clone(), breakpoints.clone());
|
||||
lines.insert(path.clone(), breakpoints.clone());
|
||||
}
|
||||
}
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending
|
||||
/// the files that changed to its sessions. A file the window no longer lists can't stay
|
||||
/// behind and be sent to every later session, whatever made the two lists diverge (#6116).
|
||||
pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap<PathBuf, Vec<Breakpoint>>) -> IdeResult<()> {
|
||||
let changed: Vec<(PathBuf, Vec<Breakpoint>)> = {
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect();
|
||||
let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new()));
|
||||
let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone()));
|
||||
let changed = removed.chain(changed).collect();
|
||||
*lines = files;
|
||||
changed
|
||||
};
|
||||
for (path, breakpoints) in changed {
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `owner`'s breakpoints (its window closed).
|
||||
pub fn forget_breakpoints(&self, owner: &str) {
|
||||
self.breakpoints.lock().remove(owner);
|
||||
}
|
||||
|
||||
async fn send_file_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() {
|
||||
continue;
|
||||
}
|
||||
for s in self.configured_sessions(owner) {
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
@@ -1640,16 +1696,39 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
|
||||
const MAX_FRAMES: u64 = 400;
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
let request = |start: u64, levels: u64| {
|
||||
session.conn.request_timeout(
|
||||
"stackTrace",
|
||||
json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }),
|
||||
json!({ "threadId": thread_id, "startFrame": start, "levels": levels }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
};
|
||||
let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) {
|
||||
Some(Value::Array(frames)) => frames,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let raw = match request(0, MAX_FRAMES).await {
|
||||
Ok(body) => frames_of(body),
|
||||
// java-debug fails the whole request when one frame's source lookup throws (on Windows,
|
||||
// a CGLIB proxy's `<generated>` source against `sourcePaths`): the frames come one at a
|
||||
// time instead, without the ones it cannot describe.
|
||||
// ponytail: one request per frame; page around the failing ones if deep stacks get slow.
|
||||
Err(first @ DapError::Failed { .. }) => {
|
||||
let Ok(top) = request(0, 1).await else { return Err(first.into()) };
|
||||
let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES);
|
||||
let mut raw = frames_of(top);
|
||||
for start in 1..total {
|
||||
if let Ok(body) = request(start, 1).await {
|
||||
raw.extend(frames_of(body));
|
||||
}
|
||||
}
|
||||
raw
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
|
||||
let frame = |f: &Value| {
|
||||
let mut frame = frame_from(f);
|
||||
@@ -1661,7 +1740,7 @@ impl DebugManager {
|
||||
}
|
||||
frame
|
||||
};
|
||||
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
|
||||
Ok(raw.iter().map(frame).collect())
|
||||
}
|
||||
|
||||
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
|
||||
@@ -1853,7 +1932,7 @@ impl DebugManager {
|
||||
if force {
|
||||
self.suspend_breakpoints(&session, Some(&path)).await?;
|
||||
}
|
||||
let stored = self.stored_breakpoints(&path);
|
||||
let stored = self.stored_breakpoints(&session.owner.key, &path);
|
||||
let sent: Vec<Breakpoint> =
|
||||
if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored };
|
||||
session.send_breakpoints(&path, &sent, Some(line)).await?;
|
||||
@@ -1868,10 +1947,15 @@ impl DebugManager {
|
||||
let files: Vec<PathBuf> = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
.get(&session.owner.key)
|
||||
.map(|b| {
|
||||
b.lines
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
|
||||
let mut failed = None;
|
||||
for (path, result) in files.into_iter().zip(sent) {
|
||||
@@ -1885,11 +1969,12 @@ impl DebugManager {
|
||||
if let Some(e) = failed {
|
||||
return Err(e.into());
|
||||
}
|
||||
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
|
||||
if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
session.send_function_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().functions = true;
|
||||
}
|
||||
if !self.data_breakpoints.lock().is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
session.send_data_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().data = true;
|
||||
}
|
||||
@@ -1899,8 +1984,11 @@ impl DebugManager {
|
||||
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
|
||||
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
|
||||
let pending = std::mem::take(&mut *session.pending_restore.lock());
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> = pending
|
||||
.files
|
||||
.into_iter()
|
||||
.map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path)))
|
||||
.collect();
|
||||
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
|
||||
for ((path, _), result) in files.iter().zip(sent) {
|
||||
if let Err(e) = result {
|
||||
@@ -1908,13 +1996,13 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
if pending.functions {
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_function_breakpoints(&functions).await {
|
||||
tracing::debug!("restoring function breakpoints failed: {e}");
|
||||
}
|
||||
}
|
||||
if pending.data {
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_data_breakpoints(&data).await {
|
||||
tracing::debug!("restoring data breakpoints failed: {e}");
|
||||
}
|
||||
@@ -2124,14 +2212,17 @@ impl DebugManager {
|
||||
Ok(hot_swap_result(&body))
|
||||
}
|
||||
|
||||
/// Stores method breakpoints (kept without a session, sent on start) and sends them to
|
||||
/// every configured session whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(&self, list: Vec<FunctionBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.function_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them
|
||||
/// to each of its configured sessions whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsFunctionBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_function_breakpoints(&list).await {
|
||||
@@ -2144,12 +2235,17 @@ impl DebugManager {
|
||||
Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled))))
|
||||
}
|
||||
|
||||
/// Stores field watchpoints and sends them to every configured session that supports them.
|
||||
pub async fn set_data_breakpoints(&self, list: Vec<DataBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.data_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that
|
||||
/// supports them.
|
||||
pub async fn set_data_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsDataBreakpoints") {
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsDataBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_data_breakpoints(&list).await {
|
||||
|
||||
@@ -126,6 +126,8 @@ struct Script {
|
||||
child_request: Option<Value>,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Fail each `stackTrace` request whose frames include this one (java-debug, one frame's source lookup throwing).
|
||||
failing_frame: Option<u64>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
debuggee_pid: Option<u32>,
|
||||
/// java-debug's spelling of the same event.
|
||||
@@ -206,6 +208,7 @@ impl Default for Script {
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
failing_frame: None,
|
||||
debuggee_pid: None,
|
||||
java_process_id: false,
|
||||
output_after_terminate: false,
|
||||
@@ -520,6 +523,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]}));
|
||||
}
|
||||
}
|
||||
"stackTrace" if let Some(bad) = script.failing_frame => {
|
||||
let start = msg["arguments"]["startFrame"].as_u64().unwrap();
|
||||
let end = (start + msg["arguments"]["levels"].as_u64().unwrap()).min(3);
|
||||
if (start..end).contains(&bad) {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "stackTrace", "success": false, "message": "Illegal char <<> at index 21: C:\\p\\com\\x\\<generated>"})
|
||||
);
|
||||
} else {
|
||||
let frames: Vec<Value> = (start..end)
|
||||
.map(|i| json!({"id": 10 + i, "name": format!("f{i}"), "line": 1, "column": 1}))
|
||||
.collect();
|
||||
ok!(msg, json!({"stackFrames": frames, "totalFrames": 3}));
|
||||
}
|
||||
}
|
||||
"stackTrace" => ok!(
|
||||
msg,
|
||||
json!({"stackFrames": [
|
||||
@@ -899,7 +916,7 @@ async fn full_protocol_flow() {
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
let disabled = Breakpoint { enabled: false, ..bp(2) };
|
||||
let cond = Breakpoint { condition: Some("x > 1".into()), ..bp(7) };
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
assert!(states.iter().all(|s| !s.verified), "no session yet");
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
@@ -981,7 +998,7 @@ async fn full_protocol_flow() {
|
||||
assert_eq!(asked["arguments"]["frameId"], 10);
|
||||
|
||||
// Live breakpoint updates reach the session.
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(0)]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(0)]).await.unwrap();
|
||||
assert!(states[0].verified);
|
||||
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
@@ -1005,7 +1022,7 @@ async fn full_protocol_flow() {
|
||||
async fn run_to_cursor_uses_temporary_breakpoint() {
|
||||
let h = harness(Script::default());
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.run_to(id, 1, path.clone(), 9, false).await.unwrap();
|
||||
@@ -1037,7 +1054,7 @@ async fn stop_terminates_and_disconnects() {
|
||||
#[tokio::test]
|
||||
async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() {
|
||||
let h = harness(Script { empty_thread_responses: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
let start = h.start(LaunchConfig {
|
||||
adapter: "unity".into(),
|
||||
request: "attach".into(),
|
||||
@@ -1889,7 +1906,7 @@ fn function_bp(name: &str, enabled: bool) -> FunctionBreakpoint {
|
||||
async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let h = harness(Script::default());
|
||||
let cond = FunctionBreakpoint { condition: Some("n > 1".into()), ..function_bp("com.a.B#run", true) };
|
||||
let states = h.manager.set_function_breakpoints(vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
let states = h.manager.set_function_breakpoints(&h.owner.key, vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
assert!(!states[0].verified && states[1].message.as_deref() == Some("Disabled"), "no session yet");
|
||||
let watch = DataBreakpoint {
|
||||
data_id: "Req#count".into(),
|
||||
@@ -1898,7 +1915,7 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
hit_condition: Some("2".into()),
|
||||
enabled: true,
|
||||
};
|
||||
h.manager.set_data_breakpoints(vec![watch]).await.unwrap();
|
||||
h.manager.set_data_breakpoints(&h.owner.key, vec![watch]).await.unwrap();
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
assert_eq!(
|
||||
@@ -1914,8 +1931,11 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let pos = |c: &str| order.iter().position(|x| x == c).unwrap();
|
||||
assert!(pos("setFunctionBreakpoints") < pos("configurationDone"));
|
||||
|
||||
let states =
|
||||
h.manager.set_function_breakpoints(vec![function_bp("missing", true), function_bp("ok", true)]).await.unwrap();
|
||||
let states = h
|
||||
.manager
|
||||
.set_function_breakpoints(&h.owner.key, vec![function_bp("missing", true), function_bp("ok", true)])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((states[0].verified, states[1].verified), (false, true), "live states from the session");
|
||||
|
||||
let info = h.manager.data_breakpoint_info(id, 101, "count".into(), Some(10)).await.unwrap();
|
||||
@@ -1958,10 +1978,13 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
let h = harness(Script::default());
|
||||
let a = PathBuf::from("/p/a.py");
|
||||
let b = PathBuf::from("/p/b.py");
|
||||
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager
|
||||
.set_breakpoints(&h.owner.key, PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }])
|
||||
.await
|
||||
.unwrap();
|
||||
h.manager.set_function_breakpoints(&h.owner.key, vec![function_bp("run", true)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let sent_for = |path: &str| -> Vec<Value> {
|
||||
@@ -1995,10 +2018,10 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
#[tokio::test]
|
||||
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
|
||||
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
let off = PathBuf::from("/p/off.py");
|
||||
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
// Waiting for each answer before the next request would stall until the request timeout.
|
||||
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
|
||||
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
|
||||
@@ -2009,6 +2032,40 @@ async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_get_only_their_windows_breakpoints_and_a_replaced_list_drops_stale_files() {
|
||||
let h = harness(Script::default());
|
||||
let other = "project-2";
|
||||
h.manager.set_breakpoints(other, PathBuf::from("/p/other.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(other, vec![function_bp("elsewhere", true)]).await.unwrap();
|
||||
let stale = PathBuf::from("/p/stale.py");
|
||||
h.manager.set_breakpoints(&h.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let paths = || -> Vec<(Value, Value)> {
|
||||
requests(&h, "setBreakpoints")
|
||||
.into_iter()
|
||||
.map(|r| (r["source"]["path"].clone(), r["breakpoints"].clone()))
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(paths(), [(json!("/p/stale.py"), json!([{"line": 3}]))], "another window's file is not sent");
|
||||
assert!(requests(&h, "setFunctionBreakpoints").is_empty(), "nor its method breakpoints");
|
||||
|
||||
// The window's list no longer has the stale file (#6116): replacing clears it in the session...
|
||||
let kept = PathBuf::from("/p/kept.py");
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths()[1..], [(json!("/p/stale.py"), json!([])), (json!("/p/kept.py"), json!([{"line": 5}]))]);
|
||||
// ...unchanged files are not sent again...
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths().len(), 3);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
// ...and the next session gets only what the window lists.
|
||||
let h2 = harness(Script::default());
|
||||
h2.manager.set_breakpoints(&h2.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
h2.manager.replace_breakpoints(&h2.owner.key, BTreeMap::new()).await.unwrap();
|
||||
h2.start(config()).await.unwrap();
|
||||
assert!(requests(&h2, "setBreakpoints").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() {
|
||||
let h = harness(Script::default());
|
||||
@@ -2209,7 +2266,7 @@ async fn godot_gets_resolved_paths() {
|
||||
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
|
||||
);
|
||||
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
let id = manager.start(godot_launch(&link), owner).await.unwrap();
|
||||
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
|
||||
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
|
||||
@@ -2236,7 +2293,7 @@ async fn kotlin_configures_without_configuration_done_response() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let mut config = config();
|
||||
config.adapter = kotlin::ADAPTER.into();
|
||||
config.request = "attach".into();
|
||||
@@ -2270,7 +2327,7 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
let (owner, events) = recording_owner("kotlin-probe");
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let h = Harness { manager, owner, events, log: Arc::default() };
|
||||
h.manager.set_breakpoints(source.clone(), vec![bp(5)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, source.clone(), vec![bp(5)]).await.unwrap();
|
||||
let id = h.manager.start_with(config.clone(), h.owner.clone(), |_| Some(adapter.clone())).await.unwrap();
|
||||
let stopped = h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "breakpoint")).await;
|
||||
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
|
||||
@@ -2292,6 +2349,21 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stack_trace_leaves_out_a_frame_the_adapter_cannot_describe() {
|
||||
let h = harness(Script { failing_frame: Some(1), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let frames = h.manager.stack_trace(id, 1).await.unwrap();
|
||||
assert_eq!(frames.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["f0", "f2"]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
|
||||
let h = harness(Script { failing_frame: Some(0), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let error = h.manager.stack_trace(id, 1).await.unwrap_err();
|
||||
assert!(error.message.contains("<generated>"), "{error:?}");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
@@ -2299,7 +2371,7 @@ async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
let native = r"D:\work\LoginController.cs";
|
||||
let h = harness(Script { source_path: Some(native.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(25)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(25)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "netcoredbg".into();
|
||||
let id = h.start(cfg).await.unwrap();
|
||||
@@ -2323,7 +2395,7 @@ async fn java_windows_source_paths_for_launch_and_attach() {
|
||||
] {
|
||||
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "java-debug".into();
|
||||
cfg.request = request.into();
|
||||
@@ -3418,7 +3490,7 @@ async fn kotlin_lsp_gets_real_paths_and_its_link_holds_nothing() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
assert_eq!(h.request("setBreakpoints")["arguments"]["source"]["path"], json!(path));
|
||||
let sent = &h.request("attach")["arguments"];
|
||||
|
||||
@@ -47,7 +47,7 @@ async fn debugpy_end_to_end() {
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| sink_events.lock().push(e));
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let bp = Breakpoint { line: 3, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(script.clone(), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![bp]).await.unwrap();
|
||||
let id = manager
|
||||
.start(
|
||||
LaunchConfig {
|
||||
@@ -74,7 +74,7 @@ async fn debugpy_end_to_end() {
|
||||
assert!(vars.iter().any(|v| v.name == "total"), "{vars:?}");
|
||||
let v = manager.evaluate(id, Some(frames[0].id), "total + 100".into()).await.unwrap();
|
||||
assert_eq!(v.value, "100");
|
||||
manager.set_breakpoints(script.clone(), vec![]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![]).await.unwrap();
|
||||
manager.resume(id, thread_id).await.unwrap();
|
||||
wait(&events, |e| matches!(e, DebugEvent::Output { output, .. } if output.contains("total 3"))).await;
|
||||
wait(&events, |e| matches!(e, DebugEvent::Terminated)).await;
|
||||
|
||||
@@ -96,6 +96,7 @@ async fn breakpoints_stepping_and_variables_in_a_real_godot() {
|
||||
let script_as_opened = dir.join("player.gd");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
script_as_opened.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -81,6 +81,7 @@ async fn listens_for_xdebug_until_stopped_with_path_mappings() {
|
||||
let local_script = local.join("index.php");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
local_script.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -261,7 +261,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let m = &run.manager;
|
||||
let line_bp =
|
||||
Breakpoint { line: case.loop_line, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
|
||||
let seen = run.seen();
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
@@ -356,9 +356,9 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
// Method breakpoint: continue → stops in `parse`.
|
||||
if caps.function_breakpoints {
|
||||
let fb = FunctionBreakpoint { name: case.function.into(), condition: None, hit_condition: None, enabled: true };
|
||||
let states = m.set_function_breakpoints(vec![fb]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_function_breakpoints("test", vec![fb]).await.map_err(|e| e.message)?;
|
||||
report.push(format!("method breakpoint `{}`: verified={}", case.function, states[0].verified));
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -368,8 +368,10 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push("method breakpoint: NOT HIT".into()),
|
||||
}
|
||||
m.set_function_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_function_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.step(s, thread, StepKind::Out).await.map_err(|e| e.message)?;
|
||||
run.stopped_after(seen).await.ok_or("no stop after step out of parse")?;
|
||||
@@ -378,7 +380,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
|
||||
// Force Step Over ignores the breakpoint inside parse.
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.force_step_over(s, thread).await.map_err(|e| e.message)?;
|
||||
let (_, t, reason) = run.stopped_after(seen).await.ok_or("no stop after force step over")?;
|
||||
@@ -409,8 +411,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
hit_condition: None,
|
||||
enabled: true,
|
||||
};
|
||||
let states = m.set_data_breakpoints(vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_data_breakpoints("test", vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -425,8 +427,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push(format!("watchpoint `{data_id}`: NOT HIT")),
|
||||
}
|
||||
m.set_data_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
m.set_data_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
}
|
||||
@@ -623,7 +625,7 @@ async fn attach_to_processes() {
|
||||
};
|
||||
let run = Run::new();
|
||||
run.manager
|
||||
.set_breakpoints(case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let id =
|
||||
|
||||
@@ -253,7 +253,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let mut report = Vec::new();
|
||||
let run = Run::new();
|
||||
let m = &run.manager;
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
|
||||
let (s, thread) = run.stopped(0, "the loop breakpoint").await?;
|
||||
@@ -312,7 +312,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
expect_line(&run.top(s2, t2).await?, LOOP_LINE, "continue")?;
|
||||
|
||||
// Without breakpoints, the program runs to its end.
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s2, t2).await.map_err(|e| e.message)?;
|
||||
run.wait(seen, "terminated", |s, e| (s == id && matches!(e, DebugEvent::Terminated)).then_some(())).await?;
|
||||
@@ -333,7 +333,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
report.push("continue to exit: output and terminated".into());
|
||||
|
||||
// Restart (the UI starts the same configuration again), then Stop while paused.
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
let again = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("restart: {}", e.message))?;
|
||||
let (s, thread) = run.stopped(seen, "the breakpoint after restart").await?;
|
||||
|
||||
@@ -110,6 +110,7 @@ async fn real_editor_attach_breakpoint_step_variables_and_detach() {
|
||||
let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32;
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"smoke",
|
||||
source.clone(),
|
||||
vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }],
|
||||
)
|
||||
|
||||
@@ -297,6 +297,8 @@ pub struct DbManager {
|
||||
type Session = Arc<tokio::sync::Mutex<Option<Held>>>;
|
||||
|
||||
const MAX_META_ROWS: usize = 100_000;
|
||||
/// Completion columns of the default schema, which are read without the shared cap.
|
||||
const MAX_SCHEMA_COMPLETION_ROWS: usize = 1_000_000;
|
||||
|
||||
/// Rows of catalog query `q`, run again as [`sql::postgres_legacy`] when a PostgreSQL server's
|
||||
/// catalog lacks a column it reads (openGauss, PostgreSQL 9).
|
||||
@@ -1429,13 +1431,34 @@ impl DbManager {
|
||||
let pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
let mut tables: Vec<CompletionTable> = Vec::new();
|
||||
if let Pool::Jdbc(p) = &*pool {
|
||||
return self.jdbc_completion(id, p).await;
|
||||
}
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let rows = match &*pool {
|
||||
Pool::Jdbc(p) => return self.jdbc_completion(id, p).await,
|
||||
Pool::Snowflake(p) => {
|
||||
tables = snowflake::meta::completion(p).await?;
|
||||
Vec::new()
|
||||
}
|
||||
_ => pool.rows(sql::completion_columns(driver), MAX_META_ROWS).await?,
|
||||
// The default schema is read in full: under a shared row cap, a schema with many
|
||||
// tables lost the columns of the tables sorting last (#6118). Other schemas share the cap.
|
||||
_ if !default_schema.is_empty() => {
|
||||
let only = sql::completion_columns(driver, sql::CompletionScope::Only(&default_schema));
|
||||
let mut rows = pool.rows(&only, MAX_SCHEMA_COMPLETION_ROWS).await?;
|
||||
let rest = sql::completion_columns(driver, sql::CompletionScope::Except(&default_schema));
|
||||
rows.extend(pool.rows(&rest, MAX_META_ROWS).await?);
|
||||
rows
|
||||
}
|
||||
_ => pool.rows(&sql::completion_columns(driver, sql::CompletionScope::All), MAX_META_ROWS).await?,
|
||||
};
|
||||
for r in rows {
|
||||
let mut it = r.into_iter().map(Option::unwrap_or_default);
|
||||
@@ -1471,16 +1494,6 @@ impl DbManager {
|
||||
})
|
||||
};
|
||||
let foreign_keys = group_foreign_keys(fk_rows, &tables);
|
||||
let default_schema = match sql::current_schema(driver) {
|
||||
None => "main".to_owned(),
|
||||
Some(q) => pool
|
||||
.rows(q, 1)
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.into_iter().next().flatten())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
Ok(CompletionModel { default_schema, tables, foreign_keys })
|
||||
}
|
||||
|
||||
|
||||
@@ -252,31 +252,47 @@ pub fn indexes(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which schemas a [`completion_columns`] query reads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CompletionScope<'a> {
|
||||
/// Every non-system schema, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
All,
|
||||
/// One schema, in full.
|
||||
Only(&'a str),
|
||||
/// Every non-system schema but this one, capped at [`COMPLETION_ROW_CAP`] rows.
|
||||
Except(&'a str),
|
||||
}
|
||||
|
||||
/// Rows a [`CompletionScope::All`] or [`CompletionScope::Except`] query returns at most.
|
||||
pub const COMPLETION_ROW_CAP: usize = 50_000;
|
||||
|
||||
/// Rows: `schema, table, kind (table/view), column, type, nullable (YES/NO), is_pk (0/1), has_default (0/1)`
|
||||
/// for SQL completion, grouped by table in column order.
|
||||
pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
match driver {
|
||||
pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
|
||||
let (query, schema, order) = match driver {
|
||||
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
|
||||
DbDriver::Clickhouse => {
|
||||
DbDriver::Clickhouse => (
|
||||
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
|
||||
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
|
||||
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
|
||||
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
|
||||
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0 \
|
||||
ORDER BY c.database, c.table, c.position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Sqlite => {
|
||||
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
|
||||
"c.database",
|
||||
"c.database, c.table, c.position",
|
||||
),
|
||||
DbDriver::Sqlite => (
|
||||
"SELECT 'main', m.name, m.type, p.name, p.type, CASE WHEN p.\"notnull\" = 0 THEN 'YES' ELSE 'NO' END, \
|
||||
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
|
||||
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
|
||||
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
|
||||
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
|
||||
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY m.name, p.cid"
|
||||
}
|
||||
// Identity columns own their sequence through an internal dependency (`attidentity` is PostgreSQL 10+).
|
||||
DbDriver::Postgres => {
|
||||
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
|
||||
"'main'",
|
||||
"m.name, p.cid",
|
||||
),
|
||||
DbDriver::Postgres => (
|
||||
"SELECT n.nspname, c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, a.attname, \
|
||||
format_type(a.atttypid, a.atttypmod), CASE WHEN a.attnotnull THEN 'NO' ELSE 'YES' END, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary \
|
||||
@@ -287,19 +303,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
|
||||
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
|
||||
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%' \
|
||||
ORDER BY n.nspname, c.relname, a.attnum LIMIT 50000"
|
||||
}
|
||||
DbDriver::Mysql => {
|
||||
AND n.nspname NOT LIKE 'pg\\_toast%' AND n.nspname NOT LIKE 'pg\\_temp%'",
|
||||
"n.nspname",
|
||||
"n.nspname, c.relname, a.attnum",
|
||||
),
|
||||
DbDriver::Mysql => (
|
||||
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
|
||||
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys') \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::SqlServer => {
|
||||
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::SqlServer => (
|
||||
"SELECT c.TABLE_SCHEMA, c.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
|
||||
c.COLUMN_NAME, c.DATA_TYPE, c.IS_NULLABLE, \
|
||||
CASE WHEN EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc \
|
||||
@@ -310,19 +328,21 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
|
||||
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA') \
|
||||
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION"
|
||||
}
|
||||
DbDriver::Snowflake => {
|
||||
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
|
||||
"c.TABLE_SCHEMA",
|
||||
"c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION",
|
||||
),
|
||||
DbDriver::Snowflake => (
|
||||
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
|
||||
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
|
||||
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
|
||||
FROM information_schema.columns c JOIN information_schema.tables t \
|
||||
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA' \
|
||||
ORDER BY c.table_schema, c.table_name, c.ordinal_position LIMIT 50000"
|
||||
}
|
||||
DbDriver::Oracle => {
|
||||
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
|
||||
"c.table_schema",
|
||||
"c.table_schema, c.table_name, c.ordinal_position",
|
||||
),
|
||||
DbDriver::Oracle => (
|
||||
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
|
||||
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
|
||||
@@ -334,10 +354,22 @@ pub fn completion_columns(driver: DbDriver) -> &'static str {
|
||||
AND kc.constraint_name = con.constraint_name WHERE con.constraint_type = 'P') k \
|
||||
ON k.owner = c.owner AND k.table_name = c.table_name AND k.column_name = c.column_name \
|
||||
WHERE c.owner NOT IN ('CTXSYS', 'DBSFWUSER', 'DVSYS', 'GSMADMIN_INTERNAL', 'LBACSYS', 'MDDATA', \
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL') \
|
||||
ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"
|
||||
}
|
||||
}
|
||||
'MDSYS', 'OLAPSYS', 'OUTLN', 'SYS', 'SYSTEM', 'XDB', 'XS$NULL')",
|
||||
"c.owner",
|
||||
"c.owner, c.table_name, c.column_id",
|
||||
),
|
||||
};
|
||||
let filter = match scope {
|
||||
CompletionScope::All => String::new(),
|
||||
CompletionScope::Only(s) => format!(" AND {schema} = {}", quote_literal(driver, s)),
|
||||
CompletionScope::Except(s) => format!(" AND {schema} <> {}", quote_literal(driver, s)),
|
||||
};
|
||||
let cap = match (scope, driver) {
|
||||
(CompletionScope::Only(_), _) | (_, DbDriver::Sqlite | DbDriver::SqlServer) => String::new(),
|
||||
(_, DbDriver::Oracle) => format!(" FETCH FIRST {COMPLETION_ROW_CAP} ROWS ONLY"),
|
||||
_ => format!(" LIMIT {COMPLETION_ROW_CAP}"),
|
||||
};
|
||||
format!("{query}{filter} ORDER BY {order}{cap}")
|
||||
}
|
||||
|
||||
/// Rows: `schema, table, constraint, column, ref schema, ref table, ref column`
|
||||
@@ -950,7 +982,7 @@ mod tests {
|
||||
let keys = indexes(driver, "default", "events");
|
||||
assert!(keys.contains("'PRIMARY KEY' AS index_name, 0 AS is_unique, primary_key AS expression"));
|
||||
assert!(keys.contains("SELECT name, 0, expr FROM system.data_skipping_indices"));
|
||||
let completion = completion_columns(driver);
|
||||
let completion = completion_columns(driver, CompletionScope::All);
|
||||
assert!(completion.contains("c.is_in_primary_key, 1"));
|
||||
assert!(completion.contains("ORDER BY c.database, c.table, c.position LIMIT 50000"));
|
||||
}
|
||||
@@ -1060,7 +1092,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
|
||||
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
|
||||
assert!(table_foreign_keys(DbDriver::SqlServer, "dbo", "t").contains("OBJECT_ID(N'[dbo].[t]')"));
|
||||
assert!(completion_columns(DbDriver::SqlServer).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
assert!(completion_columns(DbDriver::SqlServer, CompletionScope::All).contains("INFORMATION_SCHEMA.COLUMNS"));
|
||||
}
|
||||
|
||||
/// Under a case-sensitive or binary collation, catalog names only resolve as declared:
|
||||
@@ -1074,7 +1106,7 @@ mod tests {
|
||||
tables(d, "dbo"),
|
||||
columns(d, "dbo", "t"),
|
||||
indexes(d, "dbo", "t"),
|
||||
completion_columns(d).to_owned(),
|
||||
completion_columns(d, CompletionScope::All),
|
||||
foreign_keys(d).to_owned(),
|
||||
table_foreign_keys(d, "dbo", "t"),
|
||||
routines(d, "dbo").unwrap(),
|
||||
@@ -1141,7 +1173,7 @@ mod tests {
|
||||
assert!(indexes(DbDriver::Oracle, "hr", "t").contains("all_indexes"));
|
||||
assert!(foreign_keys(DbDriver::Oracle).contains("constraint_type = 'R'"));
|
||||
assert!(table_foreign_keys(DbDriver::Oracle, "hr", "t").contains("all_cons_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle).contains("all_tab_columns"));
|
||||
assert!(completion_columns(DbDriver::Oracle, CompletionScope::All).contains("all_tab_columns"));
|
||||
assert!(triggers(DbDriver::Oracle, "hr", "t").contains("all_triggers"));
|
||||
assert!(routines(DbDriver::Oracle, "hr").unwrap().contains("all_objects"));
|
||||
assert!(packages(DbDriver::Oracle, "hr").unwrap().contains("object_type = 'PACKAGE'"));
|
||||
@@ -1256,7 +1288,7 @@ mod tests {
|
||||
let columns = columns(driver, "PUBLIC", "ORDERS");
|
||||
assert!(columns.contains("'NUMBER(' || numeric_precision"), "{columns}");
|
||||
assert!(columns.contains("table_name = 'ORDERS' ORDER BY ordinal_position"), "{columns}");
|
||||
assert!(completion_columns(driver).contains("LIMIT 50000"));
|
||||
assert!(completion_columns(driver, CompletionScope::All).contains("LIMIT 50000"));
|
||||
assert!(routines(driver, "PUBLIC").unwrap().contains("information_schema.procedures"));
|
||||
assert!(sequences(driver, "PUBLIC").unwrap().contains("information_schema.sequences"));
|
||||
assert_eq!(
|
||||
@@ -1268,6 +1300,35 @@ mod tests {
|
||||
assert_eq!(crate::plan::explain_statement(driver, "select 1;"), "EXPLAIN USING TABULAR select 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_reads_the_default_schema_without_the_shared_cap() {
|
||||
// #6118: 5,000+ tables in one Oracle schema overflowed the shared cap, so tables
|
||||
// sorting last had no columns.
|
||||
let only = completion_columns(DbDriver::Oracle, CompletionScope::Only("APP's"));
|
||||
assert!(only.ends_with("AND c.owner = 'APP''s' ORDER BY c.owner, c.table_name, c.column_id"), "{only}");
|
||||
let rest = completion_columns(DbDriver::Oracle, CompletionScope::Except("APP"));
|
||||
assert!(rest.contains("AND c.owner <> 'APP' ORDER BY"), "{rest}");
|
||||
assert!(rest.ends_with(" FETCH FIRST 50000 ROWS ONLY"), "{rest}");
|
||||
let all = completion_columns(DbDriver::Oracle, CompletionScope::All);
|
||||
assert!(all.ends_with("'XS$NULL') ORDER BY c.owner, c.table_name, c.column_id FETCH FIRST 50000 ROWS ONLY"));
|
||||
for (driver, column) in [
|
||||
(DbDriver::Postgres, "n.nspname"),
|
||||
(DbDriver::Mysql, "c.table_schema"),
|
||||
(DbDriver::Clickhouse, "c.database"),
|
||||
(DbDriver::Snowflake, "c.table_schema"),
|
||||
(DbDriver::SqlServer, "c.TABLE_SCHEMA"),
|
||||
(DbDriver::Sqlite, "'main'"),
|
||||
] {
|
||||
let only = completion_columns(driver, CompletionScope::Only("app"));
|
||||
assert!(only.contains(&format!(" AND {column} = 'app' ORDER BY ")), "{only}");
|
||||
assert!(!only.contains("LIMIT") && !only.contains("FETCH FIRST"), "{only}");
|
||||
let rest = completion_columns(driver, CompletionScope::Except("app"));
|
||||
assert!(rest.contains(&format!(" AND {column} <> 'app' ORDER BY ")), "{rest}");
|
||||
let capped = !matches!(driver, DbDriver::Sqlite | DbDriver::SqlServer);
|
||||
assert_eq!(rest.ends_with(" LIMIT 50000"), capped, "{rest}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_catalog_queries_run_on_older_servers() {
|
||||
let pg = DbDriver::Postgres;
|
||||
@@ -1279,7 +1340,7 @@ mod tests {
|
||||
tables(pg, "s"),
|
||||
columns(pg, "s", "t"),
|
||||
indexes(pg, "s", "t"),
|
||||
completion_columns(pg).to_owned(),
|
||||
completion_columns(pg, CompletionScope::All),
|
||||
foreign_keys(pg).to_owned(),
|
||||
table_foreign_keys(pg, "s", "t"),
|
||||
triggers(pg, "s", "t"),
|
||||
@@ -1290,7 +1351,7 @@ mod tests {
|
||||
let upper = q.to_uppercase();
|
||||
assert!(!["LATERAL", "ORDINALITY", "ATTIDENTITY"].iter().any(|w| upper.contains(w)), "{q}");
|
||||
}
|
||||
assert_eq!(postgres_legacy(completion_columns(pg)), None);
|
||||
assert_eq!(postgres_legacy(&completion_columns(pg, CompletionScope::All)), None);
|
||||
let routines = postgres_legacy(&routines(pg, "s").unwrap()).unwrap();
|
||||
assert!(!routines.contains("prokind") && routines.contains("NOT p.proisagg"));
|
||||
assert_eq!(postgres_legacy(&indexes(pg, "s", "t")), None);
|
||||
|
||||
@@ -779,3 +779,40 @@ async fn table_grants_expand_the_acl_per_grantee() -> IdeResult<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Completion reads the default schema in full: 52,000 columns there passed the cap shared with
|
||||
/// the other schemas, and the tables sorting last lost theirs (#6118).
|
||||
#[tokio::test]
|
||||
async fn completion_reads_every_column_of_a_wide_default_schema() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let Some(db) = manager(&tmp).await else { return Ok(()) };
|
||||
let c = CancellationToken::new();
|
||||
let schema = format!("oi_wide_{}", uuid::Uuid::new_v4().simple());
|
||||
let mut sources = db.sources()?;
|
||||
let mut source = sources[0].clone();
|
||||
source.id = "wide".into();
|
||||
source.options.startup_script = format!("SET search_path = {schema}");
|
||||
sources.push(source);
|
||||
let password = server().map(|(.., password)| password);
|
||||
db.save_sources(sources).await?;
|
||||
db.set_password("wide", password, false).await?;
|
||||
db.execute("p", &format!("CREATE SCHEMA {schema}"), 1, &c).await?;
|
||||
let fill = format!(
|
||||
"DO $$ DECLARE cols text; BEGIN \
|
||||
SELECT string_agg('c' || g || ' int', ', ') INTO cols FROM generate_series(1, 200) g; \
|
||||
FOR i IN 1..260 LOOP EXECUTE format('CREATE TABLE {schema}.t%s (%s)', lpad(i::text, 3, '0'), cols); \
|
||||
END LOOP; END $$"
|
||||
);
|
||||
let result = async {
|
||||
db.execute("p", &fill, 1, &c).await?;
|
||||
let completion = db.completion("wide").await?;
|
||||
assert_eq!(completion.default_schema, schema);
|
||||
let wide: Vec<_> = completion.tables.iter().filter(|t| t.schema == schema).collect();
|
||||
assert_eq!(wide.len(), 260);
|
||||
assert!(wide.iter().all(|t| t.columns.len() == 200), "a table lost columns");
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
db.execute("p", &format!("DROP SCHEMA {schema} CASCADE"), 1, &c).await?;
|
||||
result
|
||||
}
|
||||
@@ -187,7 +187,7 @@ async fn sqlserver_introspection_works_under_a_case_sensitive_collation() {
|
||||
let fk = ["dbo", "Child", "FK_Child_Parent", "ParentId", "dbo", "Parent", "Id"];
|
||||
assert_eq!(cells(pool.rows(&sql::table_foreign_keys(d, "dbo", "Child"), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::foreign_keys(d), 100).await.unwrap()), [fk]);
|
||||
assert_eq!(cells(pool.rows(sql::completion_columns(d), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::completion_columns(d, sql::CompletionScope::All), 100).await.unwrap()).len(), 4);
|
||||
assert_eq!(cells(pool.rows(&sql::routines(d, "dbo").unwrap(), 100).await.unwrap())[0][..2], ["Touch", "procedure"]);
|
||||
drop(pool);
|
||||
master
|
||||
|
||||
@@ -46,18 +46,26 @@ fn main() {
|
||||
#[cfg(unix)]
|
||||
if args.first().is_some_and(|a| a == "--attach") {
|
||||
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
|
||||
eprintln!("usage: openidea-server --attach <project-path>");
|
||||
eprintln!("usage: openidea-server --attach <project-path> [--replace]");
|
||||
std::process::exit(2);
|
||||
};
|
||||
// `--replace`: stop another build's backend that still holds the project.
|
||||
let replace = args.get(2).is_some_and(|a| a == "--replace");
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
let code =
|
||||
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
let code = match ide_host::daemon::attach(
|
||||
&base,
|
||||
&home,
|
||||
project_path,
|
||||
replace,
|
||||
std::io::stdin(),
|
||||
std::io::stdout().lock(),
|
||||
) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
let mode = match args.as_slice() {
|
||||
|
||||
@@ -121,11 +121,13 @@ fn ensure_private_dir(dir: &Path) -> io::Result<()> {
|
||||
}
|
||||
|
||||
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
|
||||
/// `input` / `output` to its Unix socket.
|
||||
/// `input` / `output` to its Unix socket. With `replace`, a daemon of another build that
|
||||
/// refuses to retire is stopped first.
|
||||
pub fn attach(
|
||||
base: &Path,
|
||||
home: &Path,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
input: impl Read + Send + 'static,
|
||||
output: impl Write,
|
||||
) -> Result<(), String> {
|
||||
@@ -137,11 +139,11 @@ pub fn attach(
|
||||
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
|
||||
let hex = hasher.finalize().to_hex();
|
||||
let build = &hex.as_str()[..16];
|
||||
let stream = connect_or_spawn(&exe, &paths, build)?;
|
||||
let stream = connect_or_spawn(&exe, &paths, build, replace)?;
|
||||
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
|
||||
}
|
||||
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str, replace: bool) -> Result<UnixStream, String> {
|
||||
let lock_file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
@@ -153,8 +155,11 @@ fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<Unix
|
||||
flock(&lock_file, FlockOperation::LockExclusive)
|
||||
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
|
||||
|
||||
if let Some(stream) = existing_daemon(paths, build)? {
|
||||
return Ok(stream);
|
||||
match existing_daemon(paths, build) {
|
||||
Ok(Some(stream)) => return Ok(stream),
|
||||
Ok(None) => {}
|
||||
Err(e) if replace && e.contains(rpc::OTHER_BUILD_BUSY) => stop_daemon(&paths.socket)?,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
match std::fs::remove_file(&paths.socket) {
|
||||
@@ -232,10 +237,7 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
Err(io::Error::other("unexpected response from stopping daemon"))
|
||||
}
|
||||
}
|
||||
BUSY => Err(io::Error::other(
|
||||
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
|
||||
Reconnect with that build, then stop the remote backend before upgrading.",
|
||||
)),
|
||||
BUSY => Err(io::Error::other(rpc::OTHER_BUILD_BUSY)),
|
||||
_ => Err(io::Error::other("unrecognized remote backend response")),
|
||||
}
|
||||
};
|
||||
@@ -247,6 +249,63 @@ fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream
|
||||
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
|
||||
}
|
||||
|
||||
/// Stops the daemon serving `socket` (another build's, which refused to retire): asks it to
|
||||
/// shut down like the remote Stop Backend action does, and kills it if it hasn't after a while.
|
||||
fn stop_daemon(socket: &Path) -> Result<(), String> {
|
||||
let pids = daemon_pids(socket)?;
|
||||
if pids.is_empty() {
|
||||
return Err(format!("cannot find the backend serving {}", socket.display()));
|
||||
}
|
||||
let signal = |sig| {
|
||||
for pid in &pids {
|
||||
if let Some(pid) = rustix::process::Pid::from_raw(*pid) {
|
||||
let _ = rustix::process::kill_process(pid, sig);
|
||||
}
|
||||
}
|
||||
};
|
||||
let alive = || pids.iter().any(|pid| process_exists(*pid));
|
||||
signal(rustix::process::Signal::TERM);
|
||||
let deadline = Instant::now() + rpc::SHUTDOWN_TIMEOUT;
|
||||
while alive() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
if alive() {
|
||||
signal(rustix::process::Signal::KILL);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `pid` still runs: an exited process its parent hasn't reaped yet (a zombie) doesn't.
|
||||
fn process_exists(pid: i32) -> bool {
|
||||
if !rustix::process::Pid::from_raw(pid).is_some_and(|pid| rustix::process::test_kill_process(pid).is_ok()) {
|
||||
return false;
|
||||
}
|
||||
Command::new("ps")
|
||||
.args(["-o", "stat=", "-p", &pid.to_string()])
|
||||
.output()
|
||||
.map_or(true, |out| !String::from_utf8_lossy(&out.stdout).trim_start().starts_with('Z'))
|
||||
}
|
||||
|
||||
/// Processes started as `openidea-server --daemon <socket> <build>`.
|
||||
fn daemon_pids(socket: &Path) -> Result<Vec<i32>, String> {
|
||||
let out = Command::new("ps")
|
||||
.args(["-axww", "-o", "pid=", "-o", "args="])
|
||||
.output()
|
||||
.map_err(|e| format!("cannot list processes: {e}"))?;
|
||||
Ok(daemon_pids_in(&String::from_utf8_lossy(&out.stdout), &socket.to_string_lossy()))
|
||||
}
|
||||
|
||||
fn daemon_pids_in(ps: &str, socket: &str) -> Vec<i32> {
|
||||
ps.lines()
|
||||
.filter_map(|line| {
|
||||
let (pid, args) = line.trim_start().split_once(char::is_whitespace)?;
|
||||
let mut words = args.split_whitespace().skip_while(|w| *w != "--daemon").skip(1);
|
||||
(words.next() == Some(socket)).then(|| pid.parse().ok()).flatten()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn read_log_tail(file: &mut File, offset: u64) -> String {
|
||||
if file.seek(SeekFrom::Start(offset)).is_err() {
|
||||
return String::new();
|
||||
@@ -480,3 +539,19 @@ fn has_live_work(host: &Host) -> bool {
|
||||
.iter()
|
||||
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::daemon_pids_in;
|
||||
|
||||
#[test]
|
||||
fn finds_the_daemon_of_a_socket_in_the_process_list() {
|
||||
let ps = " 1 /sbin/init\n\
|
||||
581660 /root/.openidea/server/0.1.51/634a/openidea-server --daemon /root/.openidea/run/s-de2d.sock 634a\n\
|
||||
141712 /root/.openidea/server/0.1.53/e116/openidea-server --daemon /root/.openidea/run/s-a67f.sock e116\n\
|
||||
582484 /bin/bash --init-file /tmp/openidea-shell-integration-0.1.51/bash/openidea.bashrc -i\n\
|
||||
590000 grep --daemon /root/.openidea/run/s-de2d.sock.bak\n";
|
||||
assert_eq!(daemon_pids_in(ps, "/root/.openidea/run/s-de2d.sock"), [581660]);
|
||||
assert!(daemon_pids_in(ps, "/root/.openidea/run/s-none.sock").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -378,6 +378,7 @@ impl Host {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
self.mcp_agent_runs.forget_window(window);
|
||||
self.debugger.forget_breakpoints(self.owner_window(window));
|
||||
self.external_logs.write().remove(self.owner_window(window));
|
||||
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
|
||||
self.cancel_request(request);
|
||||
|
||||
@@ -32,12 +32,19 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut config = config;
|
||||
let enhanced = take_enhanced_redefinition(&mut config);
|
||||
let java_exec = java_exec_path(&config);
|
||||
let agents = if is_jvm_launch(&config) {
|
||||
let mut agents = if is_jvm_launch(&config) {
|
||||
ide_run::java_agent::current_for(java_exec.as_deref())
|
||||
} else {
|
||||
Default::default()
|
||||
ide_run::java_agent::Agents::default()
|
||||
};
|
||||
match enhanced {
|
||||
Some(Ok(option)) => agents.options.insert(0, option.to_owned()),
|
||||
Some(Err(note)) => agents.notes.push(note),
|
||||
None => {}
|
||||
}
|
||||
let config = add_java_agents(config, &agents.options);
|
||||
let mut config = match_java_debug_encoding(start_java_attach_listener(config, cfg!(windows)), cfg!(windows));
|
||||
if config.adapter == "debugpy"
|
||||
@@ -249,6 +256,21 @@ fn java_exec_path(config: &LaunchConfig) -> Option<std::path::PathBuf> {
|
||||
extra.get("javaExec").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(std::path::PathBuf::from)
|
||||
}
|
||||
|
||||
/// The configuration's Enhanced class redefinition (`enhancedClassRedefinition` in the launch
|
||||
/// extras, which this removes): for a JVM the debugger starts, JetBrains Runtime's flag, or the
|
||||
/// console line saying why the session runs without it.
|
||||
fn take_enhanced_redefinition(config: &mut LaunchConfig) -> Option<Result<&'static str, String>> {
|
||||
let Some(serde_json::Value::Object(mut extra)) =
|
||||
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let on = extra.remove("enhancedClassRedefinition")?.as_bool() == Some(true);
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
(on && is_jvm_launch(config))
|
||||
.then(|| ide_run::java_hotswap::enhanced_redefinition(java_exec_path(config).as_deref()))
|
||||
}
|
||||
|
||||
/// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options:
|
||||
/// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's
|
||||
/// `vmArguments` (a list).
|
||||
@@ -380,13 +402,25 @@ fn match_java_debug_encoding(mut config: LaunchConfig, windows: bool) -> LaunchC
|
||||
config
|
||||
}
|
||||
|
||||
/// This window's breakpoints of `path`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_breakpoints(path, breakpoints).await
|
||||
host.debugger.set_breakpoints(host.owner_window(window), path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of this window's line breakpoints with `files`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_replace_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
files: std::collections::BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
) -> IdeResult<()> {
|
||||
host.debugger.replace_breakpoints(host.owner_window(window), files).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -629,18 +663,20 @@ pub fn debug_capabilities(host: &Host, session: DebugSessionId) -> IdeResult<Deb
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_function_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_function_breakpoints(breakpoints).await
|
||||
host.debugger.set_function_breakpoints(host.owner_window(window), breakpoints).await
|
||||
}
|
||||
|
||||
/// Field watchpoints; states aligned with `breakpoints`.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_data_breakpoints(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
breakpoints: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
host.debugger.set_data_breakpoints(breakpoints).await
|
||||
host.debugger.set_data_breakpoints(host.owner_window(window), breakpoints).await
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -916,6 +952,49 @@ mod tests {
|
||||
assert_eq!(add_java_agents(config.clone(), &[]).extra_json, config.extra_json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enhanced_class_redefinition_is_taken_from_the_launch_extras() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let jdk = |name: &str, implementor: &str| {
|
||||
let home = tmp.path().join(name);
|
||||
std::fs::create_dir_all(home.join("bin")).unwrap();
|
||||
std::fs::write(home.join("release"), format!("IMPLEMENTOR=\"{implementor}\"\n")).unwrap();
|
||||
std::fs::write(home.join("bin/java"), "").unwrap();
|
||||
home.join("bin/java").to_string_lossy().into_owned()
|
||||
};
|
||||
let (jbr, temurin) = (jdk("jbr", "JetBrains s.r.o."), jdk("temurin", "Eclipse Adoptium"));
|
||||
let extras = |config: &LaunchConfig| {
|
||||
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()
|
||||
};
|
||||
|
||||
let mut config = launch(
|
||||
"java-debug",
|
||||
"launch",
|
||||
serde_json::json!({"javaExec": jbr, "vmArgs": "-Xmx1g", "enhancedClassRedefinition": true}),
|
||||
);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), Some(Ok(ide_run::java_hotswap::OPTION)));
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none(), "not passed on to the adapter");
|
||||
assert_eq!(extras(&config)["vmArgs"], "-Xmx1g");
|
||||
|
||||
let mut config =
|
||||
launch("java-debug", "launch", serde_json::json!({"javaExec": temurin, "enhancedClassRedefinition": true}));
|
||||
let note = take_enhanced_redefinition(&mut config).unwrap().unwrap_err();
|
||||
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
|
||||
let mut config = launch("java-debug", "launch", serde_json::json!({"enhancedClassRedefinition": true}));
|
||||
assert!(take_enhanced_redefinition(&mut config).unwrap().unwrap_err().contains("is unknown"));
|
||||
|
||||
// Off, absent, or not a JVM the debugger starts: nothing to add, and no note.
|
||||
for (adapter, request, extra) in [
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": false})),
|
||||
("java-debug", "launch", serde_json::json!({"javaExec": jbr})),
|
||||
("java-debug", "attach", serde_json::json!({"javaExec": jbr, "enhancedClassRedefinition": true})),
|
||||
] {
|
||||
let mut config = launch(adapter, request, extra);
|
||||
assert_eq!(take_enhanced_redefinition(&mut config), None);
|
||||
assert!(extras(&config).get("enhancedClassRedefinition").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_server_port_only_for_local_java_debug() {
|
||||
let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra));
|
||||
@@ -962,6 +1041,7 @@ ide_command::domain!(
|
||||
debug_listen_for_jvm,
|
||||
debug_pause,
|
||||
debug_redefine_classes,
|
||||
debug_replace_breakpoints,
|
||||
debug_resolve_variable,
|
||||
debug_restart_frame,
|
||||
debug_resume,
|
||||
|
||||
@@ -81,8 +81,8 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
|
||||
|
||||
/// Structure view: LSP document symbols when available (with tree-sitter
|
||||
/// visibility and type-alias kinds), tree-sitter otherwise.
|
||||
/// Tree-sitter answers come from the per-document tree cache (incremental
|
||||
/// re-parse); large documents get no syntax structure.
|
||||
/// Normal files reuse the per-document tree cache. Large Markdown files use
|
||||
/// the syntax parser's size limit for heading outlines.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<OutlineItem>> {
|
||||
let project = host.project(window)?;
|
||||
@@ -118,7 +118,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
|
||||
}
|
||||
items
|
||||
}
|
||||
None if snap.large => Vec::new(),
|
||||
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
|
||||
None => syntax(),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -222,6 +222,9 @@ impl Host {
|
||||
ide_sdk::apply::configure_python_extra_paths(cfg, &paths);
|
||||
}
|
||||
if cfg.name == "jdtls" {
|
||||
// Before anything reads the install the command resolves to.
|
||||
let managed = ide_tools::tools_dir(&data_dir).join("jdtls").join("bin").join("jdtls");
|
||||
ide_sdk::jdtls::skip_plain_launcher_wrappers(cfg, &managed);
|
||||
// A workspace member keeps its build model under its own key (Build Project).
|
||||
let cache = match &member {
|
||||
Some(member) if member != window_root => build_cache.join(crate::project::project_key(member)),
|
||||
|
||||
@@ -32,6 +32,10 @@ use std::sync::{Arc, OnceLock};
|
||||
/// doesn't know the event would show stale output.
|
||||
pub const PROTOCOL_VERSION: u32 = 4;
|
||||
pub const SESSION_REPLACED: &str = "session_replaced";
|
||||
/// What `openidea-server --attach` reports when another build's backend keeps the project
|
||||
/// (clients match it to offer stopping that backend).
|
||||
pub const OTHER_BUILD_BUSY: &str = "Another build of OpenIDEA still has this project open, is running tasks, or has \
|
||||
unsaved changes. Reconnect with that build, or stop its backend and open the project again.";
|
||||
pub const SHUTDOWN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90);
|
||||
|
||||
/// Advertised only by a persistent backend with an editable idle timeout.
|
||||
|
||||
@@ -27,24 +27,9 @@ async fn maven_launch_compiles_with_the_ides_java_build() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
write(
|
||||
&root,
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"lib/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(&root, "pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml"));
|
||||
write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
|
||||
write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
|
||||
write(
|
||||
&root,
|
||||
"lib/src/main/java/l/L.java",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
mod common;
|
||||
|
||||
use ide_core::{ChangeSet, TextChange};
|
||||
use ide_core::{ChangeSet, Pos, Range, SymbolKind, TextChange};
|
||||
use ide_host::{Host, catalogue::TrustClass, ops};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -51,6 +51,33 @@ async fn edits_loose_files_without_project_services() {
|
||||
assert!(!Arc::ptr_eq(&project, &light));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn large_markdown_has_structure_after_embedded_images() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("paper.md");
|
||||
let image = format!("\n\n", "A".repeat(64 * 1024));
|
||||
let text = format!("# Paper\n\n{}```text\n## Inside code\n```\n\n## Results\n", image.repeat(84));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let host = host(&tmp.path().join("app"));
|
||||
host.open_light("main", &path).unwrap();
|
||||
|
||||
let doc = ops::doc::doc_open(&host, "main", path).await.unwrap();
|
||||
assert!(doc.large);
|
||||
let outline = ops::doc::doc_outline(&host, "main", doc.id).await.unwrap();
|
||||
|
||||
assert_eq!(outline.len(), 1);
|
||||
let paper = &outline[0];
|
||||
assert_eq!(paper.kind, SymbolKind::Key);
|
||||
assert_eq!(paper.name, "Paper");
|
||||
assert_eq!(paper.selection_range, Range::new(Pos::new(0, 2), Pos::new(0, 7)));
|
||||
assert_eq!(paper.children.len(), 1);
|
||||
let results = &paper.children[0];
|
||||
assert_eq!(results.kind, SymbolKind::Key);
|
||||
assert_eq!(results.name, "Results");
|
||||
assert_eq!(results.selection_range, Range::new(Pos::new(174, 3), Pos::new(174, 10)));
|
||||
assert!(results.children.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn light_windows_ignore_project_scoped_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -782,7 +782,7 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(!rejected.status.success());
|
||||
assert!(String::from_utf8_lossy(&rejected.stderr).contains("Another build of OpenIDEA"), "{rejected:?}");
|
||||
assert!(String::from_utf8_lossy(&rejected.stderr).contains(ide_host::rpc::OTHER_BUILD_BUSY), "{rejected:?}");
|
||||
assert!(previous_build.try_wait().unwrap().is_none(), "the live backend was replaced");
|
||||
let resumed = old_open().await;
|
||||
assert_eq!(invoke(&resumed, "term_list", json!({})).await.unwrap()[0]["id"], term["id"]);
|
||||
@@ -798,6 +798,60 @@ async fn upgraded_build_refuses_live_work_and_then_replaces_idle_backend() {
|
||||
shutdown(&new).await;
|
||||
}
|
||||
|
||||
/// `--attach --replace` stops another build's backend that refuses to retire (#6119).
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn replace_stops_another_builds_busy_backend() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
const OLD_BUILD: &str = "fedcba9876543210";
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("h");
|
||||
let base = tmp.path().join("s");
|
||||
let project = home.join("demo");
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
let guard = DaemonGuard(ide_host::daemon::paths_for(&base, &home, "~/demo").unwrap().socket);
|
||||
let mut previous_build = tokio::process::Command::new(SERVER)
|
||||
.arg("--daemon")
|
||||
.arg(&guard.0)
|
||||
.arg(OLD_BUILD)
|
||||
.envs(server_env(&home, &base, 10_800))
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
until("old backend socket", || guard.0.exists()).await;
|
||||
let mut stream = 'connect: {
|
||||
for _ in 0..600 {
|
||||
match UnixStream::connect(&guard.0).await {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::ConnectionRefused => {
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
}
|
||||
other => break 'connect other.unwrap(),
|
||||
}
|
||||
}
|
||||
panic!("the old backend never accepted a connection");
|
||||
};
|
||||
stream.write_all(OLD_BUILD.as_bytes()).await.unwrap();
|
||||
assert_eq!(stream.read_u8().await.unwrap(), b'A');
|
||||
let (reader, writer) = stream.into_split();
|
||||
let old = Peer::connect(reader, writer, Arc::new(Client::default()));
|
||||
initialize(&old).await;
|
||||
let term = looping_terminal(&old, &project).await;
|
||||
old.kill();
|
||||
old.closed().await;
|
||||
|
||||
let client = Arc::new(Client::default());
|
||||
let args = ["--attach", "~/demo", "--replace"].map(str::to_owned).to_vec();
|
||||
let env = server_env(&home, &base, 10_800);
|
||||
let new = Peer::spawn(SERVER, &args, &home, &env, client, Box::new(|line| eprintln!("{line}"))).unwrap();
|
||||
initialize(&new).await;
|
||||
let old_exit = tokio::time::timeout(Duration::from_secs(15), previous_build.wait()).await.unwrap().unwrap();
|
||||
assert!(old_exit.success(), "the old backend did not shut down cleanly: {old_exit:?}");
|
||||
until("its terminal stopped", || !pid_alive(term["pid"].as_u64().unwrap() as u32)).await;
|
||||
assert!(invoke(&new, "term_list", json!({})).await.unwrap().as_array().unwrap().is_empty());
|
||||
shutdown(&new).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "requires a Docker context with Docker Compose and the busybox image"]
|
||||
async fn compose_service_survives_disconnect_and_is_removed_on_stop() {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Enhanced class redefinition for Java debug sessions: on JetBrains Runtime,
|
||||
//! `-XX:+AllowEnhancedClassRedefinition` lets HotSwap (Reload Changed Classes) apply
|
||||
//! structural changes such as added or removed methods and fields. Other JVMs refuse to
|
||||
//! start with the flag, so it is added only when the launched JDK is JetBrains Runtime.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The JVM flag JetBrains Runtime takes.
|
||||
pub const OPTION: &str = "-XX:+AllowEnhancedClassRedefinition";
|
||||
|
||||
/// The flag when `java` (the launched `bin/java`; `None` when unknown) is JetBrains Runtime,
|
||||
/// else the console line saying why the session runs without it.
|
||||
pub fn enhanced_redefinition(java: Option<&Path>) -> Result<&'static str, String> {
|
||||
let java = java.filter(|java| java.components().count() > 1);
|
||||
match java {
|
||||
Some(java) if crate::java_agent::jdk_allows(Some(java), Some("jetbrains")) => Ok(OPTION),
|
||||
Some(java) => Err(format!(
|
||||
"Enhanced class redefinition is off for this session: {} is not a JetBrains Runtime. \
|
||||
Choose a JetBrains Runtime as the configuration's JRE.",
|
||||
java.display()
|
||||
)),
|
||||
None => Err("Enhanced class redefinition is off for this session: the JDK it runs on is unknown. \
|
||||
Choose a JetBrains Runtime as the configuration's JRE."
|
||||
.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn jdk(dir: &Path, implementor: &str) -> std::path::PathBuf {
|
||||
let bin = dir.join("bin");
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
std::fs::write(dir.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
|
||||
let java = bin.join("java");
|
||||
std::fs::write(&java, "").unwrap();
|
||||
java
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jetbrains_runtime_gets_the_flag() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let java = jdk(tmp.path(), "JetBrains s.r.o.");
|
||||
assert_eq!(enhanced_redefinition(Some(&java)), Ok(OPTION));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_jdks_get_a_note_instead() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let java = jdk(tmp.path(), "Eclipse Adoptium");
|
||||
let note = enhanced_redefinition(Some(&java)).unwrap_err();
|
||||
assert!(note.contains("is not a JetBrains Runtime"), "{note}");
|
||||
assert!(note.contains(&java.display().to_string()), "{note}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_jdk_gets_a_note() {
|
||||
assert!(enhanced_redefinition(None).unwrap_err().contains("is unknown"));
|
||||
// A bare `java` names no JDK.
|
||||
assert!(enhanced_redefinition(Some(Path::new("java"))).unwrap_err().contains("is unknown"));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub mod gradle_jvm;
|
||||
pub mod import;
|
||||
pub mod java_agent;
|
||||
pub mod java_cmdline;
|
||||
pub mod java_hotswap;
|
||||
pub mod junit;
|
||||
mod process;
|
||||
pub mod python_path;
|
||||
|
||||
@@ -228,6 +228,45 @@ pub fn java_args(install: &JdtlsInstall, java_major: u32, script_args: &[String]
|
||||
args
|
||||
}
|
||||
|
||||
/// Whether `script` is a hand-written `jdtls` that starts the Equinox launcher with `java -jar`
|
||||
/// itself, like the one opencode puts into a JDK's `bin` (#6062). It knows none of the release
|
||||
/// script's options: each `--jvm-arg=` (the Lombok agent, heap, proxy) reaches jdtls as an
|
||||
/// application argument instead of a JVM option, and its own `-data` comes before the IDE's.
|
||||
fn is_plain_launcher_wrapper(script: &Path) -> bool {
|
||||
if std::fs::metadata(script).map_or(true, |m| m.len() > 64 * 1024) {
|
||||
return false;
|
||||
}
|
||||
let Ok(bytes) = std::fs::read(script) else { return false };
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
text.contains("org.eclipse.equinox.launcher") && !text.contains("--jvm-arg")
|
||||
}
|
||||
|
||||
/// Picks the `jdtls` to start when the first one on `PATH` is a [plain launcher
|
||||
/// wrapper](is_plain_launcher_wrapper): the next one there that isn't, else the IDE's own
|
||||
/// install (`managed`, `<tools>/jdtls/bin/jdtls`), which is offered for install while missing.
|
||||
/// A command naming a path is the user's choice and kept.
|
||||
pub fn skip_plain_launcher_wrappers(cfg: &mut LanguageServerConfig, managed: &Path) {
|
||||
if cfg.name != "jdtls" || Path::new(&cfg.command).components().count() != 1 {
|
||||
return;
|
||||
}
|
||||
let search = cfg.env.get("PATH").map(std::ffi::OsString::from).unwrap_or_else(ide_core::tool_path::search_path);
|
||||
let mut candidates = std::env::split_paths(&search)
|
||||
.filter(|dir| !dir.as_os_str().is_empty())
|
||||
.filter_map(|dir| ide_core::process::find_executable(&cfg.command, dir.as_os_str()));
|
||||
let Some(first) = candidates.next() else { return };
|
||||
if !is_plain_launcher_wrapper(&first) {
|
||||
return;
|
||||
}
|
||||
let chosen = candidates.find(|c| !is_plain_launcher_wrapper(c)).unwrap_or_else(|| managed.to_path_buf());
|
||||
tracing::warn!(
|
||||
"{} starts jdtls with `java -jar` itself and ignores the IDE's JVM arguments (Lombok agent, \
|
||||
workspace); using {} instead",
|
||||
first.display(),
|
||||
chosen.display()
|
||||
);
|
||||
cfg.command = chosen.to_string_lossy().into_owned();
|
||||
}
|
||||
|
||||
/// The release script a `jdtls` command on `PATH` resolves to: itself when it
|
||||
/// already is one, or the script its Scoop shim launches. `None` for a command
|
||||
/// that is neither a release script nor a jdtls Scoop shim.
|
||||
@@ -560,6 +599,57 @@ mod tests {
|
||||
assert_eq!(find_install(home, "macos", "aarch64").unwrap().config, home.join("config_mac_arm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_java_jar_wrapper_first_on_path_is_skipped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = |dir: &Path, text: &str| {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
let name = if cfg!(windows) { "jdtls.cmd" } else { "jdtls" };
|
||||
std::fs::write(dir.join(name), text).unwrap();
|
||||
#[cfg(unix)]
|
||||
std::fs::set_permissions(dir.join(name), std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
dir.join(name)
|
||||
};
|
||||
// opencode's wrapper (#6062), then a release script.
|
||||
let wrapper = exe(
|
||||
&dir.path().join("jdk/bin"),
|
||||
"\"%JAVA_HOME%\\bin\\java\" -jar \"%JDTLS_HOME%\\plugins\\org.eclipse.equinox.launcher_1.7.100.jar\" -data \"%DATA_DIR%\" %*\n",
|
||||
);
|
||||
let release = exe(
|
||||
&dir.path().join("jdtls/bin"),
|
||||
"parser.add_argument('--jvm-arg', action='append')\nlauncher = 'org.eclipse.equinox.launcher_*.jar'\n",
|
||||
);
|
||||
let managed = dir.path().join("tools/jdtls/bin/jdtls");
|
||||
let cfg = |dirs: &[&Path]| -> LanguageServerConfig {
|
||||
let mut cfg: LanguageServerConfig = toml::from_str("name = \"jdtls\"\ncommand = \"jdtls\"").unwrap();
|
||||
let path = std::env::join_paths(dirs.iter().map(|d| d.parent().unwrap())).unwrap();
|
||||
cfg.env.insert("PATH".into(), path.to_string_lossy().into_owned());
|
||||
cfg
|
||||
};
|
||||
|
||||
let mut next = cfg(&[&wrapper, &release]);
|
||||
skip_plain_launcher_wrappers(&mut next, &managed);
|
||||
assert_eq!(Path::new(&next.command), release);
|
||||
|
||||
let mut only = cfg(&[&wrapper]);
|
||||
skip_plain_launcher_wrappers(&mut only, &managed);
|
||||
assert_eq!(Path::new(&only.command), managed, "the IDE's install, offered while missing");
|
||||
|
||||
let mut release_first = cfg(&[&release, &wrapper]);
|
||||
skip_plain_launcher_wrappers(&mut release_first, &managed);
|
||||
assert_eq!(release_first.command, "jdtls");
|
||||
|
||||
// Wrappers that delegate (Homebrew's, a Scoop shim) and named commands are kept.
|
||||
let brew = exe(&dir.path().join("brew/bin"), "#!/bin/bash\nexec \"/opt/jdtls/libexec/bin/jdtls\" \"$@\"\n");
|
||||
let mut delegating = cfg(&[&brew, &release]);
|
||||
skip_plain_launcher_wrappers(&mut delegating, &managed);
|
||||
assert_eq!(delegating.command, "jdtls");
|
||||
let mut named = cfg(&[&wrapper]);
|
||||
named.command = wrapper.to_string_lossy().into_owned();
|
||||
skip_plain_launcher_wrappers(&mut named, &managed);
|
||||
assert_eq!(Path::new(&named.command), wrapper);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn rewrites_the_release_script_to_java() {
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) fn block_history(
|
||||
crate::repo::blob_at(&repo, &rel, "HEAD")?
|
||||
};
|
||||
let Some(head) = head else {
|
||||
return Ok(BlockHistory { head_lines: None, revisions: Vec::new() });
|
||||
return Ok(BlockHistory { head_lines: None, head: None, revisions: Vec::new() });
|
||||
};
|
||||
let head = decode(&head, encoding);
|
||||
let current = match current_text {
|
||||
@@ -32,12 +32,18 @@ pub(crate) fn block_history(
|
||||
None => decode(&std::fs::read(r.abs_path(&rel))?, encoding).into_owned(),
|
||||
};
|
||||
let Some((start, end)) = head_range(&crate::diff::line_hunks(&head, ¤t), lines) else {
|
||||
return Ok(BlockHistory { head_lines: None, revisions: Vec::new() });
|
||||
return Ok(BlockHistory { head_lines: None, head: None, revisions: Vec::new() });
|
||||
};
|
||||
let range = format!("-L{},{}:{rel}", start + 1, end + 1);
|
||||
let args = ["log", "--no-color", "--no-ext-diff", "--no-textconv", FORMAT, &range, "HEAD"];
|
||||
let out = cli::run_cancellable(r.root(), &args, cancel)?;
|
||||
Ok(BlockHistory { head_lines: Some((start, end)), revisions: parse_log(&out.stdout, encoding) })
|
||||
// The newest row's block can't stand in for HEAD's: a merge row has none.
|
||||
let mut block = String::new();
|
||||
for line in head.lines().skip(start as usize).take((end - start) as usize + 1) {
|
||||
push_line(&mut block, line);
|
||||
}
|
||||
let revisions = parse_log(&out.stdout, encoding);
|
||||
Ok(BlockHistory { head_lines: Some((start, end)), head: Some(block), revisions })
|
||||
}
|
||||
|
||||
/// The HEAD lines (0-based, inclusive) of `lines` in the current text, given the
|
||||
|
||||
@@ -139,6 +139,9 @@ pub struct BlameLine {
|
||||
pub struct BlockHistory {
|
||||
/// The selected lines in HEAD (0-based, inclusive); None when none of them is committed.
|
||||
pub head_lines: Option<(u32, u32)>,
|
||||
/// Those lines as HEAD has them, each ending with `\n`; None from servers that predate it.
|
||||
#[serde(default)]
|
||||
pub head: Option<String>,
|
||||
pub revisions: Vec<BlockRevision>,
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,8 @@ fn follows_the_block_through_edits_and_a_rename() {
|
||||
let fx = renamed_history();
|
||||
let h = history(&fx.repo(), &fx.path("b.txt"), None, (1, 2));
|
||||
assert_eq!(h.head_lines, Some((1, 2)));
|
||||
// Without a merge on top, HEAD's block is the newest row's.
|
||||
assert_eq!(h.head.as_deref(), Some(h.revisions[0].after.as_str()));
|
||||
let shown: Vec<_> = h.revisions.iter().map(|r| (r.summary.as_str(), r.path.as_str())).collect();
|
||||
// Edits outside the block and the pure rename are left out.
|
||||
assert_eq!(shown, [("Shout three", "b.txt"), ("Shout two", "a.txt"), ("Add a", "a.txt")]);
|
||||
@@ -86,6 +88,26 @@ fn follows_the_block_through_edits_and_a_rename() {
|
||||
assert!(newest.id.starts_with(&newest.short_id) && newest.time_ms > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newest_row_a_merge_without_a_diff() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("a.txt", "a\nb\nc\nd\n");
|
||||
fx.commit("Add a");
|
||||
fx.git(&["switch", "-q", "-c", "side"]);
|
||||
fx.write("a.txt", "A\nb\nc\nd\n");
|
||||
fx.commit("Side edit");
|
||||
fx.git(&["switch", "-q", "main"]);
|
||||
fx.write("a.txt", "a\nb\nc\nD\n");
|
||||
fx.commit("Main edit");
|
||||
fx.git(&["merge", "-q", "--no-edit", "side"]);
|
||||
let h = history(&fx.repo(), &fx.path("a.txt"), None, (0, 3));
|
||||
let newest = &h.revisions[0];
|
||||
assert!(newest.summary.starts_with("Merge"), "{newest:?}");
|
||||
// Git prints no patch for the merge, so its block says nothing about HEAD.
|
||||
assert_eq!((newest.before.as_str(), newest.after.as_str()), ("", ""));
|
||||
assert_eq!(h.head.as_deref(), Some("A\nb\nc\nD\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_an_edited_selection_to_head_lines() {
|
||||
let fx = renamed_history();
|
||||
@@ -93,7 +115,7 @@ fn maps_an_edited_selection_to_head_lines() {
|
||||
// Two unsaved lines inserted at the top: lines 3..=4 are HEAD's 1..=2.
|
||||
let edited = "new\nnew\none\nTWO\nTHREE\nfour\nFIVE\n";
|
||||
let h = history(&repo, &fx.path("b.txt"), Some(edited), (3, 4));
|
||||
assert_eq!(h.head_lines, Some((1, 2)));
|
||||
assert_eq!((h.head_lines, h.head.as_deref()), (Some((1, 2)), Some("TWO\nTHREE\n")));
|
||||
assert_eq!(h.revisions.len(), 3);
|
||||
// Only new lines selected, or a file Git does not know: nothing committed to show.
|
||||
let h = history(&repo, &fx.path("b.txt"), Some(edited), (0, 1));
|
||||
|
||||
@@ -8,8 +8,7 @@ use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
/// Files above this size open with expensive features (LSP, tree-sitter
|
||||
/// structure, folding) disabled.
|
||||
/// Files above this size open with reduced editor features.
|
||||
pub const LARGE_FILE_THRESHOLD: u64 = 5 * 1024 * 1024;
|
||||
/// Files above this size open read-only.
|
||||
pub const READ_ONLY_THRESHOLD: u64 = 50 * 1024 * 1024;
|
||||
|
||||
@@ -29,8 +29,8 @@ pub struct DocumentInfo {
|
||||
/// (archive entries, JDT sources with an editable attachment encoding,
|
||||
/// Git revisions); false for server-generated content (decompiled code).
|
||||
pub can_reload_encoding: bool,
|
||||
/// Larger than `ide_vfs::LARGE_FILE_THRESHOLD`: language servers, syntax
|
||||
/// structure and folding are disabled; the editor should drop heavy features.
|
||||
/// Marks files above `ide_vfs::LARGE_FILE_THRESHOLD` for reduced editor
|
||||
/// features such as disabling language servers and folding.
|
||||
#[specta(optional)]
|
||||
pub large: bool,
|
||||
/// Effective `.editorconfig` properties, when any section applies.
|
||||
|
||||
@@ -152,7 +152,9 @@ double click and Enter with `event.table_activate()` (API 1.3, absolute 0-based
|
||||
Bodies, fields and events added by later APIs travel as `Other { kind, data }`: an IDE that
|
||||
doesn't know a body says it needs updating, and leaves out a field type it doesn't know.
|
||||
Item right-click menus use `viewItem.context` (see
|
||||
[Commands and actions](/en/plugins/guides/commands#menus)).
|
||||
[Commands and actions](/en/plugins/guides/commands#menus)). A command that menu offers for the selected item,
|
||||
run from its shortcut (or Find Action) while the view has the keyboard focus, gets that
|
||||
item's key as its argument, as from the menu; none when nothing is selected.
|
||||
|
||||
## Custom editors
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ register_plugin!(TodoFinder, views);
|
||||
双击和回车用 `event.table_activate()`(API 1.3,从 0 开始的绝对行号)。
|
||||
|
||||
后续 API 新增的主体、字段和事件以 `Other { kind, data }` 传递:IDE 不认识某种主体时会提示需要更新,
|
||||
不认识的字段类型则直接省略。条目右键菜单使用 `viewItem.context`(见 [命令与动作](/zh/plugins/guides/commands) 中的“菜单”一节)。
|
||||
不认识的字段类型则直接省略。条目右键菜单使用 `viewItem.context`(见 [命令与动作](/zh/plugins/guides/commands) 中的“菜单”一节)。视图有键盘焦点时,用快捷键(或查找动作)运行选中条目的右键菜单里有的命令,命令参数是该条目的 key,与从菜单运行相同;未选中条目时没有参数。
|
||||
|
||||
## 自定义编辑器
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { commands } from "../src/platform/ipc";
|
||||
import { setInvokeRoute } from "../src/platform/tauriCore";
|
||||
import { schemeCss } from "../src/platform/colorScheme";
|
||||
import { lspDoc } from "../src/editor/lsp/lsp";
|
||||
import { semanticExtension } from "../src/editor/lsp/semantic";
|
||||
import { lspTheme } from "../src/editor/lsp/theme";
|
||||
|
||||
setInvokeRoute(() => null);
|
||||
commands.lspSemanticTokens = async () => ({
|
||||
status: "ok",
|
||||
data: {
|
||||
tokenTypes: ["namespace"],
|
||||
tokenModifiers: ["defaultLibrary", "globalScope"],
|
||||
data: [0, 0, 7, 0, 2, 1, 0, 3, 0, 3],
|
||||
},
|
||||
});
|
||||
const mode = new URLSearchParams(location.search).has("light") ? "light" : "dark";
|
||||
const style = document.createElement("style");
|
||||
style.textContent = schemeCss(mode, {
|
||||
[mode]: {
|
||||
packageReference: { foreground: "#446688" },
|
||||
predefined: { foreground: "#cc5500" },
|
||||
},
|
||||
});
|
||||
document.head.append(style);
|
||||
new EditorView({
|
||||
parent: document.body,
|
||||
doc: "example::hello();\nstd::cout << 1;",
|
||||
extensions: [
|
||||
lspTheme,
|
||||
lspDoc.of({ doc: 1, path: "demo.cpp", language: "cpp", uiMode: "C++", readOnly: false }),
|
||||
semanticExtension(),
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="./cppNamespaceStyle.fixture.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
for (const mode of ["dark", "light"]) {
|
||||
test(`C++ standard and user namespaces share the namespace colour (${mode})`, async ({ page }) => {
|
||||
await page.goto(`/e2e/cppNamespaceStyle.html${mode === "light" ? "?light" : ""}`);
|
||||
const namespaces = page.locator(".cm-sem-namespace");
|
||||
await expect(namespaces).toHaveCount(2);
|
||||
for (const namespace of await namespaces.all()) {
|
||||
await expect(namespace).toHaveCSS("color", "rgb(68, 102, 136)");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -78,7 +78,8 @@ test("precise filter values are ordered and filtering composes with result sorti
|
||||
const values = page.getByRole("group", { name: "Values", exact: true });
|
||||
const ascending = [integers[3]!, integers[2]!, integers[1]!, integers[0]!];
|
||||
await expect(values.locator("label")).toHaveText(ascending);
|
||||
await values.getByRole("checkbox", { name: integers[3], exact: true }).uncheck();
|
||||
// Checked values are the rows shown.
|
||||
for (const value of ascending.slice(1)) await values.getByRole("checkbox", { name: value, exact: true }).check();
|
||||
await page.keyboard.press("Escape");
|
||||
await grid
|
||||
.getByRole("columnheader", { name: /^value\b/ })
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("shows why the frames did not load and retries them", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 940, height: 740 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const stateModule = "/src/features/debugger/state.ts";
|
||||
const workbenchModule = "/src/workbench/contributions.ts";
|
||||
const { adoptSession, handleDebugEvent } = await import(/* @vite-ignore */ stateModule);
|
||||
const { toolWindowService } = await import(/* @vite-ignore */ workbenchModule);
|
||||
const handlers = window.__ipc.handlers;
|
||||
let failures = 1;
|
||||
handlers.debug_stack_trace = () => {
|
||||
if (failures-- > 0)
|
||||
throw { kind: "protocol", message: "debug adapter did not answer `stackTrace` in time", detail: null };
|
||||
return [{ id: 7, name: "OrderController.place(Order)", path: null, line: 41, column: 0, presentationHint: null }];
|
||||
};
|
||||
handlers.debug_threads = () => [{ id: 9, name: "http-nio-8080-exec-9" }];
|
||||
handlers.debug_scopes = () => [];
|
||||
adoptSession(98, { name: "Orders", adapter: "java-debug", status: "running" });
|
||||
toolWindowService().show("debug", true);
|
||||
handleDebugEvent(98, {
|
||||
kind: "stopped",
|
||||
threadId: 9,
|
||||
allThreadsStopped: false,
|
||||
reason: "breakpoint",
|
||||
description: null,
|
||||
});
|
||||
});
|
||||
|
||||
const frames = page.getByRole("region", { name: "Debug", exact: true }).getByRole("listbox", { name: "Frames" });
|
||||
const error = frames.getByRole("alert");
|
||||
await expect(error).toContainText("Could not load the frames: debug adapter did not answer `stackTrace` in time");
|
||||
await page.screenshot({ path: test.info().outputPath("frames-error.png") });
|
||||
await error.getByRole("button", { name: "Retry" }).click();
|
||||
await expect(frames.getByText("OrderController.place(Order)", { exact: true })).toBeVisible();
|
||||
await expect(error).toBeHidden();
|
||||
expect(await ipcCalls(page, "debug_stack_trace")).toEqual([
|
||||
{ session: 98, threadId: 9 },
|
||||
{ session: 98, threadId: 9 },
|
||||
]);
|
||||
});
|
||||
@@ -170,7 +170,11 @@ its first `:`, so `pod` for `pod:default/nginx`; the whole key when it has no
|
||||
`:`). Only the menu's `when` sees them, not the command's own `when`; a command
|
||||
whose `when` is false shows greyed out. Other menus refuse `view`, a web view
|
||||
has no item menu, and no menu opens when no declaration matches the item.
|
||||
The menu is new in API 1.2, so a plugin using it declares
|
||||
A command run without an argument (its shortcut, Find Action) while one of the
|
||||
plugin's views has the keyboard focus gets the selected item's key too, when
|
||||
that item's `viewItem.context` menu offers the command: a shortcut acts on the
|
||||
selected item like the menu entry. With nothing selected, the focus elsewhere or
|
||||
the command not in the item's menu, it gets none. The menu is new in API 1.2, so a plugin using it declares
|
||||
`engines.openidea = "^1.2"`. For example:
|
||||
|
||||
```toml
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { dmgName, renderCask, stableVersion } from "./homebrew-cask.ts";
|
||||
|
||||
const ARM = "5fc404ab470bb9ca5168ab5d1769ad5892d657a8992fb26adf192f2c60bd8279";
|
||||
const INTEL = "38b3b06bbbc46503889ab43f16131f87037d3499cac7792e9fc221bcaac0bc05";
|
||||
|
||||
describe("stableVersion", () => {
|
||||
it("takes the version of a stable tag", () => {
|
||||
expect(stableVersion("v0.1.51")).toBe("0.1.51");
|
||||
});
|
||||
|
||||
it("skips prereleases and other refs", () => {
|
||||
expect(stableVersion("v0.2.0-beta.1")).toBeNull();
|
||||
expect(stableVersion("0.1.51")).toBeNull();
|
||||
expect(stableVersion("main")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("dmgName", () => {
|
||||
it("names the release's DMG of each arch", () => {
|
||||
expect(dmgName("0.1.51", "arm")).toBe("OpenIDEA_0.1.51_aarch64.dmg");
|
||||
expect(dmgName("0.1.51", "intel")).toBe("OpenIDEA_0.1.51_x64.dmg");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderCask", () => {
|
||||
it("pins the version and the checksum of each arch", () => {
|
||||
const cask = renderCask("0.1.51", { arm: ARM, intel: INTEL });
|
||||
expect(cask).toContain(`version "0.1.51"`);
|
||||
expect(cask).toContain(`sha256 arm: "${ARM}",\n intel: "${INTEL}"`);
|
||||
expect(cask).toContain(
|
||||
`url "https://github.com/l0ng-ai/openidea/releases/download/v#{version}/OpenIDEA_#{version}_#{arch}.dmg"`,
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves updates to the app and installs the CLI", () => {
|
||||
const cask = renderCask("0.1.51", { arm: ARM, intel: INTEL });
|
||||
expect(cask).toContain("auto_updates true");
|
||||
expect(cask).toContain(`binary "#{appdir}/OpenIDEA.app/Contents/Resources/bin/openidea"`);
|
||||
expect(cask).toContain(`"~/Library/Application Support/ai.l0ng.openidea"`);
|
||||
});
|
||||
|
||||
it("refuses a checksum that isn't SHA-256", () => {
|
||||
expect(() => renderCask("0.1.51", { arm: ARM, intel: "abc" })).toThrow(/intel/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* Writes the Homebrew cask for a published release:
|
||||
* `node scripts/homebrew-cask.ts <tag> <dir> <out>`. `<dir>` holds the release's macOS DMGs
|
||||
* (`gh release download <tag> -p '*.dmg'`); `<out>` is the cask file to write, e.g.
|
||||
* `Casks/openidea.rb` in a checkout of the tap (l0ng-ai/homebrew-tap). The cask lets the app
|
||||
* update itself (`auto_updates true`): the Tauri updater and `brew upgrade` don't fight.
|
||||
*/
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream, existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const GITHUB_REPO = "l0ng-ai/openidea";
|
||||
const IDENTIFIER = "ai.l0ng.openidea";
|
||||
|
||||
/** The DMG of each Homebrew arch, as the release names it. */
|
||||
export const DMG_ARCH = { arm: "aarch64", intel: "x64" } as const;
|
||||
|
||||
export interface Checksums {
|
||||
arm: string;
|
||||
intel: string;
|
||||
}
|
||||
|
||||
/** The version of a stable release tag (`v0.1.51` → `0.1.51`); prereleases have none. */
|
||||
export function stableVersion(tag: string): string | null {
|
||||
const match = /^v(\d+\.\d+\.\d+)$/.exec(tag);
|
||||
return match ? match[1]! : null;
|
||||
}
|
||||
|
||||
export function dmgName(version: string, arch: keyof typeof DMG_ARCH): string {
|
||||
return `OpenIDEA_${version}_${DMG_ARCH[arch]}.dmg`;
|
||||
}
|
||||
|
||||
export function renderCask(version: string, sha256: Checksums): string {
|
||||
for (const [arch, sum] of Object.entries(sha256)) {
|
||||
if (!/^[0-9a-f]{64}$/.test(sum)) throw new Error(`${arch}: ${sum} is not a SHA-256`);
|
||||
}
|
||||
return `cask "openidea" do
|
||||
arch arm: "${DMG_ARCH.arm}", intel: "${DMG_ARCH.intel}"
|
||||
|
||||
version "${version}"
|
||||
sha256 arm: "${sha256.arm}",
|
||||
intel: "${sha256.intel}"
|
||||
|
||||
url "https://github.com/${GITHUB_REPO}/releases/download/v#{version}/OpenIDEA_#{version}_#{arch}.dmg"
|
||||
name "OpenIDEA"
|
||||
desc "IDE inspired by IntelliJ IDEA, rebuilt in Rust"
|
||||
homepage "https://openidea.sh/"
|
||||
|
||||
livecheck do
|
||||
url :url
|
||||
strategy :github_latest
|
||||
end
|
||||
|
||||
auto_updates true
|
||||
depends_on :macos
|
||||
|
||||
app "OpenIDEA.app"
|
||||
binary "#{appdir}/OpenIDEA.app/Contents/Resources/bin/openidea"
|
||||
|
||||
zap trash: [
|
||||
"~/Library/Application Support/${IDENTIFIER}",
|
||||
"~/Library/Caches/${IDENTIFIER}",
|
||||
"~/Library/HTTPStorages/${IDENTIFIER}",
|
||||
"~/Library/Logs/${IDENTIFIER}",
|
||||
"~/Library/Preferences/${IDENTIFIER}.plist",
|
||||
"~/Library/Saved Application State/${IDENTIFIER}.savedState",
|
||||
"~/Library/WebKit/${IDENTIFIER}",
|
||||
]
|
||||
end
|
||||
`;
|
||||
}
|
||||
|
||||
function sha256File(path: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = createHash("sha256");
|
||||
createReadStream(path)
|
||||
.on("data", (chunk) => hash.update(chunk))
|
||||
.on("error", reject)
|
||||
.on("end", () => resolve(hash.digest("hex")));
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const [tag, dir, out] = process.argv.slice(2);
|
||||
if (!tag || !dir || !out) throw new Error("usage: node scripts/homebrew-cask.ts <tag> <dir> <out>");
|
||||
const version = stableVersion(tag);
|
||||
if (!version) throw new Error(`${tag} is not a stable release tag`);
|
||||
const sum = async (arch: keyof typeof DMG_ARCH) => {
|
||||
const path = join(dir, dmgName(version, arch));
|
||||
if (!existsSync(path)) throw new Error(`${path} is missing`);
|
||||
return sha256File(path);
|
||||
};
|
||||
const cask = renderCask(version, { arm: await sum("arm"), intel: await sum("intel") });
|
||||
mkdirSync(dirname(out), { recursive: true });
|
||||
writeFileSync(out, cask);
|
||||
console.log(`wrote ${out} for OpenIDEA ${version}`);
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
||||
main().catch((e) => {
|
||||
console.error(e instanceof Error ? e.message : e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -31,6 +31,7 @@ serde_json.workspace = true
|
||||
base64.workspace = true
|
||||
percent-encoding = "2"
|
||||
tokio.workspace = true
|
||||
reqwest.workspace = true
|
||||
parking_lot.workspace = true
|
||||
blake3.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -463,7 +463,23 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State<
|
||||
}
|
||||
let home = dirs::home_dir();
|
||||
let config = menu_state.config.lock().clone();
|
||||
menu::model(&spec, &menu::recent_items(&state.recent.list(), home.as_deref()), &config)
|
||||
let remote = menu_state.remote_recent.lock().clone();
|
||||
menu::model(&spec, &menu::recent_items(&state.recent.list(), &remote, home.as_deref()), &config)
|
||||
}
|
||||
|
||||
/// The Remote Development projects of the frontend's recent list, for Open Recent.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn menu_set_remote_recent(
|
||||
app: AppHandle,
|
||||
menu_state: State<'_, MenuState>,
|
||||
state: State<'_, AppState>,
|
||||
projects: Vec<menu::RemoteRecent>,
|
||||
) {
|
||||
if menu::store_remote_recent(&menu_state, projects) {
|
||||
menu::install(&app, &menu_state, &state.recent.list());
|
||||
}
|
||||
}
|
||||
|
||||
/// Action ids the focused window cannot run now: their native menu items are
|
||||
@@ -597,7 +613,19 @@ fn source_endpoints(official: Vec<String>, source: UpdateSource) -> Vec<String>
|
||||
}
|
||||
}
|
||||
|
||||
fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
|
||||
/// Bounds connection establishment (TCP and TLS) for the updater. reqwest divides this
|
||||
/// across a host's resolved addresses, so a CDN hostname with four A records gets about
|
||||
/// 3.75s each — enough for a slow link, while still leaving the 60s check budget intact.
|
||||
const UPDATER_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
|
||||
|
||||
fn configure_updater_client(
|
||||
builder: reqwest::ClientBuilder,
|
||||
proxy: &ide_core::proxy_settings::ProxySettings,
|
||||
) -> reqwest::ClientBuilder {
|
||||
ide_http::client::with_proxy(builder, proxy).connect_timeout(UPDATER_CONNECT_TIMEOUT)
|
||||
}
|
||||
|
||||
pub(crate) fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
|
||||
use tauri_plugin_updater::UpdaterExt;
|
||||
if !updates_configured(app) {
|
||||
return Ok(None);
|
||||
@@ -620,7 +648,7 @@ fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plug
|
||||
builder = builder.target(target);
|
||||
}
|
||||
builder
|
||||
.configure_client(move |b| ide_http::client::with_proxy(b, &proxy))
|
||||
.configure_client(move |b| configure_updater_client(b, &proxy))
|
||||
.endpoints(endpoints)
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))?
|
||||
.build()
|
||||
@@ -695,24 +723,23 @@ pub enum UpdateProgress {
|
||||
/// Limits download events to one per whole percent (or per 256 KiB without a length).
|
||||
#[derive(Default)]
|
||||
struct ProgressThrottle {
|
||||
downloaded: u64,
|
||||
last_step: Option<u64>,
|
||||
}
|
||||
|
||||
impl ProgressThrottle {
|
||||
const UNKNOWN_STEP: u64 = 256 * 1024;
|
||||
|
||||
fn chunk(&mut self, len: usize, total: Option<u64>) -> Option<UpdateProgress> {
|
||||
self.downloaded += len as u64;
|
||||
/// Converts the downloader's absolute byte count into a throttled event.
|
||||
fn report(&mut self, downloaded: u64, total: Option<u64>) -> Option<UpdateProgress> {
|
||||
let step = match total {
|
||||
Some(t) if t > 0 => self.downloaded.min(t) * 100 / t,
|
||||
_ => self.downloaded / Self::UNKNOWN_STEP,
|
||||
Some(t) if t > 0 => downloaded.min(t) * 100 / t,
|
||||
_ => downloaded / Self::UNKNOWN_STEP,
|
||||
};
|
||||
if self.last_step == Some(step) {
|
||||
return None;
|
||||
}
|
||||
self.last_step = Some(step);
|
||||
Some(UpdateProgress::Downloading { downloaded: self.downloaded as f64, total: total.map(|t| t as f64) })
|
||||
Some(UpdateProgress::Downloading { downloaded: downloaded as f64, total: total.map(|t| t as f64) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -750,28 +777,22 @@ pub async fn app_install_update(
|
||||
InstallingGuard::acquire().ok_or_else(|| IdeError::unavailable("an update is already being installed"))?;
|
||||
let token = state.host.begin_request(request);
|
||||
let result = async {
|
||||
let updater = updater(&app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
|
||||
let update = tokio::select! {
|
||||
r = updater.check() => r.map_err(|e| IdeError::unavailable(e.to_string()))?,
|
||||
_ = token.cancelled() => return Err(IdeError::cancelled()),
|
||||
}
|
||||
.ok_or_else(|| IdeError::not_found("no update available"))?;
|
||||
let mut throttle = ProgressThrottle::default();
|
||||
let progress = on_progress.clone();
|
||||
let download = update.download(
|
||||
move |len, total| {
|
||||
if let Some(p) = throttle.chunk(len, total) {
|
||||
let downloaded = tokio::select! {
|
||||
result = crate::updates::download_update(&app, source, &token, move |done, total| {
|
||||
if let Some(p) = throttle.report(done, total) {
|
||||
let _ = progress.send(p);
|
||||
}
|
||||
},
|
||||
|| {},
|
||||
);
|
||||
let bytes = tokio::select! {
|
||||
r = download => r.map_err(|e| IdeError::unavailable(e.to_string()))?,
|
||||
}) => result?,
|
||||
_ = token.cancelled() => return Err(IdeError::cancelled()),
|
||||
};
|
||||
let crate::updates::DownloadedUpdate { update, bytes, path } = downloaded;
|
||||
if token.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let _ = on_progress.send(UpdateProgress::Installing);
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let installed = tauri::async_runtime::spawn_blocking(move || {
|
||||
#[cfg(windows)]
|
||||
if update.target.ends_with("-portable") {
|
||||
let exe = tauri::utils::platform::current_exe()?;
|
||||
@@ -780,7 +801,11 @@ pub async fn app_install_update(
|
||||
update.install(bytes).map_err(|e| IdeError::internal(e.to_string()))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
if installed.is_ok() {
|
||||
let _ = tokio::fs::remove_file(path).await;
|
||||
}
|
||||
installed
|
||||
}
|
||||
.await;
|
||||
state.host.end_request(request);
|
||||
@@ -793,7 +818,9 @@ pub async fn app_install_update(
|
||||
/// can show the UI's language and fall back to English. An install records the
|
||||
/// notes it saw, so this is only for an update installed outside the app.
|
||||
/// `Ok(None)` when the manifest covers another version or carries no notes.
|
||||
#[desktop_command(trust = trusted)]
|
||||
/// Reads only the public manifest, like the update check: the page usually opens
|
||||
/// in a window without a project.
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn app_release_notes(
|
||||
@@ -909,22 +936,33 @@ mod tests {
|
||||
#[test]
|
||||
fn throttle_reports_each_whole_percent_once() {
|
||||
let mut t = ProgressThrottle::default();
|
||||
assert_eq!(downloading(t.chunk(1, Some(1000))), Some((1.0, Some(1000.0))));
|
||||
assert_eq!(downloading(t.chunk(5, Some(1000))), None);
|
||||
assert_eq!(downloading(t.chunk(4, Some(1000))), Some((10.0, Some(1000.0))));
|
||||
let reported = (0..99).filter(|_| t.chunk(10, Some(1000)).is_some()).count();
|
||||
assert_eq!(reported, 99);
|
||||
assert_eq!(t.downloaded, 1000);
|
||||
assert_eq!(downloading(t.report(1, Some(1000))), Some((1.0, Some(1000.0))));
|
||||
assert_eq!(downloading(t.report(9, Some(1000))), None);
|
||||
assert_eq!(downloading(t.report(10, Some(1000))), Some((10.0, Some(1000.0))));
|
||||
let reported = (11..=100).filter(|percent| t.report(percent * 10, Some(1000)).is_some()).count();
|
||||
assert_eq!(reported, 90);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn throttle_without_length_reports_per_step() {
|
||||
let mut t = ProgressThrottle::default();
|
||||
assert!(t.chunk(10, None).is_some());
|
||||
assert!(t.chunk(1024, None).is_none());
|
||||
assert_eq!(downloading(t.chunk(256 * 1024, None)), Some(((256 * 1024 + 1034) as f64, None)));
|
||||
assert!(t.report(10, None).is_some());
|
||||
assert!(t.report(1024, None).is_none());
|
||||
assert_eq!(downloading(t.report(256 * 1024 + 1034, None)), Some(((256 * 1024 + 1034) as f64, None)));
|
||||
// A zero length is treated as unknown, not divided by.
|
||||
assert!(ProgressThrottle::default().chunk(1, Some(0)).is_some());
|
||||
assert!(ProgressThrottle::default().report(1, Some(0)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn throttle_uses_absolute_bytes_after_a_full_download_restart() {
|
||||
let mut t = ProgressThrottle::default();
|
||||
let total = 100 * 1024 * 1024;
|
||||
assert_eq!(downloading(t.report(40 * 1024 * 1024, None)), Some(((40 * 1024 * 1024) as f64, None)));
|
||||
assert_eq!(downloading(t.report(1024, Some(total))), Some((1024.0, Some(total as f64))));
|
||||
assert_eq!(
|
||||
downloading(t.report(50 * 1024 * 1024, Some(total))),
|
||||
Some(((50 * 1024 * 1024) as f64, Some(total as f64)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -936,6 +974,18 @@ mod tests {
|
||||
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn updater_client_bounds_connection_setup() {
|
||||
let proxy = ide_core::proxy_settings::ProxySettings::default();
|
||||
let builder = configure_updater_client(reqwest::ClientBuilder::new(), &proxy);
|
||||
// reqwest has no getter for this; its ClientBuilder Debug prints non-default settings.
|
||||
let debug = format!("{builder:?}");
|
||||
assert!(
|
||||
debug.contains(&format!("connect_timeout: {:?}", UPDATER_CONNECT_TIMEOUT)),
|
||||
"the updater must not wait forever on an unreachable CDN address: {debug}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_one_install_at_a_time() {
|
||||
let first = InstallingGuard::acquire().expect("first install starts");
|
||||
@@ -962,6 +1012,7 @@ ide_command::desktop_domain!(
|
||||
menu_model,
|
||||
menu_refresh,
|
||||
menu_set_disabled,
|
||||
menu_set_remote_recent,
|
||||
window_begin_prompt,
|
||||
window_close_context,
|
||||
window_complete_launch,
|
||||
|
||||
@@ -1117,6 +1117,31 @@ pub struct MenuState {
|
||||
/// Visible menu last installed. Accelerators of actions that are not on the menu
|
||||
/// are not part of this, so they must not redraw the macOS menu bar.
|
||||
rendered: Mutex<Option<Vec<RenderedMenu>>>,
|
||||
/// The Remote Development projects of the frontend's recent list.
|
||||
pub remote_recent: Mutex<Vec<RemoteRecent>>,
|
||||
}
|
||||
|
||||
/// A recent Remote Development project (SSH, WSL, Dev Container), kept by the frontend: Open
|
||||
/// Recent lists it among the local projects, as Manage Projects does.
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteRecent {
|
||||
/// `ssh://host/path`, `wsl://Ubuntu/path`…: what `file.openRecentProject` gets back.
|
||||
pub location: String,
|
||||
pub name: String,
|
||||
/// Where it lives, as shown after the name (`me@host:/srv/app`).
|
||||
pub detail: String,
|
||||
pub opened_at_ms: f64,
|
||||
}
|
||||
|
||||
/// Stores the remote recent list; `false` when it is unchanged.
|
||||
pub fn store_remote_recent(state: &MenuState, next: Vec<RemoteRecent>) -> bool {
|
||||
let mut current = state.remote_recent.lock();
|
||||
if *current == next {
|
||||
return false;
|
||||
}
|
||||
*current = next;
|
||||
true
|
||||
}
|
||||
|
||||
/// Stores `next` when it differs from the config last used to build the menu.
|
||||
@@ -1193,18 +1218,28 @@ pub struct RecentItem {
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
pub fn recent_items(recent: &[ide_workspace::RecentProject], home: Option<&Path>) -> Vec<RecentItem> {
|
||||
recent
|
||||
.iter()
|
||||
.take(MAX_RECENT)
|
||||
.map(|p| {
|
||||
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
|
||||
Some(rest) => format!("~/{}", rest.display()),
|
||||
None => p.path.display().to_string(),
|
||||
};
|
||||
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) }
|
||||
})
|
||||
.collect()
|
||||
/// The local and remote recent projects, most recently opened first.
|
||||
pub fn recent_items(
|
||||
recent: &[ide_workspace::RecentProject],
|
||||
remote: &[RemoteRecent],
|
||||
home: Option<&Path>,
|
||||
) -> Vec<RecentItem> {
|
||||
let local = recent.iter().map(|p| {
|
||||
let shown = match home.and_then(|h| p.path.strip_prefix(h).ok()) {
|
||||
Some(rest) => format!("~/{}", rest.display()),
|
||||
None => p.path.display().to_string(),
|
||||
};
|
||||
let item =
|
||||
RecentItem { path: p.path.to_string_lossy().into_owned(), label: format!("{} — {shown}", p.name) };
|
||||
(p.opened_at_ms, item)
|
||||
});
|
||||
let remote = remote.iter().map(|r| {
|
||||
(r.opened_at_ms, RecentItem { path: r.location.clone(), label: format!("{} — {}", r.name, r.detail) })
|
||||
});
|
||||
let mut items: Vec<(f64, RecentItem)> = local.chain(remote).collect();
|
||||
// Stable: the local list's own order holds among equal times.
|
||||
items.sort_by(|a, b| b.0.total_cmp(&a.0));
|
||||
items.into_iter().take(MAX_RECENT).map(|(_, item)| item).collect()
|
||||
}
|
||||
|
||||
/// One top-level menu, as it will actually be drawn.
|
||||
@@ -1746,7 +1781,7 @@ pub fn install<R: Runtime>(app: &AppHandle<R>, menu_state: &MenuState, recent: &
|
||||
return;
|
||||
}
|
||||
let home = dirs::home_dir();
|
||||
let items = recent_items(recent, home.as_deref());
|
||||
let items = recent_items(recent, &menu_state.remote_recent.lock(), home.as_deref());
|
||||
let config = menu_state.config.lock().clone();
|
||||
let disabled = menu_state.disabled.lock().clone();
|
||||
let rendered = render_bar(&prepared_spec(app, Os::current()), &config, &items);
|
||||
@@ -2233,11 +2268,39 @@ mod tests {
|
||||
branch: None,
|
||||
missing: false,
|
||||
}];
|
||||
let items = recent_items(&recent, Some(Path::new("/home/me")));
|
||||
let items = recent_items(&recent, &[], Some(Path::new("/home/me")));
|
||||
assert_eq!(items[0].label, "openidea — ~/code/openidea");
|
||||
assert_eq!(items[0].path, "/home/me/code/openidea");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_projects_join_the_recent_list_by_when_they_were_opened() {
|
||||
let local = |path: &str, at: f64| ide_workspace::RecentProject {
|
||||
path: path.into(),
|
||||
name: path.rsplit('/').next().unwrap().into(),
|
||||
opened_at_ms: at,
|
||||
branch: None,
|
||||
missing: false,
|
||||
};
|
||||
let recent = vec![local("/home/me/new", 30.0), local("/home/me/old", 10.0)];
|
||||
let remote = [RemoteRecent {
|
||||
location: "wsl://Ubuntu/home/me/api".into(),
|
||||
name: "api".into(),
|
||||
detail: "Ubuntu:/home/me/api".into(),
|
||||
opened_at_ms: 20.0,
|
||||
}];
|
||||
let items = recent_items(&recent, &remote, Some(Path::new("/home/me")));
|
||||
let paths: Vec<&str> = items.iter().map(|i| i.path.as_str()).collect();
|
||||
assert_eq!(paths, ["/home/me/new", "wsl://Ubuntu/home/me/api", "/home/me/old"]);
|
||||
assert_eq!(items[1].label, "api — Ubuntu:/home/me/api");
|
||||
|
||||
let many: Vec<_> = (0..20).map(|i| local(&format!("/p/{i}"), f64::from(i))).collect();
|
||||
let items = recent_items(&many, &remote, None);
|
||||
assert_eq!(items.len(), MAX_RECENT);
|
||||
assert_eq!([items[0].path.as_str(), items[1].path.as_str()], ["wsl://Ubuntu/home/me/api", "/p/19"]);
|
||||
assert_eq!(items[MAX_RECENT - 1].path, format!("/p/{}", 20 - MAX_RECENT + 1), "the remote one takes a slot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_drops_native_roles_and_fills_recent() {
|
||||
let spec = vec![sub(
|
||||
|
||||
@@ -164,7 +164,7 @@ async fn install(
|
||||
|
||||
/// The arguments of `docker` that start the server in the container: in the project folder, told
|
||||
/// that the folder is trusted and that the CLI already ran the lifecycle commands.
|
||||
fn server_args(up: &Up, bin: &str) -> Vec<String> {
|
||||
fn server_args(up: &Up, bin: &str, replace: bool) -> Vec<String> {
|
||||
let mut args: Vec<String> = ["exec", "-i", "-u", &up.user, "-w", &up.folder].map(str::to_owned).into();
|
||||
for var in [
|
||||
format!("{}={}", ide_host::trust::TRUSTED_ROOT_ENV, up.folder),
|
||||
@@ -173,6 +173,9 @@ fn server_args(up: &Up, bin: &str) -> Vec<String> {
|
||||
args.extend(["-e".to_owned(), var]);
|
||||
}
|
||||
args.extend([up.container.clone(), bin.to_owned(), "--attach".to_owned(), up.folder.clone()]);
|
||||
if replace {
|
||||
args.push("--replace".to_owned());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
@@ -183,6 +186,7 @@ pub(crate) async fn connect(
|
||||
state: &crate::state::AppState,
|
||||
folder: &str,
|
||||
config: &str,
|
||||
replace: bool,
|
||||
handler: Arc<dyn Handler>,
|
||||
tail: &Tail,
|
||||
progress: &Arc<Progress>,
|
||||
@@ -215,16 +219,23 @@ pub(crate) async fn connect(
|
||||
let up = up(&cli, &docker, &local, config, tail).await?;
|
||||
let bin = ensure_server(state, &docker, &up, progress).await?;
|
||||
progress(RemoteStage::Starting, None);
|
||||
let peer = spawn(&docker, &up, &bin, handler, tail)?;
|
||||
let peer = spawn(&docker, &up, &bin, replace, handler, tail)?;
|
||||
let folder = up.folder.clone();
|
||||
Ok((peer, folder, Exec::new(docker, up, bin)))
|
||||
}
|
||||
|
||||
fn spawn(docker: &Path, up: &Up, bin: &str, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
|
||||
fn spawn(docker: &Path, up: &Up, bin: &str, replace: bool, handler: Arc<dyn Handler>, tail: &Tail) -> IdeResult<Peer> {
|
||||
let tail = tail.clone();
|
||||
let program = docker.to_string_lossy();
|
||||
Peer::spawn(&program, &server_args(up, bin), &std::env::temp_dir(), &[], handler, Box::new(move |l| tail.push(l)))
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}")))
|
||||
Peer::spawn(
|
||||
&program,
|
||||
&server_args(up, bin, replace),
|
||||
&std::env::temp_dir(),
|
||||
&[],
|
||||
handler,
|
||||
Box::new(move |l| tail.push(l)),
|
||||
)
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start docker: {e}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -237,7 +248,7 @@ mod tests {
|
||||
#[test]
|
||||
fn the_server_starts_in_the_folder_trusted_and_without_the_lifecycle() {
|
||||
let up = Up { container: ID.into(), user: "vscode".into(), folder: "/workspaces/my app".into() };
|
||||
let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server");
|
||||
let args = server_args(&up, "/home/vscode/.openidea/server/1/ab/openidea-server", false);
|
||||
assert_eq!(
|
||||
args,
|
||||
[
|
||||
@@ -374,7 +385,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
|
||||
let dir = version_dir(&found.home, "0.0.0-test");
|
||||
let bin = install(&docker, &up, &dir, "b1", &server, &progress).await.unwrap();
|
||||
assert_eq!(probe(&docker, &up, "0.0.0-test").await.unwrap().installed, std::slice::from_ref(&bin));
|
||||
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &tail).unwrap();
|
||||
let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &tail).unwrap();
|
||||
let info: ide_host::rpc::ServerInfo = peer
|
||||
.request("initialize", serde_json::json!({ "version": ide_host::rpc::PROTOCOL_VERSION }), None)
|
||||
.await
|
||||
@@ -446,7 +457,7 @@ echo '{{"outcome":"success","containerId":"{ID}","remoteUser":"vscode","remoteWo
|
||||
let live = || docker_sh(&docker, &up.container, &format!("kill -0 {pid} 2>/dev/null && printf live"));
|
||||
assert_eq!(live(), "live", "the terminal must outlive the window in a dev container");
|
||||
|
||||
let peer = spawn(&docker, &up, &bin, Arc::new(Silent), &Tail::default()).unwrap();
|
||||
let peer = spawn(&docker, &up, &bin, false, Arc::new(Silent), &Tail::default()).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(30), async {
|
||||
let project: Value = peer.request("invoke", invoke("project_current", json!({})), None).await.unwrap();
|
||||
assert_eq!(project["root"], up.folder);
|
||||
|
||||
@@ -673,6 +673,7 @@ pub async fn remote_connect(
|
||||
state: State<'_, AppState>,
|
||||
target: RemoteTarget,
|
||||
mut path: String,
|
||||
replace: bool,
|
||||
on_progress: Channel<RemoteProgress>,
|
||||
) -> IdeResult<RemoteProject> {
|
||||
let progress: Arc<Progress> = Arc::new(move |stage, fraction| {
|
||||
@@ -704,9 +705,10 @@ pub async fn remote_connect(
|
||||
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
|
||||
let stream = session
|
||||
.exec_stream(&format!(
|
||||
"{} --attach {} 2>&1",
|
||||
"{} --attach {}{} 2>&1",
|
||||
ide_ssh::shell::tilde_quote(&bin),
|
||||
ide_ssh::shell::quote(attach_arg),
|
||||
if replace { " --replace" } else { "" },
|
||||
))
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start openidea-server: {e}")))?;
|
||||
@@ -723,12 +725,12 @@ pub async fn remote_connect(
|
||||
let bin = crate::remote_wsl::ensure_server(&state, distro, progress.clone()).await?;
|
||||
progress(RemoteStage::Starting, None);
|
||||
let attach_arg = if path.trim().is_empty() { "~" } else { path.trim() };
|
||||
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, handler, &tail)?;
|
||||
let peer = crate::remote_wsl::spawn(distro, &bin, attach_arg, replace, handler, &tail)?;
|
||||
(peer, None, distro.clone(), format!("WSL: {distro}"))
|
||||
}
|
||||
RemoteTarget::DevContainer { folder, config } => {
|
||||
let (peer, root, run) =
|
||||
crate::remote_container::connect(&state, folder, config, handler, &tail, &progress).await?;
|
||||
crate::remote_container::connect(&state, folder, config, replace, handler, &tail, &progress).await?;
|
||||
path = root;
|
||||
exec = Some(Arc::new(run));
|
||||
let name = std::path::Path::new(folder)
|
||||
@@ -740,6 +742,11 @@ pub async fn remote_connect(
|
||||
// A server that dies on start-up says why on stderr (`wsl.exe` prints its own errors too).
|
||||
let with_output = |e: IdeError| match tail.text() {
|
||||
t if t.is_empty() => e,
|
||||
// Another build's backend holds the project: the window offers to stop it (#6119).
|
||||
t if t.contains(ide_host::rpc::OTHER_BUILD_BUSY) => IdeError {
|
||||
data: Some(ide_core::error::ErrorData::RemoteBackendBusy),
|
||||
..IdeError::unavailable(ide_host::rpc::OTHER_BUILD_BUSY)
|
||||
},
|
||||
t => IdeError::unavailable(format!("{}: {t}", e.message)),
|
||||
};
|
||||
let info: ServerInfo = peer
|
||||
|
||||
@@ -187,10 +187,11 @@ pub(crate) fn spawn(
|
||||
distro: &str,
|
||||
bin: &str,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
handler: Arc<dyn Handler>,
|
||||
tail: &Tail,
|
||||
) -> IdeResult<Peer> {
|
||||
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, handler, tail)
|
||||
spawn_with(ide_core::wsl::EXE, distro, bin, project_path, replace, handler, tail)
|
||||
}
|
||||
|
||||
/// [`spawn`] through `launcher` instead of `wsl.exe` (tests put a stand-in there).
|
||||
@@ -199,10 +200,15 @@ fn spawn_with(
|
||||
distro: &str,
|
||||
bin: &str,
|
||||
project_path: &str,
|
||||
replace: bool,
|
||||
handler: Arc<dyn Handler>,
|
||||
tail: &Tail,
|
||||
) -> IdeResult<Peer> {
|
||||
let args: Vec<String> = ["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
|
||||
let mut args: Vec<String> =
|
||||
["-d", checked(distro)?, "--exec", bin, "--attach", project_path].map(str::to_owned).into();
|
||||
if replace {
|
||||
args.push("--replace".to_owned());
|
||||
}
|
||||
let tail = tail.clone();
|
||||
Peer::spawn(launcher, &args, &std::env::temp_dir(), &[], handler, Box::new(move |line| tail.push(line)))
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot start wsl.exe: {e}")))
|
||||
@@ -305,7 +311,8 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
|
||||
std::fs::write(&launcher, script).unwrap();
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let tail = Tail::default();
|
||||
let peer = spawn_with(launcher.to_str().unwrap(), distro, bin, project, Arc::new(Silent), &tail).unwrap();
|
||||
let peer =
|
||||
spawn_with(launcher.to_str().unwrap(), distro, bin, project, false, Arc::new(Silent), &tail).unwrap();
|
||||
let reply: String = peer.request("ping", serde_json::Value::Null, None).await.unwrap_or_else(|e| {
|
||||
panic!("{e:?}; launcher said: {}", tail.text());
|
||||
});
|
||||
@@ -314,7 +321,8 @@ printf 'Content-Length: %s\r\n\r\n%s' "${{#body}}" "$body"
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bad_distro_name_never_starts_the_launcher() {
|
||||
let err = spawn_with("does-not-exist", "-d", "/x", "~", Arc::new(Silent), &Tail::default()).err().unwrap();
|
||||
let err =
|
||||
spawn_with("does-not-exist", "-d", "/x", "~", false, Arc::new(Silent), &Tail::default()).err().unwrap();
|
||||
assert!(err.message.contains("not a valid"), "{}", err.message);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,28 @@
|
||||
//! Desktop updater coordination shared by all webviews.
|
||||
|
||||
use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updates_configured};
|
||||
mod download;
|
||||
|
||||
use crate::commands::window::{UpdateSource, check_update, update_endpoint_env, updater, updates_configured};
|
||||
use crate::state::AppState;
|
||||
use ide_core::updates::{UpdateCheck, UpdatePolicy};
|
||||
use ide_core::{IdeEvent, IdeResult};
|
||||
use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashSet;
|
||||
use std::future::Future;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
use tauri::{AppHandle, Manager};
|
||||
use tauri_plugin_updater::Update;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
/// One verified download, kept on disk until its installer has finished.
|
||||
pub(crate) struct DownloadedUpdate {
|
||||
pub update: Update,
|
||||
pub bytes: Vec<u8>,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
/// Tauri patches the installer copies; the raw exe shipped in the portable zip keeps no bundle type.
|
||||
pub fn portable_target(os: &str, arch: &str, bundle: Option<tauri::utils::config::BundleType>) -> Option<String> {
|
||||
(os == "windows" && bundle.is_none()).then(|| format!("windows-{arch}-portable"))
|
||||
@@ -129,6 +141,105 @@ pub async fn check(app: &AppHandle, source: Option<UpdateSource>) -> IdeResult<U
|
||||
result
|
||||
}
|
||||
|
||||
/// Downloads an update to a signature-keyed `.part` file, resuming from bytes
|
||||
/// kept by a previous attempt or process, and verifies the completed package.
|
||||
pub(crate) async fn download_update(
|
||||
app: &AppHandle,
|
||||
source: UpdateSource,
|
||||
token: &CancellationToken,
|
||||
mut progress: impl FnMut(u64, Option<u64>),
|
||||
) -> IdeResult<DownloadedUpdate> {
|
||||
let updater = updater(app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
|
||||
let update =
|
||||
cancellable(token, async { updater.check().await.map_err(|error| IdeError::unavailable(error.to_string())) })
|
||||
.await?
|
||||
.ok_or_else(|| IdeError::not_found("no update available"))?;
|
||||
let directory = app
|
||||
.path()
|
||||
.app_cache_dir()
|
||||
.map_err(|error| IdeError::internal(format!("update cache directory: {error}")))?
|
||||
.join("updates");
|
||||
tokio::fs::create_dir_all(&directory).await?;
|
||||
let key = cache_key(&update.version, &update.target, &update.signature);
|
||||
let path = directory.join(format!("{key}.part"));
|
||||
if let Err(error) = cleanup_stale_cache_files(&path).await {
|
||||
tracing::warn!(%error, "cannot clean obsolete update downloads");
|
||||
}
|
||||
let client = ide_http::client::shared()?;
|
||||
for attempt in 0..3 {
|
||||
let outcome =
|
||||
cancellable(token, download::fetch(&client, update.download_url.as_str(), &path, &mut progress)).await?;
|
||||
match cancellable(token, verify_file(update.clone(), path.clone())).await {
|
||||
Ok(bytes) => return Ok(DownloadedUpdate { update, bytes, path }),
|
||||
Err(error) if outcome.resumed && attempt < 2 => {
|
||||
tracing::warn!(%error, "discarding a mixed update checkpoint");
|
||||
tokio::fs::remove_file(&path).await?;
|
||||
}
|
||||
Err(_) if outcome.total.is_none() && attempt < 2 => {
|
||||
tracing::warn!("an update response of unknown length failed verification; resuming");
|
||||
}
|
||||
Err(error) => {
|
||||
if outcome.resumed || outcome.total.is_some() {
|
||||
tokio::fs::remove_file(&path).await?;
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(IdeError::internal("update download did not produce a verified package"))
|
||||
}
|
||||
|
||||
/// Runs one fallible stage until it finishes or the command is cancelled. The
|
||||
/// check and signature-verification stages previously escaped cancellation
|
||||
/// while the download itself was cancellable.
|
||||
async fn cancellable<T>(token: &CancellationToken, future: impl Future<Output = IdeResult<T>>) -> IdeResult<T> {
|
||||
tokio::select! {
|
||||
result = future => result,
|
||||
_ = token.cancelled() => Err(IdeError::cancelled()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable cache identity shared by GitHub and CNB for the same signed artifact.
|
||||
fn cache_key(version: &str, target: &str, signature: &str) -> String {
|
||||
let hash = blake3::hash(format!("{version}\0{target}\0{signature}").as_bytes()).to_hex();
|
||||
format!("{version}-{target}-{hash}")
|
||||
}
|
||||
|
||||
/// Reads and verifies a completed checkpoint on the blocking pool.
|
||||
async fn verify_file(update: Update, path: PathBuf) -> IdeResult<Vec<u8>> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let bytes = std::fs::read(path)?;
|
||||
update.verify(&bytes).map_err(|error| IdeError::internal(error.to_string()))?;
|
||||
Ok(bytes)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| IdeError::internal(error.to_string()))?
|
||||
}
|
||||
|
||||
/// Keeps the current signed artifact's checkpoint and backup while removing
|
||||
/// obsolete releases and abandoned fallback temporaries.
|
||||
async fn cleanup_stale_cache_files(path: &Path) -> IdeResult<()> {
|
||||
let Some(directory) = path.parent() else { return Ok(()) };
|
||||
let keep_part = path.file_name();
|
||||
let mut keep_backup = path.file_name().unwrap_or_default().to_os_string();
|
||||
keep_backup.push(".backup");
|
||||
let mut entries = tokio::fs::read_dir(directory).await?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
if !entry.file_type().await?.is_file() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
if Some(name.as_os_str()) == keep_part || name == keep_backup {
|
||||
continue;
|
||||
}
|
||||
let text = name.to_string_lossy();
|
||||
if text.ends_with(".part") || text.ends_with(".ready") || text.ends_with(".full") || text.ends_with(".backup") {
|
||||
let _ = tokio::fs::remove_file(entry.path()).await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit_status(state: &AppState) {
|
||||
let status = state.updates.state.lock().policy.status.clone();
|
||||
state.sink.emit(IdeEvent::UpdateStatusChanged { status });
|
||||
@@ -195,4 +306,51 @@ mod tests {
|
||||
assert_eq!(ready_owner(Some("main"), &live, &HashSet::new()), None);
|
||||
assert_eq!(ready_owner(Some("closed-window"), &[], &ready), None);
|
||||
}
|
||||
|
||||
/// The cache identity stays stable across mirrors only while the signed bytes do.
|
||||
#[test]
|
||||
fn cache_identity_follows_the_signature_not_the_download_url() {
|
||||
let first = cache_key("0.1.50", "darwin-aarch64", "signature-a");
|
||||
assert_eq!(first, cache_key("0.1.50", "darwin-aarch64", "signature-a"));
|
||||
assert_ne!(first, cache_key("0.1.50", "darwin-aarch64", "signature-b"));
|
||||
assert_ne!(first, cache_key("0.1.51", "darwin-aarch64", "signature-a"));
|
||||
}
|
||||
|
||||
/// Starting a download keeps its signed artifact's checkpoint and restores
|
||||
/// its backup, while obsolete releases and fallback temporaries go away.
|
||||
#[tokio::test]
|
||||
async fn stale_update_cache_files_are_removed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let current = dir.path().join("current.part");
|
||||
for name in
|
||||
["current.part", "current.part.backup", "current.part.full", "old.part", "old.ready", "old.part.backup"]
|
||||
{
|
||||
tokio::fs::write(dir.path().join(name), b"x").await.unwrap();
|
||||
}
|
||||
tokio::fs::write(dir.path().join("unrelated.json"), b"{}").await.unwrap();
|
||||
|
||||
cleanup_stale_cache_files(¤t).await.unwrap();
|
||||
|
||||
assert!(current.exists());
|
||||
assert!(dir.path().join("current.part.backup").exists());
|
||||
assert!(dir.path().join("unrelated.json").exists());
|
||||
for name in ["current.part.full", "old.part", "old.ready", "old.part.backup"] {
|
||||
assert!(!dir.path().join(name).exists(), "{name} was kept");
|
||||
}
|
||||
}
|
||||
|
||||
/// Signature verification is wrapped in the same cancellation boundary as
|
||||
/// network work, so a late Cancel cannot fall through into installation.
|
||||
#[tokio::test]
|
||||
async fn cancelled_stage_stops_before_installation() {
|
||||
let token = CancellationToken::new();
|
||||
token.cancel();
|
||||
let error = cancellable(&token, async {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Resumable update downloads for the existing install-and-restart flow.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use reqwest::header::{ACCEPT, ACCEPT_ENCODING, CONTENT_LENGTH, CONTENT_RANGE, RANGE};
|
||||
use reqwest::{Client, StatusCode};
|
||||
use std::path::{Path, PathBuf};
|
||||
use tokio::fs::OpenOptions;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
/// How one request completed: whether it appended to the partial file, and
|
||||
/// whether the response advertised a total size.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Outcome {
|
||||
pub resumed: bool,
|
||||
pub total: Option<u64>,
|
||||
}
|
||||
|
||||
/// Appends `url` to `path`, resuming from its current length when the server
|
||||
/// honours Range. An unsupported Range falls back to replacing the partial file
|
||||
/// because installing bytes from different representations would be unsafe.
|
||||
pub(crate) async fn fetch(
|
||||
client: &Client,
|
||||
url: &str,
|
||||
path: &Path,
|
||||
mut progress: impl FnMut(u64, Option<u64>),
|
||||
) -> IdeResult<Outcome> {
|
||||
let backup = beside(path, "backup");
|
||||
if !path.exists() && backup.exists() {
|
||||
tokio::fs::rename(&backup, path).await?;
|
||||
} else if path.exists() {
|
||||
let _ = tokio::fs::remove_file(backup).await;
|
||||
}
|
||||
let mut offset = match tokio::fs::metadata(path).await {
|
||||
Ok(metadata) => metadata.len(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0,
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
loop {
|
||||
progress(offset, None);
|
||||
let mut request = client
|
||||
.get(url)
|
||||
.header(ACCEPT, "application/octet-stream")
|
||||
// A byte offset is only meaningful for the representation the server
|
||||
// advertised. Automatic content decoding would break that contract.
|
||||
.header(ACCEPT_ENCODING, "identity");
|
||||
if offset > 0 {
|
||||
request = request.header(RANGE, format!("bytes={offset}-"));
|
||||
}
|
||||
let response = request.send().await.map_err(|error| IdeError::unavailable(error.to_string()))?;
|
||||
let status = response.status();
|
||||
|
||||
if status == StatusCode::RANGE_NOT_SATISFIABLE && offset > 0 {
|
||||
let total =
|
||||
response.headers().get(CONTENT_RANGE).and_then(|value| value.to_str().ok()).and_then(unsatisfied_total);
|
||||
if total == Some(offset) {
|
||||
return Ok(Outcome { resumed: true, total });
|
||||
}
|
||||
tokio::fs::remove_file(path).await?;
|
||||
offset = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
if status == StatusCode::PARTIAL_CONTENT {
|
||||
let (start, total) = response
|
||||
.headers()
|
||||
.get(CONTENT_RANGE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(partial_range)
|
||||
.ok_or_else(|| IdeError::unavailable("update server sent an invalid Content-Range header"))?;
|
||||
if start != offset {
|
||||
// This is not the byte range we asked for. Keep the partial file:
|
||||
// another mirror may resume it correctly, and this response is not
|
||||
// safe to append.
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"update server returned byte {start} while {offset} was requested"
|
||||
)));
|
||||
}
|
||||
let mut file = OpenOptions::new().append(true).open(path).await?;
|
||||
let downloaded = append_body(&mut file, response, offset, total, &mut progress).await?;
|
||||
ensure_complete(downloaded, total)?;
|
||||
return Ok(Outcome { resumed: offset > 0, total });
|
||||
}
|
||||
|
||||
if status == StatusCode::OK {
|
||||
let total = response
|
||||
.headers()
|
||||
.get(CONTENT_LENGTH)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse().ok());
|
||||
if offset > 0 {
|
||||
replace_with_full(response, path, total, &mut progress).await?;
|
||||
} else {
|
||||
let mut file = OpenOptions::new().create(true).write(true).truncate(true).open(path).await?;
|
||||
let downloaded = append_body(&mut file, response, 0, total, &mut progress).await?;
|
||||
ensure_complete(downloaded, total)?;
|
||||
}
|
||||
return Ok(Outcome { resumed: false, total });
|
||||
}
|
||||
|
||||
return Err(IdeError::unavailable(format!("update download failed with HTTP {status}")));
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads a full response beside the existing partial file. The old bytes
|
||||
/// stay resumable if the replacement connection fails before completion.
|
||||
async fn replace_with_full(
|
||||
response: reqwest::Response,
|
||||
path: &Path,
|
||||
total: Option<u64>,
|
||||
progress: &mut impl FnMut(u64, Option<u64>),
|
||||
) -> IdeResult<()> {
|
||||
let temporary = beside(path, "full");
|
||||
let backup = beside(path, "backup");
|
||||
let result = async {
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.write(true)
|
||||
.truncate(true)
|
||||
.open(&temporary)
|
||||
.await
|
||||
.map_err(IdeError::from)?;
|
||||
let downloaded = append_body(&mut file, response, 0, total, progress).await?;
|
||||
ensure_complete(downloaded, total)?;
|
||||
let _ = tokio::fs::remove_file(&backup).await;
|
||||
let had_old = path.exists();
|
||||
if had_old {
|
||||
tokio::fs::rename(path, &backup).await.map_err(IdeError::from)?;
|
||||
}
|
||||
if let Err(error) = tokio::fs::rename(&temporary, path).await {
|
||||
if had_old {
|
||||
let _ = tokio::fs::rename(&backup, path).await;
|
||||
}
|
||||
return Err(IdeError::from(error));
|
||||
}
|
||||
if had_old {
|
||||
let _ = tokio::fs::remove_file(&backup).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
let _ = tokio::fs::remove_file(&temporary).await;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Returns a sibling of `path` whose name has `suffix` appended after its full
|
||||
/// extension sequence, e.g. `update.part` and `full` → `update.part.full`.
|
||||
fn beside(path: &Path, suffix: &str) -> PathBuf {
|
||||
let mut name = path.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(format!(".{suffix}"));
|
||||
path.with_file_name(name)
|
||||
}
|
||||
|
||||
/// Copies one response body into the persistent file and reports absolute
|
||||
/// progress, including bytes recovered from an earlier process.
|
||||
async fn append_body(
|
||||
file: &mut tokio::fs::File,
|
||||
mut response: reqwest::Response,
|
||||
offset: u64,
|
||||
total: Option<u64>,
|
||||
progress: &mut impl FnMut(u64, Option<u64>),
|
||||
) -> IdeResult<u64> {
|
||||
let mut downloaded = offset;
|
||||
while let Some(chunk) = response.chunk().await.map_err(|error| IdeError::unavailable(error.to_string()))? {
|
||||
file.write_all(&chunk).await?;
|
||||
downloaded += chunk.len() as u64;
|
||||
progress(downloaded, total);
|
||||
}
|
||||
file.flush().await?;
|
||||
file.sync_all().await?;
|
||||
Ok(downloaded)
|
||||
}
|
||||
|
||||
/// Rejects a body that ended before the advertised length instead of promoting
|
||||
/// a truncated installer to the ready state.
|
||||
fn ensure_complete(downloaded: u64, total: Option<u64>) -> IdeResult<()> {
|
||||
match total {
|
||||
Some(total) if downloaded != total => {
|
||||
Err(IdeError::unavailable(format!("update download ended at {downloaded} of {total} bytes")))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `bytes start-end/total`, returning the start and known total.
|
||||
fn partial_range(value: &str) -> Option<(u64, Option<u64>)> {
|
||||
let value = value.strip_prefix("bytes ")?;
|
||||
let (range, total) = value.split_once('/')?;
|
||||
let (start, _) = range.split_once('-')?;
|
||||
let start = start.parse().ok()?;
|
||||
let total = (total != "*").then(|| total.parse().ok()).flatten();
|
||||
Some((start, total))
|
||||
}
|
||||
|
||||
/// Parses the total from a `bytes */total` unsatisfied-range response.
|
||||
fn unsatisfied_total(value: &str) -> Option<u64> {
|
||||
value.strip_prefix("bytes */")?.parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::thread;
|
||||
|
||||
/// Starts a one-request HTTP server and returns its URL plus the request line.
|
||||
fn serve(response: Vec<u8>) -> (String, thread::JoinHandle<String>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let handle = thread::spawn(move || {
|
||||
let (mut socket, _) = listener.accept().unwrap();
|
||||
let mut request = Vec::new();
|
||||
let mut byte = [0];
|
||||
while !request.ends_with(b"\r\n\r\n") {
|
||||
socket.read_exact(&mut byte).unwrap();
|
||||
request.push(byte[0]);
|
||||
}
|
||||
socket.write_all(&response).unwrap();
|
||||
String::from_utf8(request).unwrap()
|
||||
});
|
||||
(format!("http://{address}/update"), handle)
|
||||
}
|
||||
|
||||
/// Builds a complete HTTP response with a fixed body.
|
||||
fn http(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
|
||||
let mut response = format!("HTTP/1.1 {status}\r\nConnection: close\r\n");
|
||||
for (name, value) in headers {
|
||||
response.push_str(&format!("{name}: {value}\r\n"));
|
||||
}
|
||||
response.push_str("\r\n");
|
||||
response.into_bytes().into_iter().chain(body.iter().copied()).collect()
|
||||
}
|
||||
|
||||
/// Drops a body early, then resumes from the bytes already on disk.
|
||||
#[tokio::test]
|
||||
async fn a_broken_download_resumes_with_range() {
|
||||
let client = ide_http::client::shared().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("update.part");
|
||||
let (url, first) = serve(http("200 OK", &[("Content-Length", "10")], b"abcd"));
|
||||
assert!(fetch(&client, &url, &path, |_, _| {}).await.is_err());
|
||||
first.join().unwrap();
|
||||
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"abcd");
|
||||
|
||||
let (url, second) = serve(http(
|
||||
"206 Partial Content",
|
||||
&[("Content-Range", "bytes 4-9/10"), ("Content-Length", "6")],
|
||||
b"efghij",
|
||||
));
|
||||
let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap();
|
||||
let request = second.join().unwrap().to_ascii_lowercase();
|
||||
assert!(request.contains("range: bytes=4-"), "{request}");
|
||||
assert_eq!(outcome, Outcome { resumed: true, total: Some(10) });
|
||||
assert_eq!(tokio::fs::read(path).await.unwrap(), b"abcdefghij");
|
||||
}
|
||||
|
||||
/// Replaces a stale partial file when a proxy or mirror ignores Range.
|
||||
#[tokio::test]
|
||||
async fn a_full_response_after_a_partial_replaces_the_file() {
|
||||
let client = ide_http::client::shared().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("update.part");
|
||||
tokio::fs::write(&path, b"stale").await.unwrap();
|
||||
let (url, request) = serve(http("200 OK", &[("Content-Length", "7")], b"fresh!!"));
|
||||
let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap();
|
||||
assert!(request.join().unwrap().to_ascii_lowercase().contains("range: bytes=5-"));
|
||||
assert_eq!(outcome, Outcome { resumed: false, total: Some(7) });
|
||||
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"fresh!!");
|
||||
assert!(!path.with_file_name("update.part.full").exists());
|
||||
}
|
||||
|
||||
/// Keeps the older checkpoint when a proxy ignores Range and its full
|
||||
/// replacement download breaks before completion.
|
||||
#[tokio::test]
|
||||
async fn a_broken_full_fallback_preserves_the_previous_partial() {
|
||||
let client = ide_http::client::shared().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("update.part");
|
||||
tokio::fs::write(&path, b"stale").await.unwrap();
|
||||
let (url, _) = serve(http("200 OK", &[("Content-Length", "10")], b"fresh"));
|
||||
assert!(fetch(&client, &url, &path, |_, _| {}).await.is_err());
|
||||
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"stale");
|
||||
assert!(!path.with_file_name("update.part.full").exists());
|
||||
}
|
||||
|
||||
/// Accepts `bytes */length` as the only completion signal for an already
|
||||
/// complete partial file after a process restart.
|
||||
#[tokio::test]
|
||||
async fn an_already_complete_partial_file_is_returned_on_416() {
|
||||
let client = ide_http::client::shared().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("update.part");
|
||||
tokio::fs::write(&path, b"done").await.unwrap();
|
||||
let (url, _) = serve(http("416 Range Not Satisfiable", &[("Content-Range", "bytes */4")], b""));
|
||||
assert_eq!(fetch(&client, &url, &path, |_, _| {}).await.unwrap(), Outcome { resumed: true, total: Some(4) });
|
||||
}
|
||||
|
||||
/// A close-delimited response has no length to prove a clean EOF; the caller
|
||||
/// uses this signal to resume instead of discarding a failed checkpoint.
|
||||
#[tokio::test]
|
||||
async fn a_close_delimited_response_reports_an_unknown_total() {
|
||||
let client = ide_http::client::shared().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("update.part");
|
||||
let (url, _) = serve(http("200 OK", &[], b"body"));
|
||||
assert_eq!(fetch(&client, &url, &path, |_, _| {}).await.unwrap(), Outcome { resumed: false, total: None });
|
||||
assert_eq!(tokio::fs::read(path).await.unwrap(), b"body");
|
||||
}
|
||||
|
||||
/// A crash during the full-response swap leaves the old checkpoint in the
|
||||
/// backup name; the next fetch restores it before calculating Range.
|
||||
#[tokio::test]
|
||||
async fn a_backup_checkpoint_is_restored_before_resuming() {
|
||||
let client = ide_http::client::shared().unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("update.part");
|
||||
tokio::fs::write(beside(&path, "backup"), b"old").await.unwrap();
|
||||
let (url, request) = serve(http("416 Range Not Satisfiable", &[("Content-Range", "bytes */3")], b""));
|
||||
let outcome = fetch(&client, &url, &path, |_, _| {}).await.unwrap();
|
||||
assert!(request.join().unwrap().to_ascii_lowercase().contains("range: bytes=3-"));
|
||||
assert_eq!(outcome, Outcome { resumed: true, total: Some(3) });
|
||||
assert_eq!(tokio::fs::read(&path).await.unwrap(), b"old");
|
||||
assert!(!beside(&path, "backup").exists());
|
||||
}
|
||||
|
||||
/// Rejects malformed range metadata instead of appending to an unknown slice.
|
||||
#[test]
|
||||
fn content_range_parser_only_accepts_byte_ranges() {
|
||||
assert_eq!(partial_range("bytes 4-9/10"), Some((4, Some(10))));
|
||||
assert_eq!(partial_range("bytes 0-0/*"), Some((0, None)));
|
||||
assert_eq!(partial_range("items 4-9/10"), None);
|
||||
assert_eq!(unsatisfied_total("bytes */10"), Some(10));
|
||||
assert_eq!(unsatisfied_total("bytes 0-1/10"), None);
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ app_install_update always desktop bin
|
||||
app_log_location always desktop bindings sync
|
||||
app_metrics always desktop bindings async
|
||||
app_quit always desktop bindings sync
|
||||
app_release_notes trusted desktop bindings async
|
||||
app_release_notes always desktop bindings async
|
||||
app_restart always desktop bindings sync
|
||||
app_update_announcement always desktop bindings sync
|
||||
app_update_status always desktop bindings sync
|
||||
@@ -188,6 +188,7 @@ debug_jvm_thread_dump trusted project_host bin
|
||||
debug_listen_for_jvm trusted project_host bindings async
|
||||
debug_pause trusted project_host bindings async
|
||||
debug_redefine_classes trusted project_host bindings async
|
||||
debug_replace_breakpoints trusted project_host bindings async
|
||||
debug_resolve_variable trusted project_host bindings async
|
||||
debug_restart_frame trusted project_host bindings async
|
||||
debug_resume trusted project_host bindings async
|
||||
@@ -428,6 +429,7 @@ menu_configure always desktop bin
|
||||
menu_model always desktop bindings sync
|
||||
menu_refresh always desktop bindings sync
|
||||
menu_set_disabled always desktop bindings sync
|
||||
menu_set_remote_recent always desktop bindings sync
|
||||
nav_index_definitions always project_host bindings async
|
||||
nav_inheritance always project_host bindings async
|
||||
nav_python_stubs always project_host bindings async
|
||||
|
||||
+30
-6
@@ -227,6 +227,8 @@ export const commands = {
|
||||
* can show the UI's language and fall back to English. An install records the
|
||||
* notes it saw, so this is only for an update installed outside the app.
|
||||
* `Ok(None)` when the manifest covers another version or carries no notes.
|
||||
* Reads only the public manifest, like the update check: the page usually opens
|
||||
* in a window without a project.
|
||||
*/
|
||||
appReleaseNotes: (version: string, source: UpdateSource) => typedError<{ [key in string]: string } | null, IdeError>(__TAURI_INVOKE("app_release_notes", { version, source })),
|
||||
/** Quits through every window's unsaved-changes check, then starts again. */
|
||||
@@ -478,6 +480,8 @@ export const commands = {
|
||||
debugPause: (session: DebugSessionId, threadId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_pause", { session, threadId })),
|
||||
/** HotSwap (Reload Changed Classes) in a java-debug session. */
|
||||
debugRedefineClasses: (session: DebugSessionId) => typedError<HotSwapResult, IdeError>(__TAURI_INVOKE("debug_redefine_classes", { session })),
|
||||
/** Replaces all of this window's line breakpoints with `files`. */
|
||||
debugReplaceBreakpoints: (files: { [key in string]: Breakpoint[] }) => typedError<null, IdeError>(__TAURI_INVOKE("debug_replace_breakpoints", { files })),
|
||||
debugResolveVariable: (session: DebugSessionId, variable: Variable_Deserialize) => typedError<Variable_Serialize, IdeError>(__TAURI_INVOKE("debug_resolve_variable", { session, variable })),
|
||||
/** Reset Frame (Drop Frame). */
|
||||
debugRestartFrame: (session: DebugSessionId, frameId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_restart_frame", { session, frameId })),
|
||||
@@ -488,6 +492,7 @@ export const commands = {
|
||||
debugSendInput: (session: DebugSessionId, text: string) => typedError<null, IdeError>(__TAURI_INVOKE("debug_send_input", { session, text })),
|
||||
/** This window's live sessions, including adapter-started child sessions. */
|
||||
debugSessions: () => typedError<SessionInfo[], IdeError>(__TAURI_INVOKE("debug_sessions")),
|
||||
/** This window's breakpoints of `path`. */
|
||||
debugSetBreakpoints: (path: string, breakpoints: Breakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_breakpoints", { path, breakpoints })),
|
||||
/** Field watchpoints; states aligned with `breakpoints`. */
|
||||
debugSetDataBreakpoints: (breakpoints: DataBreakpoint[]) => typedError<BreakpointState[], IdeError>(__TAURI_INVOKE("debug_set_data_breakpoints", { breakpoints })),
|
||||
@@ -589,8 +594,8 @@ export const commands = {
|
||||
/**
|
||||
* Structure view: LSP document symbols when available (with tree-sitter
|
||||
* visibility and type-alias kinds), tree-sitter otherwise.
|
||||
* Tree-sitter answers come from the per-document tree cache (incremental
|
||||
* re-parse); large documents get no syntax structure.
|
||||
* Normal files reuse the per-document tree cache. Large Markdown files use
|
||||
* the syntax parser's size limit for heading outlines.
|
||||
*/
|
||||
docOutline: (doc: DocId) => typedError<OutlineItem[], IdeError>(__TAURI_INVOKE("doc_outline", { doc })),
|
||||
/** Python class facts for the inheritance inspections: tree-sitter, no language server. */
|
||||
@@ -1157,6 +1162,8 @@ export const commands = {
|
||||
* disabled in place (no rebuild).
|
||||
*/
|
||||
menuSetDisabled: (ids: string[]) => __TAURI_INVOKE<void>("menu_set_disabled", { ids }),
|
||||
/** The Remote Development projects of the frontend's recent list, for Open Recent. */
|
||||
menuSetRemoteRecent: (projects: RemoteRecent[]) => __TAURI_INVOKE<void>("menu_set_remote_recent", { projects }),
|
||||
/**
|
||||
* Index definitions named `name` within the roots `from` may navigate into (its own root
|
||||
* plus its configured dependencies).
|
||||
@@ -1512,7 +1519,7 @@ export const commands = {
|
||||
* dev container, whose project folder is the container's own) in this window (installs /
|
||||
* starts the server as needed).
|
||||
*/
|
||||
remoteConnect: (target: RemoteTarget, path: string, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { target, path, onProgress })),
|
||||
remoteConnect: (target: RemoteTarget, path: string, replace: boolean, onProgress: Channel<RemoteProgress>) => typedError<RemoteProject_Serialize, IdeError>(__TAURI_INVOKE("remote_connect", { target, path, replace, onProgress })),
|
||||
/** The remote session of this window (a settings window: its parent's), if any. */
|
||||
remoteCurrent: () => __TAURI_INVOKE<{
|
||||
target: RemoteTarget,
|
||||
@@ -3780,6 +3787,8 @@ export type BlameLine_Serialize = {
|
||||
export type BlockHistory = {
|
||||
/** The selected lines in HEAD (0-based, inclusive); None when none of them is committed. */
|
||||
headLines: [number, number] | null,
|
||||
/** Those lines as HEAD has them, each ending with `\n`; None from servers that predate it. */
|
||||
head?: string | null,
|
||||
revisions: BlockRevision[],
|
||||
};
|
||||
|
||||
@@ -6423,8 +6432,8 @@ export type DocumentInfo = {
|
||||
*/
|
||||
canReloadEncoding: boolean,
|
||||
/**
|
||||
* Larger than `ide_vfs::LARGE_FILE_THRESHOLD`: language servers, syntax
|
||||
* structure and folding are disabled; the editor should drop heavy features.
|
||||
* Marks files above `ide_vfs::LARGE_FILE_THRESHOLD` for reduced editor
|
||||
* features such as disabling language servers and folding.
|
||||
*/
|
||||
large?: boolean,
|
||||
/** Effective `.editorconfig` properties, when any section applies. */
|
||||
@@ -6848,7 +6857,9 @@ report?: PushReport | null } |
|
||||
* jdtls could not set a module up as a Java project: the errors on its build files and
|
||||
* the builds enclosing it (`path: message`, the path relative to the project), nearest first.
|
||||
*/
|
||||
{ type: "javaBuildProblems"; problems: string[] };
|
||||
{ type: "javaBuildProblems"; problems: string[] } |
|
||||
/** A remote backend of another OpenIDEA build still serves the project and refused to retire. */
|
||||
{ type: "remoteBackendBusy" };
|
||||
|
||||
export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "invalidInput" |
|
||||
/** The requested state is stale; the UI must use the current snapshot. */
|
||||
@@ -12157,6 +12168,19 @@ export type RemoteProject_Serialize = {
|
||||
project: ProjectInfo_Serialize,
|
||||
};
|
||||
|
||||
/**
|
||||
* A recent Remote Development project (SSH, WSL, Dev Container), kept by the frontend: Open
|
||||
* Recent lists it among the local projects, as Manage Projects does.
|
||||
*/
|
||||
export type RemoteRecent = {
|
||||
/** `ssh://host/path`, `wsl://Ubuntu/path`…: what `file.openRecentProject` gets back. */
|
||||
location: string,
|
||||
name: string,
|
||||
/** Where it lives, as shown after the name (`me@host:/srv/app`). */
|
||||
detail: string,
|
||||
openedAtMs: number | null,
|
||||
};
|
||||
|
||||
export type RemoteSession = RemoteSession_Serialize | RemoteSession_Deserialize;
|
||||
|
||||
export type RemoteSession_Deserialize = {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Text } from "@codemirror/state";
|
||||
import { semanticRanges } from "../index";
|
||||
|
||||
const doc = Text.of(["std"]);
|
||||
const token = (type: string, modifiers: string[], language = "cpp") =>
|
||||
semanticRanges(
|
||||
doc,
|
||||
{ tokenTypes: [type], tokenModifiers: modifiers, data: [0, 0, 3, 0, (1 << modifiers.length) - 1] },
|
||||
false,
|
||||
language,
|
||||
)[0]?.className.split(" ");
|
||||
|
||||
describe("C++ namespace semantic tokens", () => {
|
||||
it.each(["cpp", "CPP"])("keeps standard-library namespaces in the namespace colour (%s)", (language) => {
|
||||
expect(token("namespace", ["defaultLibrary", "globalScope"], language)).toEqual(["cm-sem-namespace"]);
|
||||
expect(token("namespace", ["defaultLibrary"], language)).toEqual(token("namespace", [], language));
|
||||
});
|
||||
|
||||
it("preserves namespace declaration and deprecation styles", () => {
|
||||
expect(token("namespace", ["defaultLibrary", "declaration", "deprecated"])).toEqual([
|
||||
"cm-sem-namespace",
|
||||
"cm-sem-declaration",
|
||||
"cm-sem-deprecated",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["class", "function", "variable"])("preserves builtin colouring for %s tokens", (type) => {
|
||||
expect(token(type, ["defaultLibrary"])).toContain("cm-sem-builtin");
|
||||
});
|
||||
|
||||
it("leaves other languages' namespace colouring unchanged", () => {
|
||||
expect(token("namespace", ["defaultLibrary"], "rust")).toEqual(["cm-sem-namespace", "cm-sem-builtin"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { registerLanguageSemantics } from "../languages";
|
||||
|
||||
registerLanguageSemantics("cpp", {
|
||||
tokenClasses({ type, classes }) {
|
||||
// clangd marks std and other library namespaces as defaultLibrary; keep their namespace colour.
|
||||
if (type !== "namespace") return;
|
||||
const builtin = classes.indexOf("cm-sem-builtin");
|
||||
if (builtin >= 0) classes.splice(builtin, 1);
|
||||
},
|
||||
});
|
||||
@@ -33,6 +33,7 @@ import "./php";
|
||||
import "./go";
|
||||
import "./java";
|
||||
import "./javascript";
|
||||
import "./cpp";
|
||||
|
||||
const semanticBackoff = featureBackoff();
|
||||
|
||||
|
||||
@@ -36,7 +36,8 @@ const appRestart = vi.fn(async () => null);
|
||||
const cancelRequest = vi.fn(async () => null);
|
||||
const appBuildInfo = vi.fn(async () => ({ version: "0.1.21" }));
|
||||
const settingsSet = vi.fn(async () => ({ status: "ok", data: { general: {}, appearance: {} } }));
|
||||
const recordInstalledUpdate = vi.fn();
|
||||
const undoRecord = vi.fn();
|
||||
const recordInstalledUpdate = vi.fn((_version: string, _notes: string | null) => undoRecord);
|
||||
|
||||
vi.mock("@/platform/releaseNotes", () => ({ recordInstalledUpdate }));
|
||||
|
||||
@@ -171,12 +172,24 @@ describe("Install and Restart", () => {
|
||||
expect(appInstallUpdate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("records the notes before the install starts: the Windows installer ends the app inside it", async () => {
|
||||
void installUpdate("0.1.22", "github", "## Fixed\n- a crash");
|
||||
expect(appInstallUpdate).toHaveBeenCalledTimes(1);
|
||||
expect(recordInstalledUpdate).toHaveBeenCalledWith("0.1.22", "## Fixed\n- a crash");
|
||||
expect(recordInstalledUpdate.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
appInstallUpdate.mock.invocationCallOrder[0]!,
|
||||
);
|
||||
install.resolve(ok(null));
|
||||
await tick();
|
||||
expect(undoRecord).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports a failure with Retry, and a cancellation", async () => {
|
||||
const failed = installUpdate("0.1.22");
|
||||
install.resolve({ status: "error", error: { kind: "unavailable", message: "connection reset" } });
|
||||
await failed;
|
||||
expect(appRestart).not.toHaveBeenCalled();
|
||||
expect(recordInstalledUpdate).not.toHaveBeenCalled();
|
||||
expect(undoRecord).toHaveBeenCalledTimes(1);
|
||||
expect(task(INSTALL_TASK_ID)?.done).toBe(true);
|
||||
expect(notes.at(-1)).toMatchObject({
|
||||
level: "error",
|
||||
@@ -194,6 +207,7 @@ describe("Install and Restart", () => {
|
||||
await cancelled;
|
||||
expect(notes.at(-1)).toMatchObject({ level: "info", title: "Update cancelled", key: UPDATE_KEY });
|
||||
expect(appRestart).not.toHaveBeenCalled();
|
||||
expect(undoRecord).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -12,6 +12,7 @@ const windowGroupJoin = vi.fn();
|
||||
const windowTakeLaunch = vi.fn();
|
||||
const windowCompleteLaunch = vi.fn();
|
||||
const wslResolve = vi.fn();
|
||||
const windowOpenRemote = vi.fn();
|
||||
const cancelClose = vi.fn();
|
||||
const notify = vi.fn();
|
||||
const listen = vi.fn();
|
||||
@@ -51,6 +52,7 @@ vi.mock("@/platform/ipc", async (orig) => {
|
||||
windowTakeLaunch: () => windowTakeLaunch(),
|
||||
windowCompleteLaunch: () => windowCompleteLaunch(),
|
||||
wslResolve: (p: string) => wslResolve(p),
|
||||
windowOpenRemote: (...a: unknown[]) => windowOpenRemote(...a),
|
||||
lightEditOpen: (p: string) => lightEditOpen(p),
|
||||
fsReadDir: (p: string) => fsReadDir(p),
|
||||
},
|
||||
@@ -266,6 +268,14 @@ describe("a recent project opened with a modifier key", () => {
|
||||
await action.run({ arg: "/p/b" } as never);
|
||||
expect(windowOpenProject).toHaveBeenLastCalledWith("/p/b", false, []);
|
||||
});
|
||||
|
||||
it("opens a Remote Development project from Open Recent on its host (#6124)", async () => {
|
||||
windowOpenRemote.mockResolvedValue(ok({ kind: "focused" }));
|
||||
const action = windowActions().find((a) => a.id === "file.openRecentProject")!;
|
||||
await action.run({ arg: "wsl://Ubuntu/home/me/api" } as never);
|
||||
expect(windowOpenRemote).toHaveBeenCalledWith({ kind: "wsl", distro: "Ubuntu" }, "/home/me/api", false);
|
||||
expect(windowOpenProject).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("loose files (LightEdit)", () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
useKeymap,
|
||||
} from "@/platform/keymap";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { syncRemoteRecentMenu } from "@/platform/remote";
|
||||
import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions";
|
||||
import { useDistractionFree } from "@/workbench/distractionFree";
|
||||
import { javaFileNameOf, menuLabelParams } from "@/workbench/menuLabels";
|
||||
@@ -258,6 +259,7 @@ export function installMenuBridge(): () => void {
|
||||
.catch(() => {});
|
||||
|
||||
push();
|
||||
syncRemoteRecentMenu();
|
||||
const onFocus = () => {
|
||||
push();
|
||||
pushEnablement(true);
|
||||
|
||||
@@ -229,9 +229,13 @@ async function runInstall(version: string, source: UpdateSource, notes: string |
|
||||
upsertTask({ id: INSTALL_TASK_ID, title, message: null, fraction: null, done: false, cancel });
|
||||
// Replaces the notification whose action is now spent.
|
||||
balloon([{ label: t("app.update.cancel"), run: cancel }]);
|
||||
// The restarted app reads this to show the What's New page of the version it now runs.
|
||||
// Recorded first: the Windows installer ends the app before the install returns.
|
||||
const undoRecord = recordInstalledUpdate(version, notes);
|
||||
try {
|
||||
await call(commands.appInstallUpdate(source, request, channel));
|
||||
} catch (e) {
|
||||
undoRecord();
|
||||
if (isCancelled(e)) {
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
@@ -257,8 +261,6 @@ async function runInstall(version: string, source: UpdateSource, notes: string |
|
||||
} finally {
|
||||
upsertTask({ id: INSTALL_TASK_ID, title, message: null, fraction: 1, done: true });
|
||||
}
|
||||
// The restarted app reads this to show the What's New page of the version it now runs.
|
||||
recordInstalledUpdate(version, notes);
|
||||
const restart = () => void commands.appRestart();
|
||||
// Stays if a window cancels the restart (unsaved changes): the update applies on the next start.
|
||||
notifications().notify({
|
||||
|
||||
@@ -22,10 +22,10 @@ import {
|
||||
} from "@/platform/project";
|
||||
import { confirmProjectTrust } from "@/platform/projectTrust";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { connectRemote, isRemoteWindow } from "@/platform/remote";
|
||||
import { connectRemote, isRemoteWindow, parseRemoteLocation } from "@/platform/remote";
|
||||
import { holdSplash } from "@/platform/splash";
|
||||
import { editorService, maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import { chooseProjectWindow, type ProjectWindowOverride } from "@/workbench/projectWindow";
|
||||
import { chooseProjectWindow, openRemoteProject, type ProjectWindowOverride } from "@/workbench/projectWindow";
|
||||
import { openTabColorPicker } from "@/workbench/TabColorPicker";
|
||||
import { cycleWindowTab, useWindowGroup } from "@/platform/windowGroups";
|
||||
import { editorSwitching } from "@/editor/api";
|
||||
@@ -606,7 +606,15 @@ export function windowActions(): Action[] {
|
||||
hidden: true,
|
||||
run: async (c) => {
|
||||
const recent = recentProjectArg(c.arg);
|
||||
if (recent) await openProjectWithPolicy(recent.path, [], recent.window);
|
||||
if (!recent) return;
|
||||
// Open Recent lists Remote Development projects by their location (`ssh://host/path`).
|
||||
const remote = parseRemoteLocation(recent.path);
|
||||
if (!remote) return openProjectWithPolicy(recent.path, [], recent.window);
|
||||
try {
|
||||
await openRemoteProject(remote.target, remote.path, undefined, recent.window);
|
||||
} catch (e) {
|
||||
openFailed(remote.path, e);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -82,6 +82,25 @@ describe("execution point state", () => {
|
||||
expect(useExecutionPoint.getState()).toMatchObject({ path, line: 9 });
|
||||
});
|
||||
|
||||
it("keeps a failed stack trace's reason for the frames list, and a retry loads the frames", async () => {
|
||||
const error = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
ipc.debugStackTrace.mockResolvedValueOnce({
|
||||
status: "error",
|
||||
error: { kind: "timedOut", message: "stackTrace timed out after 30s" },
|
||||
} as never);
|
||||
stopped();
|
||||
await settle();
|
||||
expect(useDebug.getState().sessions[1]).toMatchObject({
|
||||
frames: [],
|
||||
framesError: "stackTrace timed out after 30s",
|
||||
});
|
||||
expect(error).toHaveBeenCalled();
|
||||
await selectThread(1, 5);
|
||||
expect(useDebug.getState().sessions[1]).toMatchObject({ framesError: null, selectedFrame: 100 });
|
||||
expect(useExecutionPoint.getState()).toMatchObject({ path, line: 6840 });
|
||||
error.mockRestore();
|
||||
});
|
||||
|
||||
it("counts stops per session", async () => {
|
||||
adoptSession(2, { adapter: "java-debug" });
|
||||
expect(useDebug.getState().sessions[1]!.stops).toBe(0);
|
||||
|
||||
@@ -266,6 +266,37 @@ describe("HotSwap", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("points a refused structural change to Enhanced class redefinition when the configuration has it off", async () => {
|
||||
const refused = "Failed to redefine classes: add method not implemented";
|
||||
const hint = "turn on Enhanced class redefinition in the run configuration";
|
||||
expect(hotSwapMessage(0, [refused], false, true).body).toContain(hint);
|
||||
expect(hotSwapMessage(0, [refused], false, false).body).toBe(refused);
|
||||
expect(hotSwapMessage(0, ["boom"], false, true).body).toBe("boom");
|
||||
|
||||
const withConfig = (kind: string, params: Record<string, string>) => ({
|
||||
...session(1, true),
|
||||
runConfig: { id: kind, kind, params } as unknown as NonNullable<DebugSession["runConfig"]>,
|
||||
});
|
||||
ipc.debugRedefineClasses.mockImplementation(() => ipc.ok({ changedClasses: [], errorMessage: refused }));
|
||||
for (const [s, shown] of [
|
||||
[withConfig("application", {}), true],
|
||||
[withConfig("spring-boot", {}), true],
|
||||
[withConfig("application", { enhancedClassRedefinition: "true" }), false],
|
||||
[withConfig("tomcat", {}), false],
|
||||
[session(1, true), false],
|
||||
] as const) {
|
||||
useDebug.setState({ sessions: { 1: s } });
|
||||
// oxlint-disable-next-line no-await-in-loop -- one reload per session shape; each assertion reads its notification
|
||||
await reloadChangedClasses(false);
|
||||
expect(notes.at(-1)).toMatchObject({ level: "error", title: "Hot Swap failed" });
|
||||
expect(String(notes.at(-1)!.body).includes(hint)).toBe(shown);
|
||||
}
|
||||
|
||||
useDebug.setState({ sessions: { 1: withConfig("application", {}) } });
|
||||
onHotCodeReplace(1 as DebugSessionId, { kind: "hotCodeReplace", changeType: "ERROR", message: refused });
|
||||
expect(notes.at(-1)).toMatchObject({ title: "Hot Swap", body: expect.stringContaining(hint) });
|
||||
});
|
||||
|
||||
function pausedFrames(names: string[], restartFrame = true): DebugSession {
|
||||
return {
|
||||
...session(1, true),
|
||||
|
||||
@@ -157,6 +157,14 @@ describe("Java debugging (java-debug through jdtls)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("asks the host for enhanced class redefinition when the configuration turns it on", async () => {
|
||||
const on = { ...app, params: { enhancedClassRedefinition: "true" } };
|
||||
expect(JSON.parse((await javaLaunchConfig(on, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
|
||||
expect(JSON.parse((await javaLaunchConfig(app, "/p")).extraJson!)).not.toHaveProperty("enhancedClassRedefinition");
|
||||
const kotlin = { ...on, debugAdapter: "kotlin-debug-adapter" };
|
||||
expect(JSON.parse((await javaLaunchConfig(kotlin, "/p")).extraJson!).enhancedClassRedefinition).toBe(true);
|
||||
});
|
||||
|
||||
it("lets java-debug shorten a classpath too long for the OS, as Run does", async () => {
|
||||
for (const how of ["jarmanifest", "argfile"]) {
|
||||
shortenCommandLine = how;
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
debugSetBreakpoints: vi.fn(),
|
||||
debugReplaceBreakpoints: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
debugStart: vi.fn(async () => ({ status: "ok", data: 42 })),
|
||||
debugStop: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
debugCapabilities: vi.fn(async () => ({ status: "ok", data: {} })),
|
||||
@@ -169,6 +170,24 @@ it("drains an in-flight update and sends pending removals before startup", async
|
||||
expect(ipc.debugStart).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("hands the window's whole list to the backend before startup, even after a failed removal (#6116)", async () => {
|
||||
ipc.debugSetBreakpoints.mockResolvedValueOnce({ status: "ok", data: [] }).mockRejectedValueOnce(new Error("lost"));
|
||||
addBreakpoint("/p/Main.java", 4);
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
removeAllBreakpoints();
|
||||
await vi.advanceTimersByTimeAsync(120);
|
||||
addBreakpoint("/p/Other.java", 7);
|
||||
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
|
||||
ipc.debugReplaceBreakpoints.mockClear();
|
||||
await startSession(config("launch"));
|
||||
expect(ipc.debugReplaceBreakpoints).toHaveBeenCalledExactlyOnceWith({
|
||||
"/p/Other.java": [expect.objectContaining({ line: 7, enabled: true })],
|
||||
});
|
||||
expect(ipc.debugReplaceBreakpoints.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
ipc.debugStart.mock.invocationCallOrder[0]!,
|
||||
);
|
||||
});
|
||||
|
||||
it("flushes persisted breakpoints immediately after project loading", async () => {
|
||||
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
|
||||
localStorage.setItem(
|
||||
|
||||
@@ -87,6 +87,8 @@ export function loadBreakpoints(root: string | null) {
|
||||
}
|
||||
const previous = Object.keys(useBreakpoints.getState().byFile);
|
||||
useBreakpoints.setState({ root, byFile, muted, status: {} });
|
||||
// The backend may still hold files this window no longer lists (a reloaded window).
|
||||
void replaceBreakpoints().catch((e) => console.warn("debugReplaceBreakpoints failed", e));
|
||||
for (const path of new Set([...previous, ...Object.keys(byFile)])) scheduleSync(path);
|
||||
}
|
||||
|
||||
@@ -129,6 +131,17 @@ async function drainBreakpoints() {
|
||||
await Promise.all([...paths].map((path) => syncFile(path)));
|
||||
paths = new Set([...timers.keys(), ...inFlight.keys()]);
|
||||
}
|
||||
// The new session gets exactly the files listed here, even if a removal never reached the
|
||||
// backend (#6116). Failing that, the session still starts with what the backend has.
|
||||
await replaceBreakpoints().catch((e) => console.warn("debugReplaceBreakpoints failed", e));
|
||||
}
|
||||
|
||||
/** Makes this window's whole list the backend's: files it no longer lists are cleared there. */
|
||||
async function replaceBreakpoints() {
|
||||
if (!isTauri() || useProject.getState().project?.trusted === false) return;
|
||||
const { byFile, muted } = useBreakpoints.getState();
|
||||
const files = Object.fromEntries(Object.entries(byFile).map(([path, list]) => [path, toBackend(list, muted, path)]));
|
||||
await call(commands.debugReplaceBreakpoints(files));
|
||||
}
|
||||
|
||||
export function syncFile(path: string): Promise<void> {
|
||||
|
||||
@@ -59,15 +59,40 @@ const classesText = (n: number) => (n === 1 ? tx`${n} class` : tx`${n} classes`)
|
||||
|
||||
// java-debug reports this after redefineClasses succeeds, with no changedClasses count.
|
||||
const obsoleteMethods = (message: string) => message.trim() === "JVM contains obsolete methods";
|
||||
// JDI's refusals of a structural change: "add method not implemented", "schema change not implemented", …
|
||||
const structuralChange = (message: string) => /\bnot implemented\b/i.test(message);
|
||||
|
||||
/** Application and Spring Boot configurations offer Enhanced class redefinition (JetBrains Runtime's DCEVM). */
|
||||
const ENHANCEABLE_KINDS = new Set(["application", "spring-boot"]);
|
||||
|
||||
/** Whether the session's configuration could turn on Enhanced class redefinition but has not. */
|
||||
export function canEnhanceRedefinition(s: DebugSession): boolean {
|
||||
const rc = s.runConfig;
|
||||
return !!rc && ENHANCEABLE_KINDS.has(rc.kind) && rc.params?.enhancedClassRedefinition !== "true";
|
||||
}
|
||||
|
||||
/** The failure text, plus how to allow structural changes when JDI refused one and the configuration can. */
|
||||
function failureBody(errors: string[], enhanceable: boolean): string {
|
||||
const body = errors.join("\n");
|
||||
if (!enhanceable || !errors.some(structuralChange)) return body;
|
||||
return (
|
||||
body +
|
||||
"\n\n" +
|
||||
tx(
|
||||
"To add or remove methods and fields, turn on Enhanced class redefinition in the run configuration and debug on JetBrains Runtime.",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** Message for the reload result (IDEA wording). */
|
||||
export function hotSwapMessage(
|
||||
changed: number,
|
||||
errors: string[],
|
||||
bottomFrame = false,
|
||||
enhanceable = false,
|
||||
): { level: "info" | "warning" | "error"; title: string; body?: string } {
|
||||
if (errors.some((e) => !obsoleteMethods(e)))
|
||||
return { level: "error", title: "Hot Swap failed", body: errors.join("\n") };
|
||||
return { level: "error", title: "Hot Swap failed", body: failureBody(errors, enhanceable) };
|
||||
if (errors.length)
|
||||
return {
|
||||
level: "warning",
|
||||
@@ -226,6 +251,7 @@ export async function reloadChangedClasses(build = true, configId?: string, allo
|
||||
changed.size,
|
||||
errors,
|
||||
affected.some((s) => s.status === "paused" && s.frames.length === 1),
|
||||
sessions.some(canEnhanceRedefinition),
|
||||
);
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
@@ -308,7 +334,7 @@ export function onHotCodeReplace(session: DebugSessionId, event: Extract<DebugEv
|
||||
level: event.changeType === "ERROR" ? "error" : "warning",
|
||||
key: KEY,
|
||||
title: "Hot Swap",
|
||||
body: event.message,
|
||||
body: failureBody([event.message], canEnhanceRedefinition(useDebug.getState().sessions[session]!)),
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -174,6 +174,8 @@ export async function javaLaunchConfig(
|
||||
preparation?.report?.(`${joinJavaArgs([resolved.command, ...resolved.args])}\n`);
|
||||
const agentNote = await remoteJavaAgentNote(rc);
|
||||
if (agentNote) preparation?.report?.(agentNote);
|
||||
// The host adds JetBrains Runtime's flag for it, or says in the console why the session runs without.
|
||||
const enhanced = rc.params?.enhancedClassRedefinition === "true" ? { enhancedClassRedefinition: true } : {};
|
||||
if (kotlin) {
|
||||
return {
|
||||
name: rc.name,
|
||||
@@ -191,6 +193,7 @@ export async function javaLaunchConfig(
|
||||
javaExec: resolved.command,
|
||||
vmArguments: [...consoleVmArgs(rc), ...parsed.vmArgs],
|
||||
programArgs: parsed.programArgs,
|
||||
...enhanced,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -212,6 +215,7 @@ export async function javaLaunchConfig(
|
||||
javaExec: resolved.command === "java" ? undefined : resolved.command,
|
||||
vmArgs: [...consoleVmArgs(rc), ...parsed.vmArgs],
|
||||
args: parsed.programArgs,
|
||||
...enhanced,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -243,6 +247,7 @@ export async function javaLaunchConfig(
|
||||
shortenCommandLine: info.shortenCommandLine ?? "none",
|
||||
console: "internalConsole",
|
||||
stopOnEntry: false,
|
||||
...enhanced,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* (threads, frames, locals) after each stop.
|
||||
*/
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { logError } from "@/platform/errorLog";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import { create } from "zustand";
|
||||
@@ -96,6 +97,8 @@ export interface DebugSession {
|
||||
threads: ThreadInfo[];
|
||||
selectedThread: number | null;
|
||||
frames: StackFrame[];
|
||||
/** Why the selected thread's frames could not be loaded (Threads & Variables offers a retry). */
|
||||
framesError?: string | null;
|
||||
selectedFrame: number | null;
|
||||
/** Breakpoint hits in this session. */
|
||||
hits: number;
|
||||
@@ -1296,16 +1299,19 @@ export function selectFrame(id: DebugSessionId, frameId: number, reveal = true)
|
||||
|
||||
/** `newStop`: false when returning to an earlier stop, whose breakpoint hit was handled when it happened. */
|
||||
async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean, newStop = true) {
|
||||
if (useDebug.getState().sessions[id]?.framesError) patch(id, { framesError: null });
|
||||
const before = useDebug.getState().sessions[id];
|
||||
let frames: StackFrame[] = [];
|
||||
let framesError: string | null = null;
|
||||
try {
|
||||
frames = await call(commands.debugStackTrace(id, threadId));
|
||||
} catch (e) {
|
||||
console.warn("stackTrace failed", e);
|
||||
logError("Debugger stack trace", e);
|
||||
framesError = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
const s = useDebug.getState().sessions[id];
|
||||
if (!s || s.status !== "paused" || s.selectedThread !== threadId || s.frames !== before?.frames) return;
|
||||
patch(id, { frames });
|
||||
patch(id, { frames, framesError });
|
||||
const top = topFrame(frames);
|
||||
if (newStop && top?.path && (s.stopReason === "breakpoint" || s.stopReason === "function breakpoint")) {
|
||||
void logSuspendingHit(id, top);
|
||||
|
||||
@@ -200,6 +200,14 @@
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.framesError {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-1-5);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* variables */
|
||||
.variables {
|
||||
height: 100%;
|
||||
|
||||
@@ -10,6 +10,7 @@ import { formatBinding, hostBinding } from "@/platform/keymap";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
import { call, commands, isTauri, type Scope, type Variable } from "@/platform/ipc";
|
||||
import {
|
||||
Button,
|
||||
EmptyState,
|
||||
Icon,
|
||||
IconButton,
|
||||
@@ -476,6 +477,14 @@ function FramesPane({ session }: { session: DebugSession }) {
|
||||
</div>
|
||||
)}
|
||||
{stopNote(session) && <div className={styles.note}>{stopNote(session)}</div>}
|
||||
{paused && session.framesError && session.selectedThread != null && (
|
||||
<div className={clsx(styles.note, styles.framesError)} role="alert">
|
||||
<span>{tx`Could not load the frames: ${session.framesError}`}</span>
|
||||
<Button size="small" onClick={() => void selectThread(session.id, session.selectedThread!)}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{items.map((item) =>
|
||||
item.kind === "hidden" ? (
|
||||
<button
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { convertIcls } from "../intellijTheme";
|
||||
|
||||
const opt = (name: string, value: string) =>
|
||||
`<option name="${name}"><value><option name="FOREGROUND" value="${value}"/></value></option>`;
|
||||
const scheme = (parent: string, ...options: string[]) =>
|
||||
`<scheme name="t" version="142" parent_scheme="${parent}"><attributes>${options.join("")}</attributes></scheme>`;
|
||||
|
||||
describe("annotation colour of a theme plugin's scheme (#6108)", () => {
|
||||
it("keeps Darcula's annotation colour when the file only changes DEFAULT_METADATA", () => {
|
||||
const { tokens } = convertIcls(scheme("Darcula", opt("DEFAULT_METADATA", "1d8711")));
|
||||
expect(tokens["--syn-annotation"]).toBe("#bbb529");
|
||||
expect(tokens["--syn-decorator"]).toBe("#1d8711");
|
||||
});
|
||||
|
||||
it("takes the file's annotation key for annotations", () => {
|
||||
const { tokens } = convertIcls(
|
||||
scheme("Darcula", opt("DEFAULT_METADATA", "1d8711"), opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d")),
|
||||
);
|
||||
expect(tokens["--syn-annotation"]).toBe("#9e880d");
|
||||
});
|
||||
|
||||
it("leaves a light parent's annotation colour to the base theme", () => {
|
||||
const { tokens } = convertIcls(scheme("Default", opt("DEFAULT_METADATA", "1d8711")));
|
||||
expect(tokens["--syn-annotation"]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { ContextMenuHost, hideContextMenu } from "@/ui";
|
||||
import type { View, ViewEvent } from "@/bindings";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { executeAction, registerAction } from "@/platform/actions";
|
||||
import { bindingsFor, effectiveBindings, registerExtensionBindings, useKeymap } from "@/platform/keymap";
|
||||
import { createMemoryPluginsBackend, setPluginsBackend, type PluginsBackend } from "../backend";
|
||||
import { commandArgs, defineBuiltinUiPoints } from "../points";
|
||||
@@ -11,7 +11,7 @@ import { clearUiContributions, syncUiContributions } from "../projection";
|
||||
import { pluginMenuItems, pluginViewItemMenuItems, withPluginSetting } from "../uiPoints";
|
||||
import { matchesPattern } from "../views/customEditor";
|
||||
import { FRAME_CSP, FRAME_TAG, frameDocument, frameTheme, type FrameTheme } from "../views/frame";
|
||||
import { PluginView, treeNodes, wantedViewport } from "../views/PluginView";
|
||||
import { focusedViewItem, PluginView, treeNodes, wantedViewport } from "../views/PluginView";
|
||||
import { bumpView } from "../views/viewStore";
|
||||
|
||||
let undefinePoints: () => void = () => {};
|
||||
@@ -341,6 +341,70 @@ describe("PluginView", () => {
|
||||
await waitFor(() => expect(events).toContainEqual({ kind: "button", id: "refresh" }));
|
||||
});
|
||||
|
||||
it("gives a shortcut-run command the selected item of the plugin's focused view", async () => {
|
||||
const item = (key: string, label: string) => ({
|
||||
key,
|
||||
parent: null,
|
||||
label,
|
||||
icon: null,
|
||||
detail: null,
|
||||
expandable: false,
|
||||
expanded: false,
|
||||
});
|
||||
const tree: View = {
|
||||
toolbar: [],
|
||||
body: { kind: "tree", value: [item("task:build", "build"), item("task:test", "test")] },
|
||||
status: null,
|
||||
};
|
||||
const backend = backendWith(() => tree);
|
||||
const runCommand = vi.fn(async () => null);
|
||||
setPluginsBackend({ ...backend, runCommand });
|
||||
syncUiContributions(
|
||||
[
|
||||
{ pluginId: "jobs", point: "commands", key: "open", decl: { id: "open", title: "Open Source" } },
|
||||
{ pluginId: "jobs", point: "commands", key: "sync", decl: { id: "sync", title: "Sync" } },
|
||||
{
|
||||
pluginId: "jobs",
|
||||
point: "menus",
|
||||
key: "viewItem.context/tasks/open",
|
||||
decl: { menu: "viewItem.context", view: "tasks", command: "open", when: "viewItemKind == task" },
|
||||
},
|
||||
],
|
||||
[
|
||||
{ id: "jobs", name: "Jobs", status: "active", enabled: true } as unknown as Parameters<
|
||||
typeof syncUiContributions
|
||||
>[1][number],
|
||||
],
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<PluginView
|
||||
pluginId="jobs"
|
||||
view="tasks"
|
||||
label="Tasks"
|
||||
itemMenu={(key) => pluginViewItemMenuItems("jobs", "tasks", key)}
|
||||
/>,
|
||||
);
|
||||
expect(focusedViewItem("jobs", "plugin.jobs.open")).toBeNull();
|
||||
await user.click(await screen.findByText("test"));
|
||||
await waitFor(() => expect(focusedViewItem("jobs", "plugin.jobs.open")).toBe("task:test"));
|
||||
expect(focusedViewItem("other", "plugin.other.open")).toBeNull();
|
||||
// Only a command the item's menu offers gets the item.
|
||||
expect(focusedViewItem("jobs", "plugin.jobs.sync")).toBeNull();
|
||||
await executeAction("plugin.jobs.sync");
|
||||
expect(runCommand).toHaveBeenLastCalledWith("jobs", "sync", null, null, []);
|
||||
await executeAction("plugin.jobs.open");
|
||||
expect(runCommand).toHaveBeenLastCalledWith("jobs", "open", "task:test", null, []);
|
||||
// A menu's own argument wins over the focused view.
|
||||
await executeAction("plugin.jobs.open", "task:build");
|
||||
expect(runCommand).toHaveBeenLastCalledWith("jobs", "open", "task:build", null, []);
|
||||
// Focus elsewhere: nothing selected for the command.
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
expect(focusedViewItem("jobs", "plugin.jobs.open")).toBeNull();
|
||||
await executeAction("plugin.jobs.open");
|
||||
expect(runCommand).toHaveBeenLastCalledWith("jobs", "open", null, null, []);
|
||||
});
|
||||
|
||||
it("opens the item menu on right-click", async () => {
|
||||
const tree: View = {
|
||||
toolbar: [],
|
||||
|
||||
@@ -18,6 +18,7 @@ import { SecretsDetails, type SecretDecl } from "./secrets";
|
||||
import { pluginSettingsPageId } from "./settings";
|
||||
import { pluginsBackend } from "./backend";
|
||||
import { isLive, runPluginCommand, usePlugins } from "./store";
|
||||
import { focusedViewItem } from "./views/PluginView";
|
||||
import styles from "./PluginsPage.module.css";
|
||||
|
||||
/** Unpacks an action argument: a bare path, or a menu's `{ path, paths }`. */
|
||||
@@ -244,7 +245,8 @@ export function defineCoreUiPoints(): () => void {
|
||||
keywords: ["plugin", plugin.name, pluginId],
|
||||
description: tx`From plugin ${plugin.name}`,
|
||||
run: async ({ arg }: { arg?: unknown }) => {
|
||||
const [path, paths] = commandArgs(arg);
|
||||
// A shortcut passes nothing: the plugin's focused view supplies its selected item.
|
||||
const [path, paths] = commandArgs(arg ?? focusedViewItem(pluginId, action.id));
|
||||
await runPluginCommand(pluginId, decl.id, path, paths);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -163,10 +163,9 @@ export const ICLS_ATTRIBUTES: Record<string, Array<[Part, string]>> = {
|
||||
DEFAULT_PARAMETER: [["FOREGROUND", "--syn-param"]],
|
||||
DEFAULT_GLOBAL_VARIABLE: [["FOREGROUND", "--syn-global"]],
|
||||
DEFAULT_PREDEFINED_SYMBOL: [["FOREGROUND", "--syn-builtin"]],
|
||||
DEFAULT_METADATA: [
|
||||
["FOREGROUND", "--syn-annotation"],
|
||||
["FOREGROUND", "--syn-decorator"],
|
||||
],
|
||||
// Java annotations take the scheme's (or its parent's) annotation key, not DEFAULT_METADATA.
|
||||
ANNOTATION_NAME_ATTRIBUTES: [["FOREGROUND", "--syn-annotation"]],
|
||||
DEFAULT_METADATA: [["FOREGROUND", "--syn-decorator"]],
|
||||
DEFAULT_OPERATION_SIGN: [["FOREGROUND", "--syn-punct"]],
|
||||
DEFAULT_VALID_STRING_ESCAPE: [["FOREGROUND", "--syn-escape"]],
|
||||
DEFAULT_TAG: [["FOREGROUND", "--syn-tag"]],
|
||||
|
||||
@@ -62,6 +62,34 @@ export interface PluginViewProps {
|
||||
const OVERSCAN = 50;
|
||||
const ROW_HEIGHT = 24;
|
||||
|
||||
/** Each rendered view root → its item menu, read when a command runs from a shortcut. */
|
||||
const viewMenus = new WeakMap<Element, (key: string) => MenuItem[]>();
|
||||
|
||||
const offers = (items: MenuItem[], action: string): boolean =>
|
||||
items.some((i) =>
|
||||
i.kind === "action"
|
||||
? i.action === action
|
||||
: (i.kind ?? "item") === "item" && offers(("submenu" in i && i.submenu) || [], action),
|
||||
);
|
||||
|
||||
/**
|
||||
* The argument a plugin command run without one (a shortcut, Find Action) gets from the plugin's
|
||||
* view that has the keyboard focus: the selected item's key, when that item's context menu offers
|
||||
* the command — the same argument as from the menu. Null when the focus is elsewhere, in another
|
||||
* plugin's view, nothing is selected, or the menu doesn't offer the command there.
|
||||
*/
|
||||
export function focusedViewItem(
|
||||
pluginId: string,
|
||||
action: string,
|
||||
focused: Element | null = document.activeElement,
|
||||
): string | null {
|
||||
const view = focused?.closest<HTMLElement>("[data-plugin-view]");
|
||||
const key = view?.dataset.selectedKey;
|
||||
if (!view || view.dataset.pluginView !== pluginId || key === undefined) return null;
|
||||
const menu = viewMenus.get(view);
|
||||
return menu && offers(menu(key), action) ? key : null;
|
||||
}
|
||||
|
||||
/** Plugin text is shown as written: the plugin translates it through its own catalog. */
|
||||
export function PluginView(props: PluginViewProps) {
|
||||
const location = useViewLocation();
|
||||
@@ -154,8 +182,19 @@ function PluginViewContent({
|
||||
</div>
|
||||
);
|
||||
|
||||
// The item a keyboard-invoked command of this plugin gets, as from the item's context menu
|
||||
// (`focusedViewItem`); only a key the view still shows.
|
||||
const currentKey = selection && items?.some((i) => i.key === selection.key) ? selection.key : undefined;
|
||||
return (
|
||||
<div className={styles.view} aria-label={label}>
|
||||
<div
|
||||
ref={(el) => {
|
||||
if (el && itemMenu) viewMenus.set(el, itemMenu);
|
||||
}}
|
||||
className={styles.view}
|
||||
aria-label={label}
|
||||
data-plugin-view={pluginId}
|
||||
data-selected-key={currentKey}
|
||||
>
|
||||
{content.toolbar.length > 0 && (
|
||||
<div className={styles.toolbar} role="toolbar">
|
||||
{content.toolbar.map((b) =>
|
||||
|
||||
@@ -20,8 +20,16 @@ export function packageKindAt(
|
||||
): PackageKind | null {
|
||||
if (rootFor(roots, rel)?.kind === "excluded") return null;
|
||||
if (isJvmSourcePackage(rel, roots)) return "jvm";
|
||||
const python = [...roots, ...detected].some(
|
||||
(r) => r.detectedFrom && PY_BUILD.test(r.detectedFrom) && within(rel, moduleDir(r.detectedFrom)),
|
||||
);
|
||||
return python ? "python" : null;
|
||||
// A root `pyproject.toml` must not claim `frontend/src`, a root that
|
||||
// `frontend/package.json` detected, unless a deeper Python module holds the folder.
|
||||
let python = -1;
|
||||
let other = -1;
|
||||
for (const r of [...roots, ...detected]) {
|
||||
if (!r.detectedFrom) continue;
|
||||
if (PY_BUILD.test(r.detectedFrom)) {
|
||||
const dir = moduleDir(r.detectedFrom);
|
||||
if (within(rel, dir)) python = Math.max(python, dir.length);
|
||||
} else if (within(rel, r.path)) other = Math.max(other, r.path.length);
|
||||
}
|
||||
return python >= 0 && python >= other ? "python" : null;
|
||||
}
|
||||
@@ -72,6 +72,25 @@ describe("New › Package", () => {
|
||||
expect(packageKindAt("build/classes", synced)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a nested non-Python module out of a root-level Python project", () => {
|
||||
// The roots detection reports for a root `pyproject.toml` next to `frontend/package.json`.
|
||||
const mixed = [
|
||||
root("src", "source", "pyproject.toml"),
|
||||
root("frontend/src", "source", "frontend/package.json"),
|
||||
root("frontend/node_modules", "excluded", "frontend/package.json"),
|
||||
];
|
||||
expect(packageKindAt("frontend/src/components", mixed)).toBeNull();
|
||||
expect(packageKindAt("src/app", mixed)).toBe("python");
|
||||
expect(packageKindAt("scripts", mixed)).toBe("python");
|
||||
});
|
||||
|
||||
it("keeps Python packages next to a nested package.json outside its roots", () => {
|
||||
// A Django app folder with its own `package.json` for front-end tooling.
|
||||
const django = [root("", "source", "pyproject.toml"), root("web/node_modules", "excluded", "web/package.json")];
|
||||
expect(packageKindAt("web/blog", django)).toBe("python");
|
||||
expect(packageKindAt("web", django)).toBe("python");
|
||||
});
|
||||
|
||||
it("validates dotted package names", () => {
|
||||
expect(packageSegments("com.acme.util", "jvm")).toEqual({ segments: ["com", "acme", "util"], error: null });
|
||||
expect(packageSegments("com..x", "jvm").error).toMatch(/Not a valid package name/);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* to it (platform/remote.ts).
|
||||
*/
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { disconnectRemote, stopRemoteBackend, useRemote } from "@/platform/remote";
|
||||
import { disconnectRemote, provideBackendBusyPrompt, stopRemoteBackend, useRemote } from "@/platform/remote";
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { maybeEditorService, registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
@@ -57,6 +57,16 @@ function trackPortsWindow(): () => void {
|
||||
|
||||
export function activate(): () => void {
|
||||
const disposers = [
|
||||
provideBackendBusyPrompt(() =>
|
||||
confirm({
|
||||
title: tx("Stop Remote Backend"),
|
||||
message: tx(
|
||||
"The backend of another OpenIDEA build, for example the one from before an upgrade, still has this project open, so this build can't open it. Stop that backend and open the project? Its terminals, runs and agent sessions end, and changes it hasn't saved are lost.",
|
||||
),
|
||||
ok: tx("Stop Backend and Open"),
|
||||
icon: "warning",
|
||||
}),
|
||||
),
|
||||
trackPortsWindow(),
|
||||
installReconnect(),
|
||||
installDirenvNotifications(),
|
||||
|
||||
@@ -146,6 +146,16 @@ describe("Application / Spring Boot command line", () => {
|
||||
expect(parsed.programArgs).toEqual(["--server.port=8081", "two words"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["application", applicationType],
|
||||
["spring-boot", springBootType],
|
||||
] as const)("%s offers Enhanced class redefinition for Debug without changing the Run command", (_, type) => {
|
||||
expect(type.fields.find((f) => f.key === "enhancedClassRedefinition")).toMatchObject({ control: "checkbox" });
|
||||
const params = { mainClass: "a.Main", classpath: "${classpath}" };
|
||||
expect(type.commandLine({ ...params, enhancedClassRedefinition: "true" })).toEqual(type.commandLine(params));
|
||||
expect(jarApplicationType.fields.some((f) => f.key === "enhancedClassRedefinition")).toBe(false);
|
||||
});
|
||||
|
||||
it("reads VM options over several lines and with quoted spaces", () => {
|
||||
const line = applicationType.commandLine({
|
||||
mainClass: "a.Main",
|
||||
|
||||
@@ -78,6 +78,17 @@ const jreField: RunConfigTypeField = {
|
||||
})),
|
||||
};
|
||||
|
||||
/**
|
||||
* JetBrains Runtime's `-XX:+AllowEnhancedClassRedefinition` for Debug, so Reload Changed Classes can add or
|
||||
* remove methods and fields. The host adds it only on JetBrains Runtime (other JVMs refuse to start with it).
|
||||
*/
|
||||
const enhancedRedefinitionField: RunConfigTypeField = {
|
||||
key: "enhancedClassRedefinition",
|
||||
label: "Enhanced class redefinition",
|
||||
control: "checkbox",
|
||||
hint: "When debugging on JetBrains Runtime, Reload Changed Classes can also add or remove methods and fields",
|
||||
};
|
||||
|
||||
/** IDEA's "Use classpath of module": the module whose classpath and build the run uses. */
|
||||
const moduleField: RunConfigTypeField = {
|
||||
key: "module",
|
||||
@@ -119,6 +130,7 @@ function jvmApplicationType(spring: boolean): RunConfigTypeContribution {
|
||||
...(spring ? [profilesField("Comma separated; passed as --spring.profiles.active")] : []),
|
||||
...(spring ? updatePolicyFields(false) : []),
|
||||
jreField,
|
||||
enhancedRedefinitionField,
|
||||
moduleField,
|
||||
{
|
||||
key: "classpath",
|
||||
|
||||
@@ -13,6 +13,7 @@ beforeEach(() => {
|
||||
notify.mockClear();
|
||||
});
|
||||
afterEach(() => {
|
||||
usePlatform.setState({ os: "macos" });
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
@@ -181,6 +182,7 @@ function remoteTarget(current = () => true): TerminalPasteTarget {
|
||||
}
|
||||
|
||||
it.each(["event", "menu"])("rejects oversized %s images before reading or uploading", async (route) => {
|
||||
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
|
||||
const read = vi.fn(async () => new ArrayBuffer(0));
|
||||
const blob = image(read, 20 * 1024 * 1024 + 1);
|
||||
const store = vi.spyOn(commands, "termStoreImage");
|
||||
@@ -246,6 +248,7 @@ it("claims remote image events before xterm and pastes a quoted path only after
|
||||
});
|
||||
|
||||
it("reads an image from the explicit paste menu after text and file recovery", async () => {
|
||||
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/stale.png"] });
|
||||
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
|
||||
const getType = vi.fn(async () => image());
|
||||
@@ -261,6 +264,7 @@ it("reads an image from the explicit paste menu after text and file recovery", a
|
||||
});
|
||||
|
||||
it("recovers remote menu file paths when image clipboard reading is unavailable", async () => {
|
||||
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: ["/local/file.txt"] });
|
||||
const store = vi.spyOn(commands, "termStoreImage");
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { readText: async () => "" } });
|
||||
@@ -271,6 +275,7 @@ it("recovers remote menu file paths when image clipboard reading is unavailable"
|
||||
});
|
||||
|
||||
it("uploads a menu image even if reading clipboard text is rejected", async () => {
|
||||
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
|
||||
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
configurable: true,
|
||||
@@ -304,6 +309,7 @@ it("uploads image events instead of recovering a local image path", async () =>
|
||||
});
|
||||
|
||||
it("does not upload a menu image when the target changes while reading", async () => {
|
||||
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
|
||||
let valid = true;
|
||||
let finish!: (value: Blob) => void;
|
||||
const getType = vi.fn(
|
||||
@@ -446,6 +452,7 @@ function localTarget(shell = "sh", current = () => true): TerminalPasteTarget {
|
||||
}
|
||||
|
||||
it.each(["event", "menu"])("stores raw local clipboard media through %s paste", async (route) => {
|
||||
usePlatform.setState({ os: "windows" }); // the WebView menu path; macOS reads natively
|
||||
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/tmp/a'b c.png" });
|
||||
const host = document.createElement("div");
|
||||
const paste = vi.fn();
|
||||
@@ -632,7 +639,7 @@ it.each([
|
||||
{ os: "linux", native: "ls -la", expected: ["ls -la"], execCommand: 0 },
|
||||
// An image-only clipboard keeps the WebView paths.
|
||||
{ os: "linux", native: "", expected: [], execCommand: 1 },
|
||||
{ os: "macos", native: "ls -la", expected: ["ls -la"], execCommand: 1 },
|
||||
{ os: "macos", native: "ls -la", expected: ["ls -la"], execCommand: 0 },
|
||||
] as const)("menu paste on $os with native text '$native'", async ({ os, native, expected, execCommand }) => {
|
||||
usePlatform.setState({ os });
|
||||
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: native });
|
||||
@@ -651,3 +658,68 @@ it.each([
|
||||
expect(exec).toHaveBeenCalledTimes(execCommand);
|
||||
expect(paste.mock.calls).toEqual(expected.map((text) => [text]));
|
||||
});
|
||||
|
||||
// WebKit on macOS shows a "Paste" callout for execCommand("paste") and navigator.clipboard reads
|
||||
// outside a paste event: a menu paste reads text, files and images through the backend.
|
||||
it.each([
|
||||
{ name: "text", text: "ls -la", files: [], png: null, target: localTarget, expected: "ls -la" },
|
||||
{
|
||||
name: "Finder file",
|
||||
text: "a b.txt",
|
||||
files: ["/x/a b.txt"],
|
||||
png: null,
|
||||
target: localTarget,
|
||||
expected: "'/x/a b.txt'",
|
||||
},
|
||||
{ name: "screenshot", text: null, files: [], png: "AQI=", target: localTarget, expected: "'/tmp/shot.png'" },
|
||||
{ name: "remote screenshot", text: null, files: [], png: "AQI=", target: remoteTarget, expected: "'/tmp/shot.png'" },
|
||||
{ name: "empty clipboard", text: null, files: [], png: null, target: localTarget, expected: null },
|
||||
{
|
||||
name: "remote file list",
|
||||
text: "",
|
||||
files: ["/x/a b.txt"],
|
||||
png: null,
|
||||
target: remoteTarget,
|
||||
expected: "/x/a b.txt",
|
||||
},
|
||||
])("macOS menu paste of $name never asks WebKit", async ({ text, files, png, target, expected }) => {
|
||||
usePlatform.setState({ os: "macos" });
|
||||
vi.spyOn(commands, "clipboardText").mockResolvedValue({ status: "ok", data: text });
|
||||
vi.spyOn(commands, "clipboardFileList").mockResolvedValue({ status: "ok", data: files });
|
||||
vi.spyOn(commands, "clipboardImage").mockResolvedValue({
|
||||
status: "ok",
|
||||
data: png && `data:image/png;base64,${png}`,
|
||||
});
|
||||
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/tmp/shot.png" });
|
||||
const web = { readText: vi.fn(async () => "web"), read: vi.fn(async () => []) };
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: web });
|
||||
const exec = vi.fn(() => false);
|
||||
Object.defineProperty(document, "queryCommandSupported", { configurable: true, value: () => true });
|
||||
Object.defineProperty(document, "execCommand", { configurable: true, value: exec });
|
||||
const paste = vi.fn();
|
||||
try {
|
||||
await pasteTerminalClipboard(paste, () => target());
|
||||
} finally {
|
||||
Reflect.deleteProperty(document, "queryCommandSupported");
|
||||
Reflect.deleteProperty(document, "execCommand");
|
||||
}
|
||||
expect(exec).not.toHaveBeenCalled();
|
||||
expect(web.readText).not.toHaveBeenCalled();
|
||||
expect(web.read).not.toHaveBeenCalled();
|
||||
expect(paste.mock.calls).toEqual(expected ? [[expected]] : []);
|
||||
if (png) expect(store).toHaveBeenCalledWith(42, png, "image/png");
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the WebView menu paste for a browser on macOS", async () => {
|
||||
vi.unstubAllGlobals();
|
||||
const store = vi.spyOn(commands, "termStoreImage").mockResolvedValue({ status: "ok", data: "/remote/image.png" });
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
configurable: true,
|
||||
value: { readText: async () => "", read: async () => [{ types: ["image/png"], getType: async () => image() }] },
|
||||
});
|
||||
const paste = vi.fn();
|
||||
await pasteTerminalClipboard(paste, () => remoteTarget());
|
||||
expect(store).toHaveBeenCalledWith(42, "AQI=", "image/png");
|
||||
expect(paste).toHaveBeenCalledWith("'/remote/image.png'");
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { pasteClipboardFiles, readClipboardPlainText, readClipboardText } from "@/platform/clipboard";
|
||||
import { pasteClipboardFiles, readClipboardPlainText, readClipboardPng, readClipboardText } from "@/platform/clipboard";
|
||||
import { toBase64 } from "@/platform/base64";
|
||||
import { call, commands, type TerminalId } from "@/platform/ipc";
|
||||
import { call, commands, isTauri, type TerminalId } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
@@ -139,6 +139,28 @@ export async function pasteTerminalClipboard(paste: (text: string) => void, getT
|
||||
return;
|
||||
}
|
||||
}
|
||||
// WebKit on macOS asks the user to confirm execCommand("paste") and Clipboard.read() from a
|
||||
// menu with a "Paste" callout; the backend reads files, text and images without asking.
|
||||
if (target && isTauri() && usePlatform.getState().os === "macos") {
|
||||
const paths: string[] = await call(commands.clipboardFileList()).catch(() => []);
|
||||
const text =
|
||||
paths.length && !target.remote ? pathsText(paths, target) : await readClipboardPlainText().catch(() => "");
|
||||
if (!target.current()) return;
|
||||
if (text) {
|
||||
paste(text);
|
||||
return;
|
||||
}
|
||||
const png = await readClipboardPng();
|
||||
if (!target.current()) return;
|
||||
if (png)
|
||||
await pasteMedia(
|
||||
new Blob([Uint8Array.from(atob(png), (c) => c.charCodeAt(0))], { type: "image/png" }),
|
||||
target,
|
||||
paste,
|
||||
);
|
||||
else if (paths.length) paste(paths.join("\n"));
|
||||
return;
|
||||
}
|
||||
// Native paste preserves clipboard blobs where Clipboard.read() is unavailable.
|
||||
if (target && document.queryCommandSupported?.("paste") && document.execCommand("paste")) return;
|
||||
const images =
|
||||
|
||||
@@ -1130,6 +1130,7 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia
|
||||
>
|
||||
<Tree<ChangeNode>
|
||||
handleRef={treeRef}
|
||||
horizontalScroll
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={nodeText}
|
||||
|
||||
@@ -438,9 +438,12 @@ function TwoPaneDiff({
|
||||
inputKey.current = input.key;
|
||||
// Swap Sides shows the request's sides the other way round; another request starts unswapped.
|
||||
const [swappedFor, setSwappedFor] = useState<DiffData | null>(null);
|
||||
// The one-side viewer puts its only editable document into the unified editor.
|
||||
const indexOnlyLeft = isIndex(input_.left) && input_.right.type === "text" && input_.right.absent;
|
||||
const swapped = !!indexOnlyLeft || swappedFor === input_;
|
||||
// The one-side viewer puts its only editable document into the unified editor. A deleted
|
||||
// file's diff shows the original text as the document itself: the absent side stays on the
|
||||
// left as the diff's original, as for a staged deletion.
|
||||
const deletedOneSided =
|
||||
!(input_.left.type === "text" && input_.left.absent) && input_.right.type === "text" && !!input_.right.absent;
|
||||
const swapped = deletedOneSided || swappedFor === input_;
|
||||
const data = useMemo(
|
||||
() => (swapped ? { ...input_, left: input_.right, right: input_.left } : input_),
|
||||
[input_, swapped],
|
||||
@@ -1788,7 +1791,7 @@ function TwoPaneDiff({
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
className={clsx(styles.root, fit && styles.fit, indexOnlyLeft && styles.indexDeletion)}
|
||||
className={clsx(styles.root, fit && styles.fit, deletedOneSided && styles.indexDeletion)}
|
||||
onKeyDown={onKeyDown}
|
||||
onFocusCapture={() => {
|
||||
setFocusedDiffNavigator(nav.current);
|
||||
@@ -1994,7 +1997,7 @@ function TwoPaneDiff({
|
||||
size="small"
|
||||
onClick={() => {
|
||||
void Promise.resolve(indexDoc?.save())
|
||||
.then(() => executeAction("vcs.showDiffInNewWindow", indexOnlyLeft ? input_ : data))
|
||||
.then(() => executeAction("vcs.showDiffInNewWindow", deletedOneSided ? input_ : data))
|
||||
.catch(() => {});
|
||||
}}
|
||||
/>
|
||||
@@ -2049,15 +2052,25 @@ function TwoPaneDiff({
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
// A deleted file's swapped viewer still reads in the request's order: revision → (deleted).
|
||||
<div className={labels}>
|
||||
<span className={styles.label} title={sourceLabels ? `${captionA} → ${captionB}` : undefined}>
|
||||
<span className={styles.labelText}>{sideLabel(left)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...titleA} />}
|
||||
<span
|
||||
className={styles.label}
|
||||
title={
|
||||
sourceLabels ? (deletedOneSided ? `${captionB} → ${captionA}` : `${captionA} → ${captionB}`) : undefined
|
||||
}
|
||||
>
|
||||
<span className={styles.labelText}>{sideLabel(deletedOneSided ? right : left)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...(deletedOneSided ? titleB : titleA)} />}
|
||||
{unifiedOnLeft && <span className={styles.badge}>{tx("editable")}</span>}
|
||||
{eolDiffers && eolA && <span className={styles.badge}>{badgeA}</span>} →
|
||||
<span className={styles.labelText}>{sideLabel(right)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...titleB} />}
|
||||
{eolDiffers && eolB && <span className={styles.badge}>{badgeB}</span>}
|
||||
{eolDiffers && (deletedOneSided ? eolB : eolA) && (
|
||||
<span className={styles.badge}>{deletedOneSided ? badgeB : badgeA}</span>
|
||||
)}{" "}
|
||||
→<span className={styles.labelText}>{sideLabel(deletedOneSided ? left : right)}</span>
|
||||
{sourceLabels && <PaneTitleDetail {...(deletedOneSided ? titleA : titleB)} />}
|
||||
{eolDiffers && (deletedOneSided ? eolA : eolB) && (
|
||||
<span className={styles.badge}>{deletedOneSided ? badgeA : badgeB}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -37,7 +37,8 @@ export function blockOf(text: string, [from, to]: readonly [number, number]): st
|
||||
/** The rows of the list: Local Changes when the block differs from HEAD, then the commits. */
|
||||
export function historyRows(history: BlockHistory, current: string): HistoryRow[] {
|
||||
const rows: HistoryRow[] = history.revisions.map((revision) => ({ kind: "revision", revision }));
|
||||
const head = history.revisions[0]?.after;
|
||||
// Servers that predate `head` only give the newest row's block, which a merge leaves empty.
|
||||
const head = history.head ?? history.revisions[0]?.after;
|
||||
if (history.headLines && head !== undefined && head !== current) rows.unshift({ kind: "local", head, current });
|
||||
return rows;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, call: vi.fn() };
|
||||
});
|
||||
|
||||
vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
|
||||
|
||||
import { ChangesTree } from "../CommitView";
|
||||
import { useVcs } from "../store";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
const NAME = "some_long_service_implementation_with_a_very_long_name.ts";
|
||||
|
||||
describe("changes tree width (#6080)", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
});
|
||||
useVcs.setState({
|
||||
root: "/p",
|
||||
repo: "/p",
|
||||
roots: ["/p"],
|
||||
status: [
|
||||
{
|
||||
path: `/p/src/features/some_long_module_name/${NAME}`,
|
||||
relPath: `src/features/some_long_module_name/${NAME}`,
|
||||
staged: null,
|
||||
unstaged: "modified" as const,
|
||||
renamedFrom: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["commit", "local"] as const)("scrolls horizontally in %s mode instead of clipping rows", (mode) => {
|
||||
render(<ChangesTree mode={mode} />);
|
||||
const tree = screen.getByRole("tree", { name: "Changes" });
|
||||
// The rows keep their natural width and the tree tracks the widest one for its scroll range.
|
||||
expect(tree.querySelector("[data-content-width]")).not.toBeNull();
|
||||
const row = screen.getByText(NAME).closest("[data-row]") as HTMLElement;
|
||||
expect(row.className).toMatch(/wideRow/);
|
||||
});
|
||||
});
|
||||
@@ -221,6 +221,16 @@ describe("commit message draft (#4423)", () => {
|
||||
expect(useCommit.getState()).toMatchObject({ author: "", authorDate: scoped.authorDate, amend: false });
|
||||
});
|
||||
|
||||
it("loads no message for Amend with several repositories (#6149)", async () => {
|
||||
useVcs.setState({ root: "/a", roots: ["/a", "/a/b"] });
|
||||
type("my draft");
|
||||
await setAmend(true);
|
||||
expect(vcsLog).not.toHaveBeenCalled();
|
||||
expect(useCommit.getState()).toMatchObject({ amend: true, message: "my draft" });
|
||||
await setAmend(false);
|
||||
expect(useCommit.getState()).toMatchObject({ amend: false, message: "my draft" });
|
||||
});
|
||||
|
||||
it("keeps the typed draft, not the amended commit's message, while Amend is on", async () => {
|
||||
type("my draft");
|
||||
flushDraft();
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, waitFor } from "@testing-library/react";
|
||||
import type { EditorInput } from "@/workbench/contributions";
|
||||
|
||||
const texts: Record<string, string> = { HEAD: "a\nb\nc\n" };
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
fsProbe: () => Promise.resolve({ status: "ok", data: { size: 0, binary: false, tooLarge: false } }),
|
||||
vcsFileAt: (_path: string, rev: string) => Promise.resolve({ status: "ok", data: texts[rev] }),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { DiffEditor } from "../DiffEditor";
|
||||
|
||||
const input = {
|
||||
kind: "diff",
|
||||
key: "diff:deleted",
|
||||
data: {
|
||||
path: "/p/a.ts",
|
||||
left: { type: "rev", rev: "HEAD" },
|
||||
right: { type: "text", text: "", label: "(deleted)", absent: true },
|
||||
},
|
||||
} as unknown as EditorInput;
|
||||
|
||||
/** Plain gutter numbers rendered for document lines (skipping the hidden width-calibration spacer). */
|
||||
const gutterNumbers = (container: HTMLElement) =>
|
||||
[...container.querySelectorAll(".cm-lineNumbers .cm-gutterElement")]
|
||||
.filter((n) => (n as HTMLElement).style.visibility !== "hidden")
|
||||
.map((n) => n.textContent)
|
||||
.filter((t) => t && /^\d+$/.test(t));
|
||||
|
||||
describe("line numbers of a deleted file's diff", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => localStorage.clear());
|
||||
|
||||
it("shows the original text as the document itself, numbered like an editor", async () => {
|
||||
const mounted = render(<DiffEditor input={input} />);
|
||||
try {
|
||||
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-editor")).toHaveLength(1));
|
||||
// "a\nb\nc\n" is four CodeMirror lines, the last one empty, as in the editor itself.
|
||||
await waitFor(() => expect(gutterNumbers(mounted.container)).toEqual(["1", "2", "3", "4"]));
|
||||
const lines = [...mounted.container.querySelectorAll(".cm-content > .cm-line")].map((l) => l.textContent);
|
||||
expect(lines).toEqual(["a", "b", "c", ""]);
|
||||
// No mirrored widget numbers: the lines are real, so the gutter, selection and context
|
||||
// menu behave like the editor's.
|
||||
expect(mounted.container.querySelector(".cm-diffWidgetNumber")).toBeNull();
|
||||
} finally {
|
||||
mounted.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the document's own numbers for an added file", async () => {
|
||||
const added = {
|
||||
...input,
|
||||
data: {
|
||||
path: "/p/a.ts",
|
||||
left: { type: "text", text: "", label: "(does not exist)", absent: true },
|
||||
right: { type: "rev", rev: "HEAD" },
|
||||
},
|
||||
} as unknown as EditorInput;
|
||||
texts.HEAD = "a\nb\nc\n";
|
||||
const mounted = render(<DiffEditor input={added} />);
|
||||
try {
|
||||
await waitFor(() => expect(mounted.container.querySelectorAll(".cm-editor")).toHaveLength(1));
|
||||
await waitFor(() => expect(gutterNumbers(mounted.container)).toContain("3"));
|
||||
} finally {
|
||||
mounted.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { Chunk, MergeView } from "@codemirror/merge";
|
||||
import { Text } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { bandAt, bandPath, transferY, PaddedPanes, UnalignedPanes, type Band } from "../diffScroll";
|
||||
import { collapsedDiffLines } from "../collapsedDiffLines";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
@@ -177,6 +178,32 @@ describe("synchronized navigation scrolling", () => {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the wheel-scrolled pane in charge when the follower pane adjusts scrollTop on measure", () => {
|
||||
vi.useFakeTimers();
|
||||
const frame = vi.spyOn(window, "requestAnimationFrame").mockReturnValue(1);
|
||||
const p = panes();
|
||||
try {
|
||||
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
|
||||
p.scroll(p.b, 1200);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(1200);
|
||||
// Repeated wheel events must not cancel native momentum with scrollTo(instant).
|
||||
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
|
||||
expect(p.b.scrollDOM.scrollTo).not.toHaveBeenCalled();
|
||||
// Follower shifts from CodeMirror height measurement must not yank the wheel source back.
|
||||
p.scroll(p.a, 800);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(1200);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(1200);
|
||||
// Pointer interaction on the other pane hands control back immediately.
|
||||
p.a.scrollDOM.dispatchEvent(new Event("pointerdown"));
|
||||
p.scroll(p.a, 400);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(400);
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
frame.mockRestore();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("padded pane scrolling (aligned diff)", () => {
|
||||
@@ -241,6 +268,60 @@ describe("padded pane scrolling (aligned diff)", () => {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the wheel-scrolled pane in charge when the follower shifts during layout", () => {
|
||||
vi.useFakeTimers();
|
||||
const p = panes();
|
||||
try {
|
||||
p.b.scrollDOM.dispatchEvent(new Event("wheel"));
|
||||
p.scroll(p.b, 900);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(900);
|
||||
p.scroll(p.a, 500);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(900);
|
||||
expect(p.a.scrollDOM.scrollTop).toBe(900);
|
||||
vi.advanceTimersByTime(150);
|
||||
p.scroll(p.a, 200);
|
||||
expect(p.b.scrollDOM.scrollTop).toBe(200);
|
||||
} finally {
|
||||
p.controller.destroy();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("collapsed diff lines", () => {
|
||||
it("defers button DOM replacement from docViewUpdate into CodeMirror's measure write phase", () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc: "a\nb\nc", extensions: [collapsedDiffLines()] }),
|
||||
parent,
|
||||
});
|
||||
const measureSpy = vi.spyOn(view, "requestMeasure");
|
||||
try {
|
||||
const row = document.createElement("div");
|
||||
row.className = "cm-collapsedLines";
|
||||
row.textContent = "10 unchanged lines";
|
||||
view.contentDOM.appendChild(row);
|
||||
const plugin = (
|
||||
view as unknown as { plugins: Array<{ value: { docViewUpdate?: () => void } | null }> }
|
||||
).plugins.find((p) => typeof p.value?.docViewUpdate === "function");
|
||||
expect(plugin).toBeDefined();
|
||||
measureSpy.mockClear();
|
||||
plugin!.value!.docViewUpdate!();
|
||||
// Must not mutate DOM synchronously during docViewUpdate (triggers WebKit scrollTop clamping).
|
||||
expect(row.querySelector("button")).toBeNull();
|
||||
expect(measureSpy).toHaveBeenCalledTimes(1);
|
||||
const req = measureSpy.mock.calls[0]![0] as { write?: (v: unknown, view: EditorView) => void };
|
||||
req.write?.(null, view);
|
||||
expect(row.querySelector("button")).not.toBeNull();
|
||||
expect(row.querySelector("button")?.textContent).toBe("10 unchanged lines");
|
||||
} finally {
|
||||
measureSpy.mockRestore();
|
||||
view.destroy();
|
||||
parent.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("divider arrows", () => {
|
||||
|
||||
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача