дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-25 19:04:37 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
0682bc5f6b | ||
|
|
098e80dbef | ||
|
|
6ab7627fc4 | ||
|
|
55e778897f | ||
|
|
cc6ed6b5fd | ||
|
|
5efd58d3af | ||
|
|
d250b351bb | ||
|
|
033f049caf | ||
|
|
74157ffe54 | ||
|
|
732e92f756 | ||
|
|
a83bad107c | ||
|
|
39f709def5 | ||
|
|
ea6638b05e | ||
|
|
a91421c6e0 | ||
|
|
973f0a18a8 | ||
|
|
fb64f0cd26 | ||
|
|
34f2e18ff1 | ||
|
|
83a949ffe9 | ||
|
|
af8bd1afcd | ||
|
|
ce12f68613 | ||
|
|
77996f17e7 | ||
|
|
bacdd3e5c3 | ||
|
|
cb7bddec14 | ||
|
|
407561e59a | ||
|
|
e34e925b8f | ||
|
|
04ab9e8999 | ||
|
|
4a9927c256 | ||
|
|
084be4fb51 | ||
|
|
5c0ff2a918 | ||
|
|
c65acc902e | ||
|
|
ec0a681b72 | ||
|
|
5895022904 | ||
|
|
215023e85c | ||
|
|
aab53f89b3 | ||
|
|
519f1d43f4 | ||
|
|
88368033be | ||
|
|
d952827557 |
No files matched your search
@@ -1,119 +0,0 @@
|
||||
name: Nightly
|
||||
|
||||
# Twice a day, builds the newest main commit that passed CI as a prerelease tagged with its own
|
||||
# version, so remote development finds the server of that version. The `nightly` release holds
|
||||
# the manifest the nightly app updates from; its tag marks the commit last built, and a run with
|
||||
# nothing newer stops there. Only the latest builds are kept.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "17 2,14 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: "Build even if nothing is newer than the last nightly"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nightly
|
||||
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
permissions:
|
||||
actions: read
|
||||
contents: write
|
||||
if: github.repository == 'l0ng-ai/openidea'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
sha: ${{ steps.commit.outputs.sha }}
|
||||
tag: ${{ steps.release.outputs.tag }}
|
||||
release_id: ${{ steps.release.outputs.id }}
|
||||
steps:
|
||||
- id: commit
|
||||
env:
|
||||
FORCE: ${{ inputs.force }}
|
||||
run: |
|
||||
sha="$(gh run list --workflow ci.yml --branch main --event push --status success --limit 1 \
|
||||
--json headSha --jq '.[0].headSha // ""')"
|
||||
if [ -z "$sha" ]; then
|
||||
echo "::notice::no main commit has passed CI"
|
||||
exit 0
|
||||
fi
|
||||
# No `nightly` tag yet (the first run): compare fails and the build goes on.
|
||||
status="$(gh api "repos/$GH_REPO/compare/nightly...$sha" --jq .status 2>/dev/null)" || status=ahead
|
||||
if [ "$status" != ahead ] && [ "$FORCE" != true ]; then
|
||||
echo "::notice::$sha is not newer than the last nightly"
|
||||
exit 0
|
||||
fi
|
||||
echo "sha=$sha" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.commit.outputs.sha != ''
|
||||
with: { ref: "${{ steps.commit.outputs.sha }}" }
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.commit.outputs.sha != ''
|
||||
with: { node-version: 22 }
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
if: steps.commit.outputs.sha != ''
|
||||
- id: release
|
||||
if: steps.commit.outputs.sha != ''
|
||||
env:
|
||||
SHA: ${{ steps.commit.outputs.sha }}
|
||||
run: |
|
||||
version="$(node scripts/nightly-prepare.ts "$(date -u +%Y%m%d%H%M)")"
|
||||
tag="v$version"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git commit -am "chore: $tag"
|
||||
git tag "$tag"
|
||||
git push origin "$tag"
|
||||
id="$(gh api -X POST "repos/$GH_REPO/releases" -f tag_name="$tag" -f name="OpenIDEA Nightly $version" \
|
||||
-F draft=true -F prerelease=true -f body="Built from $SHA." --jq .id)"
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
echo "id=$id" >> "$GITHUB_OUTPUT"
|
||||
|
||||
binaries:
|
||||
permissions:
|
||||
contents: write
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.tag != ''
|
||||
uses: ./.github/workflows/release-build.yml
|
||||
with:
|
||||
tag: ${{ needs.prepare.outputs.tag }}
|
||||
release_id: ${{ needs.prepare.outputs.release_id }}
|
||||
secrets: inherit
|
||||
|
||||
publish:
|
||||
permissions:
|
||||
contents: write
|
||||
needs: [prepare, binaries]
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
TAG: ${{ needs.prepare.outputs.tag }}
|
||||
SHA: ${{ needs.prepare.outputs.sha }}
|
||||
KEEP: 14
|
||||
steps:
|
||||
- name: Publish the build
|
||||
run: gh release edit "$TAG" --tag "$TAG" --draft=false
|
||||
- name: Point the updater at it
|
||||
run: |
|
||||
gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP"
|
||||
gh release view nightly >/dev/null 2>&1 ||
|
||||
gh release create nightly --prerelease --latest=false --target "$SHA" --title "OpenIDEA Nightly" \
|
||||
--notes "The update manifest of the nightly builds, and the commit last built."
|
||||
gh release upload nightly "$RUNNER_TEMP/latest.json" --clobber
|
||||
gh api -X PATCH "repos/$GH_REPO/git/refs/tags/nightly" -f sha="$SHA" -F force=true --silent
|
||||
# Failed builds' drafts go too, once they are this old.
|
||||
- name: Delete old builds
|
||||
run: |
|
||||
gh release list --limit 200 --json tagName,createdAt --jq \
|
||||
'[.[] | select(.tagName | contains("-nightly."))] | sort_by(.createdAt) | reverse | .[env.KEEP | tonumber:][].tagName' |
|
||||
while read -r tag; do
|
||||
gh release delete "$tag" --cleanup-tag --yes
|
||||
done
|
||||
@@ -1,7 +1,7 @@
|
||||
name: Release build
|
||||
|
||||
# Builds a tag's desktop apps, remote servers and updater manifest into its draft release.
|
||||
# Stable releases (release.yml) and nightly builds (nightly.yml) both run it.
|
||||
# Builds a tag's desktop apps, remote servers and updater manifest into its draft release
|
||||
# (run by release.yml).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -224,18 +224,17 @@ jobs:
|
||||
return;
|
||||
}
|
||||
// Bundle suffix → updater platform keys, as tauri-action names them.
|
||||
// Nightly versions don't fit MSI or RPM, so those builds offer NSIS on Windows.
|
||||
const nightly = tag.includes("-nightly.");
|
||||
const windows = (arch, msi, nsis) => nightly
|
||||
? [[nsis, [`windows-${arch}`, `windows-${arch}-nsis`]]]
|
||||
: [[msi, [`windows-${arch}`, `windows-${arch}-msi`]], [nsis, [`windows-${arch}-nsis`]]];
|
||||
const windows = (arch, msi, nsis) => [
|
||||
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
|
||||
[nsis, [`windows-${arch}-nsis`]],
|
||||
];
|
||||
const kinds = [
|
||||
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
|
||||
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
|
||||
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
|
||||
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
|
||||
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
|
||||
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
|
||||
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
|
||||
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
|
||||
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
|
||||
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
|
||||
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
tags: ["v*", "!v*-nightly.*"]
|
||||
tags: ["v*"]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
@@ -23,7 +23,6 @@ env:
|
||||
jobs:
|
||||
# Creates (or reuses) one draft release that every platform build uploads into.
|
||||
create-release:
|
||||
if: ${{ !contains(github.event.inputs.tag || github.ref_name, '-nightly.') }}
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
@@ -62,7 +61,7 @@ jobs:
|
||||
core.setOutput("id", existing.id);
|
||||
return;
|
||||
}
|
||||
// Nightly builds are prereleases: the notes span stable release to stable release.
|
||||
// Prereleases are skipped: the notes span stable release to stable release.
|
||||
const previous = releases.find((r) => !r.draft && !r.prerelease);
|
||||
const { data: notes } = await github.rest.repos.generateReleaseNotes({
|
||||
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
|
||||
|
||||
@@ -3042,7 +3042,7 @@ fn blocks(prompt: &AgentPrompt, contents: &[Option<String>]) -> Vec<Value> {
|
||||
});
|
||||
}
|
||||
for i in &prompt.images {
|
||||
out.push(json!({ "type": "image", "mimeType": i.mime_type, "data": i.data }));
|
||||
out.push(json!({ "type": "image", "mimeType": i.media_type(), "data": i.data }));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -281,6 +281,22 @@ pub struct AgentImage {
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
impl AgentImage {
|
||||
/// The type the bytes are in. Agents reject an image whose declared type doesn't match its
|
||||
/// bytes, and a pasted image's declared type can be wrong (a browser's JPEG or WebP copied as
|
||||
/// `image/png`). Falls back to `mime_type` for formats not recognised here.
|
||||
pub fn media_type(&self) -> &str {
|
||||
let head = crate::acp::normalize_base64(&self.data[..self.data.len().min(16)]);
|
||||
match head.as_slice() {
|
||||
[0x89, b'P', b'N', b'G', ..] => "image/png",
|
||||
[0xFF, 0xD8, 0xFF, ..] => "image/jpeg",
|
||||
[b'G', b'I', b'F', b'8', ..] => "image/gif",
|
||||
[b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => "image/webp",
|
||||
_ => &self.mime_type,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A message to the agent: text, plus files to look at and images.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -1335,6 +1335,25 @@ async fn subagents_get_their_own_conversation() {
|
||||
check(&manager(tmp.path(), Arc::new(FakeAgent::default())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_blocks_declare_the_type_of_their_bytes() {
|
||||
let image = |mime: &str, data: &str| AgentImage { mime_type: mime.into(), data: data.into(), name: None };
|
||||
let cases = [
|
||||
// A browser's JPEG pasted as PNG.
|
||||
(image("image/png", "/9j/4AAQSkZJRgABAQ"), "image/jpeg"),
|
||||
(image("image/jpeg", "iVBORw0KGgoAAAANSUhEUg"), "image/png"),
|
||||
(image("image/png", "R0lGODlhAQABAIAAAP"), "image/gif"),
|
||||
(image("image/png", "UklGRiQAAABXRUJQVlA4"), "image/webp"),
|
||||
// Not recognised: as declared.
|
||||
(image("image/bmp", "Qk02AAAAAAAAADYAAA"), "image/bmp"),
|
||||
(image("image/png", "AAA"), "image/png"),
|
||||
];
|
||||
for (image, expected) in cases {
|
||||
let p = AgentPrompt { text: String::new(), files: vec![], images: vec![image] };
|
||||
assert_eq!(blocks(&p, &[])[0]["mimeType"], expected, "{:?}", p.images[0].data);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompts_become_acp_content_blocks() {
|
||||
let p = AgentPrompt {
|
||||
|
||||
@@ -10,11 +10,14 @@ use std::process::Command as ProcCommand;
|
||||
|
||||
/// Output file of the `dependency:build-classpath` probe, relative to each module.
|
||||
const CP_FILE: &str = "target/ide-compile-cp.txt";
|
||||
// Older records include undeclared reactor test outputs even in runtime classpaths.
|
||||
const CLASSPATH_CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// The resolved dependency classpath for one module and scope, tied to the same
|
||||
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct CachedClasspath {
|
||||
version: u32,
|
||||
fingerprint: LaunchFingerprint,
|
||||
classpath: String,
|
||||
}
|
||||
@@ -132,6 +135,7 @@ pub fn module_classpath(
|
||||
if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
@@ -142,7 +146,7 @@ pub fn module_classpath(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
let cached = CachedClasspath { fingerprint, classpath: classpath.clone() };
|
||||
let cached = CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
|
||||
}
|
||||
@@ -208,11 +212,11 @@ fn classpath(
|
||||
if dir == target.module {
|
||||
continue;
|
||||
}
|
||||
for classes in ["target/classes", "target/test-classes"] {
|
||||
let path = dir.join(classes);
|
||||
if path.is_dir() {
|
||||
entries.push(path.to_string_lossy().into_owned());
|
||||
}
|
||||
// A dependency's tests are not exported with its main artifact. Any explicitly
|
||||
// declared test artifact is supplied by Maven's resolved classpath below.
|
||||
let path = dir.join("target/classes");
|
||||
if path.is_dir() {
|
||||
entries.push(path.to_string_lossy().into_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -337,13 +341,19 @@ mod tests {
|
||||
root,
|
||||
"pom.xml",
|
||||
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
|
||||
<packaging>pom</packaging><modules><module>lib</module><module>app</module></modules></project>"#,
|
||||
<packaging>pom</packaging><modules><module>shared</module><module>lib</module><module>app</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"lib/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>lib</artifactId></project>"#,
|
||||
<artifactId>lib</artifactId><dependencies><dependency><groupId>demo</groupId><artifactId>shared</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"shared/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>shared</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
@@ -354,6 +364,7 @@ mod tests {
|
||||
write(root, "app/src/main/java/demo/Main.java", "class Main {}");
|
||||
write(root, "app/src/test/java/demo/MainTest.java", "class MainTest {}");
|
||||
write(root, "lib/target/classes/Lib.class", "built");
|
||||
write(root, "shared/target/classes/Shared.class", "built");
|
||||
crate::load(root, &root.join("cache"), None)
|
||||
}
|
||||
|
||||
@@ -436,7 +447,9 @@ mod tests {
|
||||
let target = single_file_target(root, &model, &file).unwrap();
|
||||
assert!(target.top.command.ends_with("mvnw"));
|
||||
assert_eq!(target.pl, "app");
|
||||
fs::create_dir_all(root.join("lib/target/test-classes")).unwrap();
|
||||
let cp = single_file_classpath(root, &model, &target).unwrap();
|
||||
assert!(!std::env::split_paths(&cp).any(|p| p == root.join("lib/target/test-classes")), "{cp}");
|
||||
let separator = ':';
|
||||
// Reactor class directories first, so fresh outputs shadow installed snapshots.
|
||||
let lib = root.join("lib/target/classes").to_string_lossy().into_owned();
|
||||
@@ -451,9 +464,16 @@ mod tests {
|
||||
assert!(cp.split(separator).count() >= 3, "{cp}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(!args.lines().any(|a| a == "compile" || a == "package"), "{args}");
|
||||
fs::create_dir_all(root.join("app/target/test-classes")).unwrap();
|
||||
let target = single_file_target(root, &model, &root.join("app/src/test/java/demo/MainTest.java")).unwrap();
|
||||
let cp = single_file_classpath(root, &model, &target).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert_eq!(paths[0], root.join("app/target/test-classes"));
|
||||
assert!(paths.contains(&root.join("app/target/classes")), "{cp}");
|
||||
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{cp}");
|
||||
}
|
||||
|
||||
/// A launch uses runtime dependencies, while tests additionally see test-scope ones.
|
||||
/// Launches request Maven's matching scope without adding reactor test outputs.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn launch_module_classpath_uses_the_matching_dependency_scope() {
|
||||
@@ -465,15 +485,29 @@ mod tests {
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
&script,
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\npl='.'\nwhile [ $# -gt 0 ]; do\nif [ \"$1\" = \"-pl\" ]; then pl=\"$2\"; shift 2; else shift; fi\ndone\nmkdir -p \"$pl/target\"\nprintf '/repo/runtime.jar:/repo/test.jar' > \"$pl/target/ide-compile-cp.txt\"\n",
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\npl='.'\nwhile [ $# -gt 0 ]; do\nif [ \"$1\" = \"-pl\" ]; then pl=\"$2\"; shift 2; else shift; fi\ndone\nmkdir -p \"$pl/target\"\nprintf '/repo/runtime.jar:/repo/fixture-tests.jar:/repo/fixture/target/test-classes' > \"$pl/target/ide-compile-cp.txt\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
|
||||
for dir in
|
||||
["app/target/classes", "app/target/test-classes", "lib/target/test-classes", "shared/target/test-classes"]
|
||||
{
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
let cache = root.join("cache");
|
||||
let runtime =
|
||||
module_classpath(root, &model, &root.join("app"), false, None, &cache, &CancellationToken::new()).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&runtime).collect();
|
||||
assert!(paths.contains(&root.join("app/target/classes")), "{runtime}");
|
||||
assert!(paths.contains(&root.join("lib/target/classes")), "{runtime}");
|
||||
assert!(!paths.contains(&root.join("app/target/test-classes")), "{runtime}");
|
||||
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{runtime}");
|
||||
assert!(paths.contains(&root.join("shared/target/classes")), "{runtime}");
|
||||
assert!(!paths.contains(&root.join("shared/target/test-classes")), "{runtime}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/fixture-tests.jar")), "{runtime}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/fixture/target/test-classes")), "{runtime}");
|
||||
assert!(runtime.contains("/repo/runtime.jar"), "{runtime}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "compile"), "{args}");
|
||||
@@ -482,7 +516,15 @@ mod tests {
|
||||
|
||||
let test =
|
||||
module_classpath(root, &model, &root.join("app"), true, None, &cache, &CancellationToken::new()).unwrap();
|
||||
assert!(test.contains("/repo/test.jar"), "{test}");
|
||||
assert!(test.contains("/repo/fixture-tests.jar"), "{test}");
|
||||
let paths: Vec<_> = std::env::split_paths(&test).collect();
|
||||
assert!(paths.contains(&root.join("app/target/test-classes")), "{test}");
|
||||
assert!(paths.contains(&root.join("app/target/classes")), "{test}");
|
||||
assert!(paths.contains(&root.join("lib/target/classes")), "{test}");
|
||||
assert!(!paths.contains(&root.join("lib/target/test-classes")), "{test}");
|
||||
assert!(paths.contains(&root.join("shared/target/classes")), "{test}");
|
||||
assert!(!paths.contains(&root.join("shared/target/test-classes")), "{test}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/fixture/target/test-classes")), "{test}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
|
||||
}
|
||||
@@ -491,7 +533,7 @@ mod tests {
|
||||
/// build input changes; the probe does not run packaging plugins.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn launch_classpath_cache_follows_the_runner_jdk() {
|
||||
fn launch_classpath_cache_follows_the_runner_jdk_and_format() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -513,6 +555,7 @@ mod tests {
|
||||
fs::write(home.join("release"), format!("JAVA_VERSION=\"{version}\"\n")).unwrap();
|
||||
fs::write(home.join("bin/java"), "").unwrap();
|
||||
}
|
||||
fs::create_dir_all(root.join("app/target/classes")).unwrap();
|
||||
let cache = root.join("classpath-cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let jdk21 = root.join("jdk21");
|
||||
@@ -526,6 +569,30 @@ mod tests {
|
||||
assert_eq!(second, first);
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), "x");
|
||||
|
||||
let record = classpath_cache_path(root, &cache, &root.join("app"), false).unwrap();
|
||||
let current: serde_json::Value = serde_json::from_slice(&fs::read(&record).unwrap()).unwrap();
|
||||
let test_output = root.join("lib/target/test-classes");
|
||||
fs::create_dir_all(&test_output).unwrap();
|
||||
let polluted = std::env::join_paths(std::env::split_paths(&first).chain([test_output])).unwrap();
|
||||
let mut calls = "x".to_owned();
|
||||
for version in [None, Some(0), Some(u32::MAX)] {
|
||||
let mut stale = current.clone();
|
||||
stale["classpath"] = polluted.to_string_lossy().as_ref().into();
|
||||
if let Some(version) = version {
|
||||
stale["version"] = version.into();
|
||||
} else {
|
||||
stale.as_object_mut().unwrap().remove("version");
|
||||
}
|
||||
fs::write(&record, serde_json::to_vec(&stale).unwrap()).unwrap();
|
||||
let rebuilt = module_classpath(root, &model, &root.join("app"), false, None, &cache, &cancel).unwrap();
|
||||
assert_eq!(rebuilt, first, "incompatible cache format {version:?} must be rebuilt");
|
||||
calls.push('x');
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
|
||||
let reused = module_classpath(root, &model, &root.join("app"), false, None, &cache, &cancel).unwrap();
|
||||
assert_eq!(reused, rebuilt);
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
|
||||
}
|
||||
|
||||
let jdk8 = root.join("jdk8");
|
||||
for project in &mut model.maven.as_mut().unwrap().projects {
|
||||
project.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned());
|
||||
@@ -533,6 +600,7 @@ mod tests {
|
||||
let switched = module_classpath(root, &model, &root.join("app"), false, None, &cache, &cancel).unwrap();
|
||||
assert!(switched.contains("jdk8/classpath/jdk.jar"), "{switched}");
|
||||
assert!(!switched.contains("jdk21/classpath/jdk.jar"), "{switched}");
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), "xx");
|
||||
calls.push('x');
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls);
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,19 @@ pub enum IdeEvent {
|
||||
server: ServerId,
|
||||
kind: LspRefreshKind,
|
||||
},
|
||||
/// A language server asked the user to choose an action, e.g. Dart's
|
||||
/// "Renamed field will be invisible in …" warning during a rename. Answered
|
||||
/// with `lsp_message_request_answer`; the server cancels if we reply null.
|
||||
LspMessageRequest {
|
||||
id: u32,
|
||||
server: String,
|
||||
message: String,
|
||||
actions: Vec<String>,
|
||||
},
|
||||
/// The request was answered or timed out; every window drops its dialog.
|
||||
LspMessageRequestDone {
|
||||
id: u32,
|
||||
},
|
||||
TerminalExited {
|
||||
terminal: TerminalId,
|
||||
code: Option<i32>,
|
||||
|
||||
@@ -135,6 +135,8 @@ pub struct CommitSettings {
|
||||
/// `Settings::default()`, or `SettingsStore::set` rejects the key as unknown.
|
||||
#[specta(optional)]
|
||||
pub double_click_opens_diff: Option<bool>,
|
||||
/// Team conventions for Generate Commit Message with Agent, added to its prompt.
|
||||
pub agent_instructions: String,
|
||||
}
|
||||
|
||||
impl Default for CommitSettings {
|
||||
@@ -156,6 +158,7 @@ impl Default for CommitSettings {
|
||||
wrap_at_margin: false,
|
||||
disabled_plugin_checks: Vec::new(),
|
||||
double_click_opens_diff: None,
|
||||
agent_instructions: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +142,7 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
|
||||
}
|
||||
const FMT: &str = "{{json .}}";
|
||||
let (containers, images, volumes, networks) = std::thread::scope(|s| {
|
||||
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", FMT], QUICK));
|
||||
let c = s.spawn(|| run(ep, &["ps", "--all", "--no-trunc", "--format", PS_FORMAT], QUICK));
|
||||
let i = s.spawn(|| run(ep, &["image", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
let v = s.spawn(|| run(ep, &["volume", "ls", "--format", FMT], QUICK));
|
||||
let n = s.spawn(|| run(ep, &["network", "ls", "--no-trunc", "--format", FMT], QUICK));
|
||||
|
||||
@@ -226,6 +226,16 @@ fn lines<T: for<'de> Deserialize<'de>>(text: &str) -> impl Iterator<Item = T> +
|
||||
})
|
||||
}
|
||||
|
||||
/// The `docker ps --format` template: only the fields [`RawContainer`] reads. `{{json .}}`
|
||||
/// would also include `Size`, which makes the daemon compute every container's writable
|
||||
/// layer and can take tens of seconds.
|
||||
pub const PS_FORMAT: &str = concat!(
|
||||
r#"{"ID":{{json .ID}},"Names":{{json .Names}},"Image":{{json .Image}},"#,
|
||||
r#""Command":{{json .Command}},"State":{{json .State}},"Status":{{json .Status}},"#,
|
||||
r#""Ports":{{json .Ports}},"CreatedAt":{{json .CreatedAt}},"Labels":{{json .Labels}},"#,
|
||||
r#""Mounts":{{json .Mounts}},"Networks":{{json .Networks}}}"#,
|
||||
);
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawContainer {
|
||||
@@ -247,7 +257,7 @@ fn split_csv(raw: &str) -> Vec<String> {
|
||||
raw.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
/// `docker ps -a --no-trunc --format '{{json .}}'`.
|
||||
/// `docker ps -a --no-trunc --format` [`PS_FORMAT`] (or `'{{json .}}'`).
|
||||
pub fn parse_containers(text: &str) -> Vec<DockerContainer> {
|
||||
let mut out: Vec<DockerContainer> = lines::<RawContainer>(text)
|
||||
.map(|r| {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Parsing of recorded `docker … --format '{{json .}}'` output.
|
||||
|
||||
use ide_docker::{
|
||||
parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images, parse_networks,
|
||||
parse_volumes,
|
||||
PS_FORMAT, parse_container_stats, parse_container_top, parse_containers, parse_image_history, parse_images,
|
||||
parse_networks, parse_volumes,
|
||||
};
|
||||
|
||||
const PS: &str = include_str!("fixtures/ps.jsonl");
|
||||
@@ -10,6 +10,27 @@ const IMAGES: &str = include_str!("fixtures/images.jsonl");
|
||||
const VOLUMES: &str = include_str!("fixtures/volumes.jsonl");
|
||||
const NETWORKS: &str = include_str!("fixtures/networks.jsonl");
|
||||
|
||||
/// Fills `{{json .Field}}` placeholders of a `--format` template from a `{{json .}}` line.
|
||||
fn render(template: &str, line: &str) -> String {
|
||||
let fields: serde_json::Map<String, serde_json::Value> = serde_json::from_str(line).unwrap();
|
||||
let mut out = template.to_owned();
|
||||
while let Some(start) = out.find("{{json .") {
|
||||
let end = start + out[start..].find("}}").unwrap() + 2;
|
||||
let key = &out[start + "{{json .".len()..end - 2];
|
||||
let value = fields.get(key).unwrap_or_else(|| panic!("fixture lacks {key}"));
|
||||
out.replace_range(start..end, &value.to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ps_format_carries_everything_the_parser_reads_but_size() {
|
||||
assert!(!PS_FORMAT.contains("Size"), "Size makes the daemon compute container sizes");
|
||||
let rendered: Vec<String> = PS.lines().filter(|l| l.starts_with('{')).map(|l| render(PS_FORMAT, l)).collect();
|
||||
assert_eq!(rendered.len(), 2);
|
||||
assert_eq!(parse_containers(&rendered.join("\n")), parse_containers(PS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn containers_with_compose_labels() {
|
||||
let c = parse_containers(PS);
|
||||
|
||||
@@ -886,12 +886,19 @@ pub async fn build_run(
|
||||
for (path, items) in compile::diagnostics(&result.messages) {
|
||||
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
|
||||
}
|
||||
Ok(result)
|
||||
Ok::<_, IdeError>(result)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
result?
|
||||
let outcome = result??;
|
||||
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
|
||||
// folders the build wrote are attached. An up-to-date build skips Maven and
|
||||
// still needs this: the classes can already be on disk.
|
||||
if outcome.system == ide_build::compile::BuildSystem::Maven {
|
||||
project.lsp.sync_maven_generated_sources(&project.root).await;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Build › Compile File: compiles one Java source of a linked Maven module with
|
||||
@@ -928,12 +935,16 @@ pub async fn build_compile_file(
|
||||
for (path, items) in compile::diagnostics(&result.messages) {
|
||||
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
|
||||
}
|
||||
Ok(result)
|
||||
Ok::<_, IdeError>(result)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
result?
|
||||
let outcome = result??;
|
||||
if outcome.system == ide_build::compile::BuildSystem::Maven {
|
||||
project.lsp.sync_maven_generated_sources(&project.root).await;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1710,6 +1710,14 @@ pub fn lsp_servers(host: &Host, window: &str) -> IdeResult<Vec<ServerInfo>> {
|
||||
Ok(host.project(window)?.lsp.servers())
|
||||
}
|
||||
|
||||
/// Answers a server's `window/showMessageRequest` question (`null`: dismissed). It runs where the
|
||||
/// language server runs: the question waits in that process, a remote project's server included.
|
||||
#[command(trust = trusted)]
|
||||
pub fn lsp_message_request_answer(id: u32, choice: Option<String>) -> IdeResult<()> {
|
||||
ide_lsp::answer_message_request(id, choice);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-emits the language servers' current diagnostics (the UI loaded after they arrived).
|
||||
#[command(trust = always)]
|
||||
pub fn lsp_resend_diagnostics(host: &Host, window: &str) -> IdeResult<()> {
|
||||
@@ -2776,6 +2784,7 @@ ide_command::domain!(
|
||||
lsp_java_move_destinations,
|
||||
lsp_java_source_types,
|
||||
lsp_library_sources,
|
||||
lsp_message_request_answer,
|
||||
lsp_prepare_rename,
|
||||
lsp_prepare_type_hierarchy,
|
||||
lsp_references,
|
||||
|
||||
@@ -33,10 +33,10 @@ struct Decl {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Agent {
|
||||
pub(super) struct Agent {
|
||||
/// The jar, resolved inside the package.
|
||||
jar: PathBuf,
|
||||
args: Option<String>,
|
||||
pub(super) jar: PathBuf,
|
||||
pub(super) args: Option<String>,
|
||||
}
|
||||
|
||||
/// Agents of enabled plugins.
|
||||
@@ -47,6 +47,10 @@ pub struct JavaAgents {
|
||||
}
|
||||
|
||||
impl JavaAgents {
|
||||
pub(super) fn for_plugin(&self, plugin: &str) -> Option<Agent> {
|
||||
self.items.read().iter().find(|(_, id, _)| id == plugin).map(|(_, _, agent)| agent.clone())
|
||||
}
|
||||
|
||||
fn add(self: &Arc<Self>, plugin: String, agent: Agent) -> Disposable {
|
||||
let seq = self.seq.fetch_add(1, Ordering::Relaxed);
|
||||
self.items.write().push((seq, plugin, agent));
|
||||
|
||||
@@ -3087,6 +3087,26 @@ impl PluginHost {
|
||||
homepage: m.homepage.clone(),
|
||||
change_notes: m.change_notes.clone(),
|
||||
icon: p.icon.clone(),
|
||||
java_agent: self.java_agents.for_plugin(&m.id).map(|agent| {
|
||||
let pin = self
|
||||
.ledger
|
||||
.lock()
|
||||
.get(&p.subject())
|
||||
.filter(|grant| grant.has(&Capability::JavaAgent))
|
||||
.and_then(|grant| grant.binaries.get(&Capability::JavaAgent.to_string()).cloned());
|
||||
let approved = pin.as_ref().is_some_and(|pin| {
|
||||
pin.path == agent.jar && ledger::file_hash(&pin.path).is_ok_and(|hash| hash == pin.hash)
|
||||
});
|
||||
PluginJavaAgent {
|
||||
file_name: agent
|
||||
.jar
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| agent.jar.display().to_string()),
|
||||
args: agent.args,
|
||||
approved,
|
||||
}
|
||||
}),
|
||||
source: p.source,
|
||||
path: p.dir().to_path_buf().into(),
|
||||
enabled: !self.state.lock().disabled.contains(&m.id),
|
||||
|
||||
@@ -55,6 +55,18 @@ impl PluginStatus {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Java agent a plugin contributes, for Settings › Plugins.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginJavaAgent {
|
||||
/// The jar's file name.
|
||||
pub file_name: String,
|
||||
/// The optional argument passed after `=`.
|
||||
pub args: Option<String>,
|
||||
/// The jar still has the hash recorded when `java.agent` was granted.
|
||||
pub approved: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PluginInfo {
|
||||
@@ -66,6 +78,8 @@ pub struct PluginInfo {
|
||||
pub homepage: Option<String>,
|
||||
pub change_notes: Option<String>,
|
||||
pub icon: Option<PluginIcon>,
|
||||
/// The Java agent this plugin declares, and whether it is still approved.
|
||||
pub java_agent: Option<PluginJavaAgent>,
|
||||
pub source: PluginSource,
|
||||
/// Package directory.
|
||||
pub path: ide_core::IpcPath,
|
||||
|
||||
@@ -198,6 +198,8 @@ pub fn client_accepts(event: &IdeEvent) -> bool {
|
||||
| IdeEvent::LanguageServerWarning { .. }
|
||||
| IdeEvent::LanguageServerRemoved { .. }
|
||||
| IdeEvent::LspRefresh { .. }
|
||||
| IdeEvent::LspMessageRequest { .. }
|
||||
| IdeEvent::LspMessageRequestDone { .. }
|
||||
| IdeEvent::TerminalExited { .. }
|
||||
| IdeEvent::RunExited { .. }
|
||||
| IdeEvent::Debug { .. }
|
||||
|
||||
@@ -2204,6 +2204,10 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
|
||||
let info = f.host.install_from_dir(&pkg, &Consent::default()).unwrap();
|
||||
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
|
||||
assert!(info.contributions.iter().any(|c| c.point == "javaAgents" && c.label == "fixture agent.jar=mode=test"));
|
||||
let agent = info.java_agent.clone().expect("agent metadata");
|
||||
assert_eq!(agent.file_name, "fixture agent.jar");
|
||||
assert_eq!(agent.args.as_deref(), Some("mode=test"));
|
||||
assert!(!agent.approved);
|
||||
let source = f.host.java_agents();
|
||||
let launch = || {
|
||||
let agents = ide_run::java_agent::approved(&source.agents());
|
||||
@@ -2217,6 +2221,7 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
|
||||
// Granted: the installed jar with its arguments, one argument after the VM options.
|
||||
let info = f.host.set_capability("java-agent", "java.agent", true).unwrap();
|
||||
assert!(info.capabilities.iter().any(|c| c.id == "java.agent" && c.granted));
|
||||
assert!(info.java_agent.as_ref().is_some_and(|agent| agent.approved));
|
||||
let jar = dunce::canonicalize(f.installed("java-agent").join("agent/fixture agent.jar")).unwrap();
|
||||
let option = format!("-javaagent:{}=mode=test", jar.display());
|
||||
let mut with_agent = plain.clone();
|
||||
@@ -2228,7 +2233,11 @@ fn java_agent_loads_only_while_granted_and_unchanged() {
|
||||
let (args, notes) = launch();
|
||||
assert_eq!(args, plain);
|
||||
assert!(notes.len() == 1 && notes[0].contains("changed since it was approved"), "{notes:?}");
|
||||
let changed = f.host.info_of("java-agent").unwrap();
|
||||
assert!(!changed.java_agent.as_ref().unwrap().approved, "Settings must show the changed jar");
|
||||
f.host.set_capability("java-agent", "java.agent", false).unwrap();
|
||||
f.host.set_capability("java-agent", "java.agent", true).unwrap();
|
||||
assert!(f.host.info_of("java-agent").unwrap().java_agent.as_ref().is_some_and(|a| a.approved));
|
||||
assert_eq!(launch(), (with_agent.clone(), vec![]));
|
||||
|
||||
// Revoked, then the plugin disabled: no agent either way.
|
||||
|
||||
@@ -68,7 +68,7 @@ pub(crate) struct Shared {
|
||||
pub store: Option<Store>,
|
||||
pub indexing: AtomicBool,
|
||||
pub cancelled: AtomicBool,
|
||||
/// Files whose content was (re)read and parsed; observability for tests.
|
||||
/// Non-cached content reads, including binary/unsupported files; used by tests.
|
||||
pub parsed: std::sync::atomic::AtomicUsize,
|
||||
queue: Mutex<Queue>,
|
||||
wake: Condvar,
|
||||
@@ -160,14 +160,38 @@ impl Shared {
|
||||
q.busy = true;
|
||||
}
|
||||
if scan {
|
||||
let startup_started = Instant::now();
|
||||
// A warm start can trust the snapshot when neither the scope nor any
|
||||
// directory/file metadata changed. Rebuilding the walk's file list is
|
||||
// the expensive part; validate the flat manifest first.
|
||||
if !self.try_fast_start() {
|
||||
let snapshot_started = Instant::now();
|
||||
let fast = self.try_fast_start();
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
if !fast {
|
||||
let snapshot_guard = SystemTime::now();
|
||||
let walk_started = Instant::now();
|
||||
let found = self.walk_roots(None);
|
||||
let walk_elapsed = walk_started.elapsed();
|
||||
let hydration_started = Instant::now();
|
||||
self.load_persisted(&found);
|
||||
let hydration_elapsed = hydration_started.elapsed();
|
||||
self.full_scan(Some(found), snapshot_guard);
|
||||
if !self.is_cancelled() {
|
||||
tracing::info!(
|
||||
mode = "fallback",
|
||||
snapshot_attempt_ms = snapshot_elapsed.as_millis() as u64,
|
||||
walk_ms = walk_elapsed.as_millis() as u64,
|
||||
hydration_ms = hydration_elapsed.as_millis() as u64,
|
||||
elapsed_ms = startup_started.elapsed().as_millis() as u64,
|
||||
"index startup completed"
|
||||
);
|
||||
}
|
||||
} else if !self.is_cancelled() {
|
||||
tracing::info!(
|
||||
mode = "snapshot",
|
||||
elapsed_ms = startup_started.elapsed().as_millis() as u64,
|
||||
"index startup completed"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
@@ -234,6 +258,7 @@ impl Shared {
|
||||
return false;
|
||||
}
|
||||
let root = filter.root();
|
||||
let validation_started = Instant::now();
|
||||
for i in 0..snapshot.dirs_len() {
|
||||
let rel = snapshot.dir(i);
|
||||
let path = if rel.is_empty() { root.to_owned() } else { root.join(rel) };
|
||||
@@ -265,6 +290,7 @@ impl Shared {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let validation_elapsed = validation_started.elapsed();
|
||||
let build_started = Instant::now();
|
||||
let entries: Vec<Option<(FileEntry, Vec<StoredSymbol>)>> = INDEX_POOL.install(|| {
|
||||
(0..snapshot.len())
|
||||
@@ -302,9 +328,16 @@ impl Shared {
|
||||
d.load_bulk(entries, dirs);
|
||||
drop(d);
|
||||
tracing::info!(
|
||||
"index snapshot: warm start in {:?} (load {loaded:?}, validate/build {built:?}, insert {:?})",
|
||||
started.elapsed(),
|
||||
insert_started.elapsed()
|
||||
mode = "snapshot",
|
||||
snapshot_hydrated = snapshot.len(),
|
||||
discovered = 0usize,
|
||||
symbol_extractions = 0usize,
|
||||
load_ms = loaded.as_millis() as u64,
|
||||
directory_validation_ms = validation_elapsed.as_millis() as u64,
|
||||
file_validation_build_ms = built.as_millis() as u64,
|
||||
insert_ms = insert_started.elapsed().as_millis() as u64,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"index snapshot hydrated"
|
||||
);
|
||||
#[cfg(test)]
|
||||
eprintln!(
|
||||
@@ -441,7 +474,7 @@ impl Shared {
|
||||
self.scan(None, found, guard);
|
||||
}
|
||||
|
||||
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) {
|
||||
fn scan(&self, dirs: Option<&[PathBuf]>, prewalked: Option<Vec<Found>>, guard: SystemTime) -> Option<ScanCounts> {
|
||||
let started = Instant::now();
|
||||
self.indexing.store(true, Ordering::SeqCst);
|
||||
self.emit_state();
|
||||
@@ -457,10 +490,12 @@ impl Shared {
|
||||
|
||||
let filter = self.filter();
|
||||
let walk_started = Instant::now();
|
||||
let was_prewalked = prewalked.is_some();
|
||||
let found = prewalked.unwrap_or_else(|| self.walk_roots(dirs));
|
||||
let walk = walk_started.elapsed();
|
||||
if self.is_cancelled() {
|
||||
return self.end_scan(task);
|
||||
self.end_scan(task);
|
||||
return None;
|
||||
}
|
||||
let classify_started = Instant::now();
|
||||
let seen: HashSet<&Path> = found.iter().map(|f| f.path.as_path()).collect();
|
||||
@@ -487,6 +522,7 @@ impl Shared {
|
||||
self.persist(&[], &stale, false);
|
||||
|
||||
let total = todo.len();
|
||||
let update_started = Instant::now();
|
||||
let mut laps = ChunkLaps::default();
|
||||
{
|
||||
// One streaming parallel pass: parse on `INDEX_POOL` without
|
||||
@@ -546,11 +582,14 @@ impl Shared {
|
||||
laps.extract = pass_started.elapsed();
|
||||
}
|
||||
if self.is_cancelled() {
|
||||
return self.end_scan(task);
|
||||
self.end_scan(task);
|
||||
return None;
|
||||
}
|
||||
let durable_started = Instant::now();
|
||||
self.persist(&[], &[], true);
|
||||
let durable = durable_started.elapsed();
|
||||
let update_elapsed = update_started.elapsed();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Some(store) = &self.store {
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let d = self.data.read();
|
||||
@@ -563,6 +602,7 @@ impl Shared {
|
||||
tracing::warn!("index recent snapshot: {e}");
|
||||
}
|
||||
}
|
||||
let snapshot_elapsed = snapshot_started.elapsed();
|
||||
*self.snapshot_due.lock() = None;
|
||||
self.indexing.store(false, Ordering::SeqCst);
|
||||
self.sink.emit(IdeEvent::Task {
|
||||
@@ -574,20 +614,47 @@ impl Shared {
|
||||
cancellable: false,
|
||||
});
|
||||
self.emit_state();
|
||||
if self.is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
laps.outcomes.not_processed += total - laps.outcomes.total();
|
||||
let counts = ScanCounts {
|
||||
discovered: found.len(),
|
||||
metadata_reused: found.len() - total,
|
||||
scheduled: total,
|
||||
outcomes: laps.outcomes,
|
||||
};
|
||||
let outcomes = &counts.outcomes;
|
||||
let d = self.data.read();
|
||||
tracing::info!(
|
||||
"indexed {} files ({} parsed, {} symbols) in {:?} (walk {:?}, classify {:?}, extract {:?}, insert {:?}, persist {:?}, durable {:?})",
|
||||
d.file_count,
|
||||
total,
|
||||
d.symbol_count,
|
||||
started.elapsed(),
|
||||
walk,
|
||||
classify,
|
||||
laps.extract,
|
||||
laps.insert,
|
||||
laps.persist,
|
||||
durable
|
||||
scope = if dirs.is_some() { "subtree" } else { "full" },
|
||||
files = d.file_count,
|
||||
symbols = d.symbol_count,
|
||||
discovered = counts.discovered,
|
||||
metadata_reused = counts.metadata_reused,
|
||||
scheduled = counts.scheduled,
|
||||
hash_reused = outcomes.hash_reused,
|
||||
symbol_extractions = outcomes.symbol_extractions,
|
||||
ignored = outcomes.ignored,
|
||||
oversized = outcomes.oversized,
|
||||
binary = outcomes.binary,
|
||||
unsupported = outcomes.unsupported,
|
||||
read_failed = outcomes.read_failed,
|
||||
not_processed = outcomes.not_processed,
|
||||
prewalked = was_prewalked,
|
||||
walk_ms = walk.as_millis() as u64,
|
||||
classify_ms = classify.as_millis() as u64,
|
||||
// Pipeline and update wall times overlap insert/persist; do not sum these fields.
|
||||
extract_pipeline_ms = laps.extract.as_millis() as u64,
|
||||
insert_ms = laps.insert.as_millis() as u64,
|
||||
persist_ms = laps.persist.as_millis() as u64,
|
||||
durable_ms = durable.as_millis() as u64,
|
||||
update_ms = update_elapsed.as_millis() as u64,
|
||||
snapshot_write_ms = snapshot_elapsed.as_millis() as u64,
|
||||
elapsed_ms = started.elapsed().as_millis() as u64,
|
||||
"index scan completed"
|
||||
);
|
||||
Some(counts)
|
||||
}
|
||||
|
||||
/// Extracts records in parallel, then publishes them to memory and disk.
|
||||
@@ -599,6 +666,7 @@ impl Shared {
|
||||
files.par_iter().filter_map(|(f, prev_hash)| self.parse_found(f, *prev_hash, &filter)).collect()
|
||||
});
|
||||
laps.extract = started.elapsed();
|
||||
laps.outcomes.not_processed = files.len() - extracted.len();
|
||||
if extracted.is_empty() {
|
||||
return laps;
|
||||
}
|
||||
@@ -622,9 +690,9 @@ impl Shared {
|
||||
let key = filter.store_key(&f.path);
|
||||
let outcome = match self.extract(f, prev_hash) {
|
||||
Extracted::Unchanged => ParsedOutcome::Unchanged { mtime: f.mtime, size: f.size, ignored: f.ignored },
|
||||
Extracted::New(rec) => {
|
||||
Extracted::New(rec, extraction) => {
|
||||
let bytes = key.as_ref().and_then(|_| postcard::to_allocvec(&rec).ok());
|
||||
ParsedOutcome::New { rec, bytes }
|
||||
ParsedOutcome::New { rec, bytes, extraction }
|
||||
}
|
||||
};
|
||||
Some(ParsedFile { rel, key, outcome, path: f.path.clone() })
|
||||
@@ -640,7 +708,8 @@ impl Shared {
|
||||
for out in batch {
|
||||
let ParsedFile { rel, key, outcome, path } = out;
|
||||
match outcome {
|
||||
ParsedOutcome::New { rec, bytes } => {
|
||||
ParsedOutcome::New { rec, bytes, extraction } => {
|
||||
laps.outcomes.record(extraction);
|
||||
if let (Some(key), Some(bytes)) = (key, bytes) {
|
||||
puts.push((key, bytes));
|
||||
}
|
||||
@@ -658,10 +727,13 @@ impl Shared {
|
||||
d.insert(e, symbols);
|
||||
}
|
||||
for r in refreshes {
|
||||
if let Some(rec) = d.refresh_metadata(&r.path, r.mtime, r.size, r.ignored)
|
||||
&& let Some(key) = r.key
|
||||
{
|
||||
refreshed_records.push((key, rec));
|
||||
if let Some(rec) = d.refresh_metadata(&r.path, r.mtime, r.size, r.ignored) {
|
||||
laps.outcomes.record(Extraction::HashReused);
|
||||
if let Some(key) = r.key {
|
||||
refreshed_records.push((key, rec));
|
||||
}
|
||||
} else {
|
||||
laps.outcomes.not_processed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -726,15 +798,18 @@ impl Shared {
|
||||
|
||||
fn extract(&self, f: &Found, prev_hash: Option<[u8; 32]>) -> Extracted {
|
||||
let mut rec = FileRecord { mtime: f.mtime, size: f.size, ignored: f.ignored, ..Default::default() };
|
||||
if f.ignored || f.size > MAX_SYMBOL_FILE {
|
||||
return Extracted::New(rec);
|
||||
if f.ignored {
|
||||
return Extracted::New(rec, Extraction::Ignored);
|
||||
}
|
||||
if f.size > MAX_SYMBOL_FILE {
|
||||
return Extracted::New(rec, Extraction::Oversized);
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(f.size as usize);
|
||||
match std::fs::File::open(&f.path).and_then(|mut file| file.read_to_end(&mut bytes)) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
tracing::debug!("index: cannot read {}: {e}", f.path.display());
|
||||
return Extracted::New(rec);
|
||||
return Extracted::New(rec, Extraction::ReadFailed);
|
||||
}
|
||||
}
|
||||
rec.hash = *blake3::hash(&bytes).as_bytes();
|
||||
@@ -743,7 +818,7 @@ impl Shared {
|
||||
}
|
||||
self.parsed.fetch_add(1, Ordering::Relaxed);
|
||||
if bytes[..bytes.len().min(8192)].contains(&0) {
|
||||
return Extracted::New(rec);
|
||||
return Extracted::New(rec, Extraction::Binary);
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
let lang = self.languages.detect(&f.path, Some(first_line(&text)));
|
||||
@@ -760,8 +835,9 @@ impl Shared {
|
||||
bases: t.bases,
|
||||
})
|
||||
.collect();
|
||||
return Extracted::New(rec, Extraction::Symbols);
|
||||
}
|
||||
Extracted::New(rec)
|
||||
Extracted::New(rec, Extraction::Unsupported)
|
||||
}
|
||||
|
||||
fn process(&self, jobs: Vec<Job>) {
|
||||
@@ -938,7 +1014,7 @@ fn first_line(text: &str) -> &str {
|
||||
enum Extracted {
|
||||
/// Content hash matches the indexed version.
|
||||
Unchanged,
|
||||
New(FileRecord),
|
||||
New(FileRecord, Extraction),
|
||||
}
|
||||
|
||||
/// Wall-time laps of one `index_files` chunk, accumulated by the scan.
|
||||
@@ -947,6 +1023,7 @@ struct ChunkLaps {
|
||||
extract: Duration,
|
||||
insert: Duration,
|
||||
persist: Duration,
|
||||
outcomes: ExtractionCounts,
|
||||
}
|
||||
|
||||
impl ChunkLaps {
|
||||
@@ -954,6 +1031,7 @@ impl ChunkLaps {
|
||||
self.extract += other.extract;
|
||||
self.insert += other.insert;
|
||||
self.persist += other.persist;
|
||||
self.outcomes.add(other.outcomes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -967,7 +1045,7 @@ struct MetadataRefresh {
|
||||
|
||||
enum ParsedOutcome {
|
||||
Unchanged { mtime: u64, size: u64, ignored: bool },
|
||||
New { rec: FileRecord, bytes: Option<Vec<u8>> },
|
||||
New { rec: FileRecord, bytes: Option<Vec<u8>>, extraction: Extraction },
|
||||
}
|
||||
|
||||
/// One file parsed off the index thread: its outcome ready to publish, with new
|
||||
@@ -980,6 +1058,356 @@ struct ParsedFile {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
/// Mutually exclusive outcomes for this batch, not all files in the index. "Symbols"
|
||||
/// means tags() was called, even when no symbols were found.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Extraction {
|
||||
HashReused,
|
||||
Symbols,
|
||||
Ignored,
|
||||
Oversized,
|
||||
Binary,
|
||||
Unsupported,
|
||||
ReadFailed,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, PartialEq, Eq)]
|
||||
struct ExtractionCounts {
|
||||
hash_reused: usize,
|
||||
symbol_extractions: usize,
|
||||
ignored: usize,
|
||||
oversized: usize,
|
||||
binary: usize,
|
||||
unsupported: usize,
|
||||
read_failed: usize,
|
||||
/// Cancellation, a changed root configuration, or a concurrently removed entry.
|
||||
not_processed: usize,
|
||||
}
|
||||
|
||||
impl ExtractionCounts {
|
||||
fn total(&self) -> usize {
|
||||
self.hash_reused
|
||||
+ self.symbol_extractions
|
||||
+ self.ignored
|
||||
+ self.oversized
|
||||
+ self.binary
|
||||
+ self.unsupported
|
||||
+ self.read_failed
|
||||
+ self.not_processed
|
||||
}
|
||||
|
||||
fn record(&mut self, outcome: Extraction) {
|
||||
*match outcome {
|
||||
Extraction::HashReused => &mut self.hash_reused,
|
||||
Extraction::Symbols => &mut self.symbol_extractions,
|
||||
Extraction::Ignored => &mut self.ignored,
|
||||
Extraction::Oversized => &mut self.oversized,
|
||||
Extraction::Binary => &mut self.binary,
|
||||
Extraction::Unsupported => &mut self.unsupported,
|
||||
Extraction::ReadFailed => &mut self.read_failed,
|
||||
} += 1;
|
||||
}
|
||||
|
||||
fn add(&mut self, other: Self) {
|
||||
self.hash_reused += other.hash_reused;
|
||||
self.symbol_extractions += other.symbol_extractions;
|
||||
self.ignored += other.ignored;
|
||||
self.oversized += other.oversized;
|
||||
self.binary += other.binary;
|
||||
self.unsupported += other.unsupported;
|
||||
self.read_failed += other.read_failed;
|
||||
self.not_processed += other.not_processed;
|
||||
}
|
||||
}
|
||||
|
||||
struct ScanCounts {
|
||||
/// Files yielded by the filtered walker, not every file on disk.
|
||||
discovered: usize,
|
||||
/// Metadata matched an in-memory entry (possibly loaded from disk cache).
|
||||
metadata_reused: usize,
|
||||
scheduled: usize,
|
||||
outcomes: ExtractionCounts,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod metric_tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn index_files<'a>(index: &Shared, files: impl Iterator<Item = &'a Found>, force: bool) -> ExtractionCounts {
|
||||
let files: Vec<_> = files
|
||||
.map(|f| {
|
||||
let hash = if force || f.ignored { None } else { index.data.read().get(&f.path).map(|e| e.hash) };
|
||||
(f.clone(), hash)
|
||||
})
|
||||
.collect();
|
||||
index.index_files(&files).outcomes
|
||||
}
|
||||
|
||||
fn shared(root: &Path) -> Shared {
|
||||
Shared::new(
|
||||
PathFilter::new(root, &crate::IndexRoots::from(Vec::new()), &[]),
|
||||
Arc::new(LanguageRegistry::load(None).unwrap()),
|
||||
Arc::new(Syntax::new()),
|
||||
Arc::new(ide_core::NullSink),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_scan_counts_full_batch_and_tail() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
let count = SCAN_BATCH + 3;
|
||||
for i in 0..count {
|
||||
std::fs::write(root.join(format!("file_{i}.unknown")), "plain").unwrap();
|
||||
}
|
||||
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (count, 0, count));
|
||||
assert_eq!(cold.outcomes, ExtractionCounts { unsupported: count, ..Default::default() });
|
||||
assert_eq!(shared.data.read().file_count as usize, count);
|
||||
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (count, count, 0));
|
||||
assert_eq!(hot.outcomes.total(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_entry_is_not_counted_as_hash_reuse() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
let path = root.join("main.rs");
|
||||
std::fs::write(&path, "fn main() {}").unwrap();
|
||||
shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
let (found, hash) = {
|
||||
let data = shared.data.read();
|
||||
let e = data.get(&path).unwrap();
|
||||
(Found { path: path.clone(), mtime: e.mtime, size: e.size, ignored: e.ignored }, e.hash)
|
||||
};
|
||||
let parsed = shared.parse_found(&found, Some(hash), &shared.filter()).unwrap();
|
||||
shared.data.write().remove(&path).unwrap();
|
||||
let counts = shared.publish(std::iter::once(parsed)).outcomes;
|
||||
assert_eq!(counts, ExtractionCounts { not_processed: 1, ..Default::default() });
|
||||
assert_eq!(shared.data.read().file_count, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_distinguishes_cold_metadata_and_hash_reuse() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let path = root.join("main.rs");
|
||||
std::fs::write(&path, "fn main() {}\n").unwrap();
|
||||
let shared = shared(&root);
|
||||
let cold = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((cold.discovered, cold.metadata_reused, cold.scheduled), (1, 0, 1));
|
||||
assert_eq!(cold.outcomes, ExtractionCounts { symbol_extractions: 1, ..Default::default() });
|
||||
let hot = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((hot.discovered, hot.metadata_reused, hot.scheduled), (1, 1, 0));
|
||||
assert_eq!(hot.outcomes, ExtractionCounts::default());
|
||||
// Force a metadata mismatch without a timestamp-resolution-dependent sleep.
|
||||
let mut rec = {
|
||||
let data = shared.data.read();
|
||||
data.record(data.get(&path).unwrap())
|
||||
};
|
||||
rec.mtime = rec.mtime.wrapping_add(1);
|
||||
let (entry, symbols) = FileEntry::new(path.clone(), "main.rs".into(), rec);
|
||||
shared.data.write().insert(entry, symbols);
|
||||
let touched = shared.scan(None, None, SystemTime::now()).unwrap();
|
||||
assert_eq!((touched.discovered, touched.metadata_reused, touched.scheduled), (1, 0, 1));
|
||||
assert_eq!(touched.outcomes, ExtractionCounts { hash_reused: 1, ..Default::default() });
|
||||
assert_eq!(shared.data.read().symbol_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extraction_outcomes_are_exclusive_and_forced_parsing_is_counted() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
let shared = shared(&root);
|
||||
let mut found = Vec::new();
|
||||
for (name, contents, ignored, size) in [
|
||||
("source.rs", "fn source() {}", false, 14),
|
||||
("ignored.rs", "fn hidden() {}", true, 14),
|
||||
("huge.rs", "", false, MAX_SYMBOL_FILE + 1),
|
||||
("binary.rs", "\0", false, 1),
|
||||
("plain.unknown", "plain", false, 5),
|
||||
("missing.rs", "", false, 0),
|
||||
] {
|
||||
let path = root.join(name);
|
||||
if name != "missing.rs" {
|
||||
std::fs::write(&path, contents).unwrap();
|
||||
}
|
||||
found.push(Found { path, mtime: 0, size, ignored });
|
||||
}
|
||||
let counts = index_files(&shared, found.iter(), false);
|
||||
assert_eq!(
|
||||
counts,
|
||||
ExtractionCounts {
|
||||
symbol_extractions: 1,
|
||||
ignored: 1,
|
||||
oversized: 1,
|
||||
binary: 1,
|
||||
unsupported: 1,
|
||||
read_failed: 1,
|
||||
hash_reused: 0,
|
||||
not_processed: 0,
|
||||
}
|
||||
);
|
||||
assert_eq!(shared.data.read().file_count as usize, found.len());
|
||||
assert_eq!(index_files(&shared, found[..1].iter(), false).hash_reused, 1);
|
||||
assert_eq!(index_files(&shared, found[..1].iter(), true).symbol_extractions, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopened_cache_counts_metadata_reuse() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let root = dunce::canonicalize(root).unwrap();
|
||||
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
|
||||
let cache = dir.path().join("cache");
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
let found = index.walk_roots(None);
|
||||
index.load_persisted(&found);
|
||||
let counts = index.scan(None, Some(found), SystemTime::now()).unwrap();
|
||||
assert_eq!((counts.discovered, counts.metadata_reused, counts.scheduled), (1, 1, 0));
|
||||
assert_eq!(counts.outcomes, ExtractionCounts::default());
|
||||
assert_eq!(index.data.read().symbol_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_snapshot_hydrates_without_symbol_extraction() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let root = dunce::canonicalize(root).unwrap();
|
||||
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
|
||||
let cache = dir.path().join("cache");
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert_eq!(index.scan(None, None, SystemTime::now()).unwrap().outcomes.symbol_extractions, 1);
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
assert!(index.try_fast_start());
|
||||
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
assert_eq!(index.data.read().symbol_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_warm_start_does_not_log_completion() {
|
||||
struct CompletionCounter(Arc<std::sync::atomic::AtomicUsize>);
|
||||
impl tracing::Subscriber for CompletionCounter {
|
||||
fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
|
||||
true
|
||||
}
|
||||
fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
|
||||
tracing::span::Id::from_u64(1)
|
||||
}
|
||||
fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
|
||||
fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
|
||||
fn enter(&self, _: &tracing::span::Id) {}
|
||||
fn exit(&self, _: &tracing::span::Id) {}
|
||||
fn event(&self, event: &tracing::Event<'_>) {
|
||||
struct Message(bool);
|
||||
impl tracing::field::Visit for Message {
|
||||
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
|
||||
if field.name() == "message" && format!("{value:?}").contains("index startup completed") {
|
||||
self.0 = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut message = Message(false);
|
||||
event.record(&mut message);
|
||||
if message.0 {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let root = dunce::canonicalize(root).unwrap();
|
||||
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
|
||||
let cache = dir.path().join("cache");
|
||||
{
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
index.scan(None, None, SystemTime::now()).unwrap();
|
||||
}
|
||||
let mut index = shared(&root);
|
||||
index.store = Some(Store::open(&cache, &root, "metrics-test").unwrap());
|
||||
let count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
index.cancel();
|
||||
tracing::subscriber::with_default(CompletionCounter(count.clone()), || {
|
||||
tracing::info!("index startup completed");
|
||||
assert_eq!(count.swap(0, Ordering::Relaxed), 1);
|
||||
index.run(true);
|
||||
});
|
||||
assert_eq!(index.parsed.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
assert_eq!(count.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_outside_current_scope_and_cancelled_batches_are_accounted_for() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let index = shared(&root);
|
||||
// A scan can retain Found values from a root removed by set_scope.
|
||||
let outside = Found { path: dir.path().join("outside.rs"), mtime: 0, size: 0, ignored: false };
|
||||
assert_eq!(
|
||||
index_files(&index, [&outside].into_iter(), false),
|
||||
ExtractionCounts { not_processed: 1, ..Default::default() }
|
||||
);
|
||||
index.cancel();
|
||||
let inside = Found { path: root.join("inside.rs"), mtime: 0, size: 0, ignored: false };
|
||||
assert_eq!(
|
||||
index_files(&index, [&inside].into_iter(), false),
|
||||
ExtractionCounts { not_processed: 1, ..Default::default() }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_during_final_notifications_suppresses_completion() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
std::fs::write(root.join("source.rs"), "fn source() {}").unwrap();
|
||||
let index: Arc<Shared> = Arc::new_cyclic(|weak: &std::sync::Weak<Shared>| {
|
||||
let mut index = shared(&root);
|
||||
let weak = weak.clone();
|
||||
index.sink = Arc::new(move |event| {
|
||||
if matches!(event, IdeEvent::Task { done: true, .. }) {
|
||||
weak.upgrade().unwrap().cancel();
|
||||
}
|
||||
});
|
||||
index
|
||||
});
|
||||
assert!(index.scan(None, None, SystemTime::now()).is_none());
|
||||
assert!(index.is_cancelled());
|
||||
assert!(!index.indexing.load(Ordering::Relaxed));
|
||||
assert_eq!(index.data.read().file_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_scan_does_not_report_completion() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let shared = shared(dir.path());
|
||||
shared.cancel();
|
||||
assert!(shared.scan(None, None, SystemTime::now()).is_none());
|
||||
assert!(!shared.indexing.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::data::safe_rel;
|
||||
|
||||
@@ -981,6 +981,12 @@ fn g() {}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_typescript_import_run_ending_with_multiline_import() {
|
||||
let src = "import { ZodError } from 'zod'\nimport { Library } from './library.js'\nimport {\n CreationIntent,\n} from './creation-assistant.js'\n";
|
||||
assert!(folds("typescript", src).contains(&(0, 4, FoldKind::Imports)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folding_xml_custom_regions() {
|
||||
for (start, end) in [
|
||||
|
||||
@@ -358,6 +358,63 @@ impl ClientHandler {
|
||||
mgr.sink().emit(IdeEvent::Notify { level, title: self.server.name.clone(), body: Some(text) });
|
||||
}
|
||||
|
||||
/// `window/showMessageRequest` expects `MessageActionItem | null`. Showing
|
||||
/// the question as a plain notification and replying null made Dart cancel
|
||||
/// renames with a warning (`Renamed field will be invisible in …`).
|
||||
fn message_request(&self, mgr: &LspManager, params: &Value) -> Result<Value, (i64, String)> {
|
||||
let message = params.get("message").and_then(Value::as_str).unwrap_or_default().to_owned();
|
||||
let actions: Vec<String> = params
|
||||
.get("actions")
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items.iter().filter_map(|item| item.get("title").and_then(Value::as_str).map(str::to_owned)).collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let sink = mgr.sink();
|
||||
let Some((id, answer)) = crate::message_requests::begin() else {
|
||||
tracing::warn!("[{}] too many pending message requests; dismissing", self.server.name);
|
||||
sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Warning,
|
||||
title: self.server.name.clone(),
|
||||
body: Some("Too many open questions; try again".into()),
|
||||
});
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
struct Guard {
|
||||
id: u32,
|
||||
sink: ide_core::SharedSink,
|
||||
}
|
||||
impl Drop for Guard {
|
||||
fn drop(&mut self) {
|
||||
crate::message_requests::close(self.id);
|
||||
self.sink.emit(IdeEvent::LspMessageRequestDone { id: self.id });
|
||||
}
|
||||
}
|
||||
let _guard = Guard { id, sink: sink.clone() };
|
||||
sink.emit(IdeEvent::LspMessageRequest {
|
||||
id,
|
||||
server: self.server.name.clone(),
|
||||
message: message.clone(),
|
||||
actions: actions.clone(),
|
||||
});
|
||||
// Below the IDE's 30 s timeout for the enclosing request (e.g. rename),
|
||||
// so the dialog cannot outlive the operation it is answering.
|
||||
let received = answer.recv_timeout(Duration::from_secs(20));
|
||||
let timed_out = matches!(received, Err(std::sync::mpsc::RecvTimeoutError::Timeout));
|
||||
let chosen = received.ok().flatten();
|
||||
if timed_out {
|
||||
sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Warning,
|
||||
title: self.server.name.clone(),
|
||||
body: Some(format!("No answer in time for: {message}")),
|
||||
});
|
||||
}
|
||||
match chosen.filter(|title| actions.contains(title)) {
|
||||
Some(title) => Ok(json!({ "title": title })),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}
|
||||
|
||||
fn configuration(&self, params: &Value) -> Value {
|
||||
let options = all_settings(&self.server.effective_config());
|
||||
let items = params.get("items").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
@@ -541,10 +598,7 @@ impl Handler for ClientHandler {
|
||||
};
|
||||
match method {
|
||||
"window/workDoneProgress/create" => Ok(Value::Null),
|
||||
"window/showMessageRequest" => {
|
||||
self.show_message(&mgr, ¶ms);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
"window/showMessageRequest" => self.message_request(&mgr, ¶ms),
|
||||
"window/showDocument" => Ok(json!({ "success": false })),
|
||||
"workspace/configuration" => Ok(self.configuration(¶ms)),
|
||||
"workspace/workspaceFolders" => Ok(mgr.workspace_folders(&self.server)),
|
||||
|
||||
@@ -17,10 +17,12 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub(crate) const SERVER: &str = "jdtls";
|
||||
const GENERATED_SOURCES: &str = "openidea.java.generatedSources";
|
||||
|
||||
pub(crate) mod configuration;
|
||||
mod extract_interface;
|
||||
mod formatter;
|
||||
mod generated;
|
||||
mod hierarchy;
|
||||
pub(crate) mod jvm_inspect;
|
||||
mod move_refactoring;
|
||||
@@ -638,6 +640,7 @@ impl LspManager {
|
||||
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
|
||||
/// change, a Maven sync, other Maven profiles), but does not check open documents
|
||||
/// again against the new classpath: their errors would stay until the next edit.
|
||||
/// Generated Maven sources are attached first, so that recheck sees them.
|
||||
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
|
||||
let uris: Vec<String> = self
|
||||
.docs
|
||||
@@ -650,11 +653,10 @@ impl LspManager {
|
||||
})
|
||||
.map(|d| crate::uri::path_to_uri_string(&d.path))
|
||||
.collect();
|
||||
if uris.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mgr = self.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let Some(run) = server.running_gen(generation) else { return };
|
||||
mgr.sync_generated_sources(&server, &run).await;
|
||||
for uri in uris {
|
||||
let params =
|
||||
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
|
||||
@@ -668,6 +670,49 @@ impl LspManager {
|
||||
});
|
||||
}
|
||||
|
||||
/// Puts Maven plugin output that already exists on disk (`target/generated-sources/...`)
|
||||
/// onto the jdtls classpath. Best-effort: only a jdtls that is already running is
|
||||
/// touched, so a Maven build does not start the language server by itself.
|
||||
pub async fn sync_maven_generated_sources(&self, root: &Path) {
|
||||
let servers: Vec<_> = self
|
||||
.servers
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|server| server.name == SERVER && server.running().is_some())
|
||||
.filter(|server| server.root == root || root.starts_with(&server.root) || server.root.starts_with(root))
|
||||
.cloned()
|
||||
.collect();
|
||||
for server in servers {
|
||||
let Some(run) = server.running() else { continue };
|
||||
self.sync_generated_sources(&server, &run).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn sync_generated_sources(&self, server: &Arc<Server>, run: &Running) {
|
||||
if !run.caps.read().commands().iter().any(|command| command == GENERATED_SOURCES) {
|
||||
return;
|
||||
}
|
||||
let root = server.root.clone();
|
||||
let scan = tokio::task::spawn_blocking(move || generated::scan(&root))
|
||||
.await
|
||||
.unwrap_or(generated::GeneratedScan { maven: false, roots: Vec::new() });
|
||||
if !scan.maven {
|
||||
return;
|
||||
}
|
||||
let arguments: Vec<Value> = scan
|
||||
.roots
|
||||
.into_iter()
|
||||
.map(|root| json!({ "path": root.path.to_string_lossy(), "test": root.test }))
|
||||
.collect();
|
||||
let params = json!({ "command": GENERATED_SOURCES, "arguments": arguments });
|
||||
let request = run.peer.request::<_, Value>("workspace/executeCommand", params, None);
|
||||
if let Ok(Err(e)) | Err(e) =
|
||||
tokio::time::timeout(COMMAND_TIMEOUT, request).await.map_err(|_| ide_jsonrpc::RpcError::Timeout)
|
||||
{
|
||||
tracing::debug!("jdtls: {GENERATED_SOURCES}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The jdtls instance serving `path` (a module directory or source file),
|
||||
/// started if needed and waited for.
|
||||
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
//! Maven plugin output that jdtls never imports.
|
||||
//!
|
||||
//! `protobuf-maven-plugin` and the same kind of generator call
|
||||
//! `MavenProject.addCompileSourceRoot` while the build runs. That list is not in the
|
||||
//! POM, so m2e never adds the folders and the editor keeps reporting missing packages
|
||||
//! after a successful Maven compile. Annotation-processor output (`annotations`,
|
||||
//! `test-annotations`) is left out: jdtls compiles it itself, and adding it as a source
|
||||
//! folder makes the processor emit the same file twice.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MAX_DEPTH: usize = 16;
|
||||
const MAX_JAVA_FILES: usize = 4_000;
|
||||
const MAX_PARENTS: usize = 8;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) struct GeneratedRoot {
|
||||
pub path: PathBuf,
|
||||
pub test: bool,
|
||||
}
|
||||
|
||||
pub(crate) struct GeneratedScan {
|
||||
pub maven: bool,
|
||||
pub roots: Vec<GeneratedRoot>,
|
||||
}
|
||||
|
||||
/// Generated Java source folders under `root` (a reactor or one module).
|
||||
pub(crate) fn scan(root: &Path) -> GeneratedScan {
|
||||
let mut modules = Vec::new();
|
||||
collect_modules(root, 0, &mut modules);
|
||||
let mut roots = Vec::new();
|
||||
for module in &modules {
|
||||
let build = build_dir(module);
|
||||
collect_tree(&build.join("generated-sources"), false, &mut roots);
|
||||
collect_tree(&build.join("generated-test-sources"), true, &mut roots);
|
||||
}
|
||||
roots.sort();
|
||||
roots.dedup();
|
||||
GeneratedScan { maven: !modules.is_empty(), roots }
|
||||
}
|
||||
|
||||
fn collect_modules(dir: &Path, depth: usize, modules: &mut Vec<PathBuf>) {
|
||||
if depth > MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
let has_pom = dir.join("pom.xml").is_file();
|
||||
if has_pom {
|
||||
modules.push(dir.to_path_buf());
|
||||
}
|
||||
let build_name = has_pom.then(|| build_dir(dir)).and_then(|dir| dir.file_name().map(|name| name.to_os_string()));
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let Ok(kind) = entry.file_type() else { continue };
|
||||
if !kind.is_dir() || kind.is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let shown = name.to_string_lossy();
|
||||
if shown.starts_with('.') || shown == "node_modules" || shown == "target" {
|
||||
continue;
|
||||
}
|
||||
if build_name.as_ref().is_some_and(|build| build == &name) {
|
||||
continue;
|
||||
}
|
||||
collect_modules(&entry.path(), depth + 1, modules);
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_tree(tree: &Path, test: bool, roots: &mut Vec<GeneratedRoot>) {
|
||||
let mut files = Vec::new();
|
||||
walk_java(tree, 0, &mut files);
|
||||
let mut found = HashSet::new();
|
||||
for file in files {
|
||||
let Some(package) = package_name(&read_head(&file)) else { continue };
|
||||
let Some(root) = source_root(&file, &package) else { continue };
|
||||
if root.starts_with(tree) && found.insert(root.clone()) {
|
||||
roots.push(GeneratedRoot { path: root, test });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_java(dir: &Path, depth: usize, files: &mut Vec<PathBuf>) {
|
||||
if depth > MAX_DEPTH || files.len() >= MAX_JAVA_FILES {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
if files.len() >= MAX_JAVA_FILES {
|
||||
return;
|
||||
}
|
||||
let Ok(kind) = entry.file_type() else { continue };
|
||||
if kind.is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let path = entry.path();
|
||||
if kind.is_dir() {
|
||||
// The compiler's own output. jdtls already consumes it as annotation processing.
|
||||
if depth == 0 && matches!(entry.file_name().to_str(), Some("annotations" | "test-annotations")) {
|
||||
continue;
|
||||
}
|
||||
walk_java(&path, depth + 1, files);
|
||||
} else if kind.is_file() && path.extension().is_some_and(|ext| ext == "java") {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_head(path: &Path) -> String {
|
||||
let Ok(bytes) = std::fs::read(path) else { return String::new() };
|
||||
let head = &bytes[..bytes.len().min(4096)];
|
||||
String::from_utf8_lossy(head).into_owned()
|
||||
}
|
||||
|
||||
/// The `package` declaration, ignoring comments that precede it.
|
||||
fn package_name(text: &str) -> Option<String> {
|
||||
let mut rest = text;
|
||||
loop {
|
||||
let trimmed = rest.trim_start();
|
||||
if let Some(after) = trimmed.strip_prefix("//") {
|
||||
rest = after.split_once('\n').map(|(_, next)| next).unwrap_or("");
|
||||
continue;
|
||||
}
|
||||
if let Some(after) = trimmed.strip_prefix("/*") {
|
||||
rest = after.split_once("*/").map(|(_, next)| next).unwrap_or("");
|
||||
continue;
|
||||
}
|
||||
let after = trimmed.strip_prefix("package")?;
|
||||
if !after.starts_with(|c: char| c.is_whitespace()) {
|
||||
return None;
|
||||
}
|
||||
let after = after.trim_start();
|
||||
let end = after.find([';', '{', '\n', '\r', ' ', '\t', '/']).unwrap_or(after.len());
|
||||
let name = after[..end].trim();
|
||||
if name.is_empty() || !name.split('.').all(java_identifier) {
|
||||
return None;
|
||||
}
|
||||
return Some(name.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
fn java_identifier(segment: &str) -> bool {
|
||||
let mut chars = segment.chars();
|
||||
matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$')
|
||||
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
|
||||
}
|
||||
|
||||
/// Directory that is the source root for `file` declaring `package`.
|
||||
fn source_root(file: &Path, package: &str) -> Option<PathBuf> {
|
||||
let mut dir = file.parent()?.to_path_buf();
|
||||
for segment in package.split('.').rev() {
|
||||
if dir.file_name().and_then(|n| n.to_str()) != Some(segment) {
|
||||
return None;
|
||||
}
|
||||
dir.pop();
|
||||
}
|
||||
Some(dir)
|
||||
}
|
||||
|
||||
fn build_dir(module: &Path) -> PathBuf {
|
||||
let mut pom = module.join("pom.xml");
|
||||
let mut seen = HashSet::new();
|
||||
for _ in 0..MAX_PARENTS {
|
||||
if !seen.insert(pom.clone()) {
|
||||
break;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(&pom) else { break };
|
||||
let text = strip_comments(&text);
|
||||
if let Some(raw) = own_build_directory(&text) {
|
||||
let rel = relative_build_dir(&raw).unwrap_or_else(|| "target".to_owned());
|
||||
return module.join(rel);
|
||||
}
|
||||
let Some(parent) = parent_pom(pom.parent().unwrap_or(module), &text) else { break };
|
||||
pom = parent;
|
||||
}
|
||||
module.join("target")
|
||||
}
|
||||
|
||||
fn own_build_directory(pom: &str) -> Option<String> {
|
||||
let build = section(pom, "build")?;
|
||||
let own = plugins_removed(build);
|
||||
section(&own, "directory").map(str::to_owned)
|
||||
}
|
||||
|
||||
fn parent_pom(dir: &Path, pom: &str) -> Option<PathBuf> {
|
||||
let parent = section(pom, "parent")?;
|
||||
let rel = match relative_path(parent) {
|
||||
Some(value) if value.trim().is_empty() => return None,
|
||||
Some(value) => value.trim(),
|
||||
None => "../pom.xml",
|
||||
};
|
||||
if rel.contains("${") || rel.starts_with(['/', '\\']) || rel.contains(':') {
|
||||
return None;
|
||||
}
|
||||
let path = dir.join(rel);
|
||||
path.is_file().then_some(path)
|
||||
}
|
||||
|
||||
/// `<relativePath>` text, or `Some("")` for a self-closing `<relativePath/>` (no local parent).
|
||||
fn relative_path(parent: &str) -> Option<&str> {
|
||||
if let Some(value) = section(parent, "relativePath") {
|
||||
return Some(value);
|
||||
}
|
||||
["<relativePath/>", "<relativePath />"].iter().any(|tag| parent.contains(tag)).then_some("")
|
||||
}
|
||||
|
||||
fn relative_build_dir(raw: &str) -> Option<String> {
|
||||
let mut value = raw.trim();
|
||||
for prefix in ["${project.basedir}", "${basedir}"] {
|
||||
if let Some(rest) = value.strip_prefix(prefix) {
|
||||
value = rest.trim_start_matches(['/', '\\']);
|
||||
}
|
||||
}
|
||||
if value.is_empty()
|
||||
|| value.contains("${")
|
||||
|| value.contains("..")
|
||||
|| value.starts_with(['/', '\\'])
|
||||
|| value.contains(':')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(value.replace('\\', "/"))
|
||||
}
|
||||
|
||||
fn strip_comments(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find("<!--") {
|
||||
out.push_str(&rest[..start]);
|
||||
rest = rest[start..].find("-->").map_or("", |end| &rest[start + end + 3..]);
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
fn section<'a>(text: &'a str, tag: &str) -> Option<&'a str> {
|
||||
let open = format!("<{tag}>");
|
||||
let start = text.find(&open)? + open.len();
|
||||
let end = text[start..].find(&format!("</{tag}>"))?;
|
||||
Some(&text[start..start + end])
|
||||
}
|
||||
|
||||
fn plugins_removed(build: &str) -> String {
|
||||
let mut text = build.to_owned();
|
||||
for tag in ["plugins", "pluginManagement"] {
|
||||
let (open, close) = (format!("<{tag}>"), format!("</{tag}>"));
|
||||
let mut kept = String::with_capacity(text.len());
|
||||
let mut rest = text.as_str();
|
||||
while let Some(start) = rest.find(&open) {
|
||||
kept.push_str(&rest[..start]);
|
||||
rest = rest[start..].find(&close).map_or("", |end| &rest[start + end + close.len()..]);
|
||||
}
|
||||
kept.push_str(rest);
|
||||
text = kept;
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn grpc(root: &Path) {
|
||||
write(root, "pom.xml", "<project><artifactId>app</artifactId></project>");
|
||||
write(
|
||||
root,
|
||||
"target/generated-sources/protobuf/java/com/example/hello/Hello.java",
|
||||
"package com.example.hello;\npublic class Hello {}",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"target/generated-sources/protobuf/grpc-java/com/example/hello/HelloGrpc.java",
|
||||
"/* generated */\npackage com.example.hello;\npublic class HelloGrpc {}",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"target/generated-sources/annotations/com/example/hello/HelloMapperImpl.java",
|
||||
"package com.example.hello;\nclass HelloMapperImpl {}",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protobuf_and_grpc_roots_are_kept_and_annotation_output_is_not() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
grpc(root);
|
||||
let scan = scan(root);
|
||||
assert!(scan.maven);
|
||||
assert_eq!(
|
||||
scan.roots,
|
||||
vec![
|
||||
GeneratedRoot { path: root.join("target/generated-sources/protobuf/grpc-java"), test: false },
|
||||
GeneratedRoot { path: root.join("target/generated-sources/protobuf/java"), test: false },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_before_the_package_and_test_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "pom.xml", "<project/>");
|
||||
write(
|
||||
root,
|
||||
"target/generated-test-sources/protobuf/java/com/example/hello/HelloTest.java",
|
||||
"// package ignored.nope;\n/* package also.nope; */\npackage com.example.hello;\nclass HelloTest {}",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"target/generated-test-sources/test-annotations/com/example/hello/Skip.java",
|
||||
"package com.example.hello;\nclass Skip {}",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"target/generated-sources/protobuf/java/com/example/Wrong.java",
|
||||
"package com.other;\nclass Wrong {}",
|
||||
);
|
||||
let scan = scan(root);
|
||||
assert_eq!(
|
||||
scan.roots,
|
||||
vec![GeneratedRoot { path: root.join("target/generated-test-sources/protobuf/java"), test: true }]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_build_directory_ignores_plugin_configuration_and_inherits_from_the_parent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(
|
||||
root,
|
||||
"pom.xml",
|
||||
r#"<project><build><directory>out</directory></build><modules><module>app</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project>
|
||||
<parent><groupId>g</groupId><artifactId>p</artifactId><version>1</version></parent>
|
||||
<build>
|
||||
<plugins><plugin><configuration><directory>nope</directory></configuration></plugin></plugins>
|
||||
<directory>${project.basedir}/custom</directory>
|
||||
</build>
|
||||
</project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"lib/pom.xml",
|
||||
"<project><parent><groupId>g</groupId><artifactId>p</artifactId><version>1</version></parent></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/custom/generated-sources/protobuf/grpc-java/com/example/hello/HelloGrpc.java",
|
||||
"package com.example.hello;\nclass HelloGrpc {}",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"lib/out/generated-sources/protobuf/java/com/example/hello/Hello.java",
|
||||
"package com.example.hello;\nclass Hello {}",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"lib/target/generated-sources/protobuf/java/com/example/hello/Stale.java",
|
||||
"package com.example.hello;\nclass Stale {}",
|
||||
);
|
||||
let scan = scan(root);
|
||||
let paths: Vec<_> = scan.roots.iter().map(|r| r.path.clone()).collect();
|
||||
assert_eq!(
|
||||
paths,
|
||||
vec![
|
||||
root.join("app/custom/generated-sources/protobuf/grpc-java"),
|
||||
root.join("lib/out/generated-sources/protobuf/java"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_relative_path_does_not_inherit_the_parent_build_directory() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "pom.xml", "<project><build><directory>out</directory></build></project>");
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
"<project><parent><groupId>g</groupId><artifactId>p</artifactId><version>1</version><relativePath/></parent></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/target/generated-sources/protobuf/java/com/example/hello/Hello.java",
|
||||
"package com.example.hello;\nclass Hello {}",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/out/generated-sources/protobuf/java/com/example/hello/Other.java",
|
||||
"package com.example.hello;\nclass Other {}",
|
||||
);
|
||||
let scan = scan(root);
|
||||
assert_eq!(
|
||||
scan.roots,
|
||||
vec![GeneratedRoot { path: root.join("app/target/generated-sources/protobuf/java"), test: false }]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_without_maven_is_not_a_scan() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write(
|
||||
tmp.path(),
|
||||
"target/generated-sources/protobuf/java/com/example/hello/Hello.java",
|
||||
"package com.example.hello;\nclass Hello {}",
|
||||
);
|
||||
let scan = scan(tmp.path());
|
||||
assert!(!scan.maven);
|
||||
assert!(scan.roots.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ mod kotlin_lsp;
|
||||
mod launch;
|
||||
mod library_source;
|
||||
mod loading;
|
||||
mod message_requests;
|
||||
mod notebook;
|
||||
mod phoxite;
|
||||
mod plugin_requests;
|
||||
@@ -48,6 +49,7 @@ pub use jdtls::jvm_inspect::JdtJvmInspector;
|
||||
pub use jdtls::stream_trace::JdtStreamTracer;
|
||||
pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable};
|
||||
pub use launch::{LaunchError, Launcher, ProcessLauncher};
|
||||
pub use message_requests::answer as answer_message_request;
|
||||
pub use notebook::{NotebookCell, NotebookCellDoc, cell_uri};
|
||||
pub use plugin_requests::plugin_method_allowed;
|
||||
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Pending `window/showMessageRequest` questions, answered from the UI.
|
||||
//!
|
||||
//! The LSP handler runs on a blocking-capable thread (`ide-jsonrpc` promises
|
||||
//! this), so it can wait for the user's choice. Answers arrive through the
|
||||
//! `lsp_message_request_answer` command and are matched by a process-wide id;
|
||||
//! a question that timed out is removed so a late click cannot answer it.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::mpsc;
|
||||
|
||||
static NEXT: AtomicU32 = AtomicU32::new(1);
|
||||
static PENDING: std::sync::LazyLock<Mutex<HashMap<u32, mpsc::Sender<Option<String>>>>> =
|
||||
std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// At most this many questions may wait for an answer: an unruly server must
|
||||
/// not pile up modal dialogs or hold many blocking threads.
|
||||
const MAX_PENDING: usize = 8;
|
||||
|
||||
/// Registers a question and returns its id plus the answer receiver. `None`
|
||||
/// means the cap was reached; the caller must fail closed without asking.
|
||||
pub fn begin() -> Option<(u32, mpsc::Receiver<Option<String>>)> {
|
||||
let mut pending = PENDING.lock();
|
||||
if pending.len() >= MAX_PENDING {
|
||||
return None;
|
||||
}
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
pending.insert(id, tx);
|
||||
Some((id, rx))
|
||||
}
|
||||
|
||||
/// Answers question `id` with the chosen action title, or `None` when dismissed.
|
||||
pub fn answer(id: u32, choice: Option<String>) -> bool {
|
||||
let Some(tx) = PENDING.lock().remove(&id) else { return false };
|
||||
tx.send(choice).is_ok()
|
||||
}
|
||||
|
||||
/// Forgets a question that ended without an answer (timeout or shutdown).
|
||||
pub fn close(id: u32) {
|
||||
PENDING.lock().remove(&id);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn answer_resolves_only_once() {
|
||||
let (id, rx) = begin().unwrap();
|
||||
assert!(answer(id, Some("Rename Anyway".into())));
|
||||
assert!(!answer(id, Some("late".into())));
|
||||
assert_eq!(rx.recv().unwrap(), Some("Rename Anyway".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_ignores_late_answers() {
|
||||
let (id, _rx) = begin().unwrap();
|
||||
close(id);
|
||||
assert!(!answer(id, None));
|
||||
}
|
||||
}
|
||||
@@ -1607,6 +1607,36 @@ async fn a_cancelled_pull_is_retried_and_a_refresh_pulls_again() {
|
||||
eventually(|| shown(&h, &path, "mock") == Some(vec!["reloaded".into()])).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn show_message_request_unknown_action_replies_null() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
h.open("dismiss.mk", "abc\n");
|
||||
h.wait_status("mock", ServerStatus::Ready).await;
|
||||
let peer = h.launcher.state("mock").peer();
|
||||
let request = peer.request(
|
||||
"window/showMessageRequest",
|
||||
json!({ "type": 2, "message": "Continue?", "actions": [{ "title": "Yes" }] }),
|
||||
None,
|
||||
);
|
||||
tokio::pin!(request);
|
||||
let id = loop {
|
||||
if let Some(id) = h.events.lock().iter().find_map(|event| match event {
|
||||
IdeEvent::LspMessageRequest { id, message, .. } if message == "Continue?" => Some(*id),
|
||||
_ => None,
|
||||
}) {
|
||||
break id;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = &mut request => panic!("showMessageRequest finished before the UI event"),
|
||||
_ = tokio::time::sleep(Duration::from_millis(10)) => {}
|
||||
}
|
||||
};
|
||||
// An action that was not offered must not be sent back as a choice.
|
||||
assert!(ide_lsp::answer_message_request(id, Some("No".into())));
|
||||
let reply: Value = request.await.unwrap();
|
||||
assert_eq!(reply, Value::Null);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn apply_edit_hook_and_server_requests() {
|
||||
let h = harness(&[("mock", incremental_caps())]);
|
||||
@@ -1657,15 +1687,34 @@ async fn apply_edit_hook_and_server_requests() {
|
||||
assert_eq!(folders[0]["uri"], json!(uri_of(&h.root)));
|
||||
let v: Value = peer.request("window/workDoneProgress/create", json!({ "token": "t" }), None).await.unwrap();
|
||||
assert_eq!(v, Value::Null);
|
||||
let v: Value = peer
|
||||
.request(
|
||||
"window/showMessageRequest",
|
||||
json!({ "type": 1, "message": "boom", "actions": [{ "title": "OK" }] }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(v, Value::Null);
|
||||
let request = peer.request(
|
||||
"window/showMessageRequest",
|
||||
json!({ "type": 1, "message": "Rename Anyway?", "actions": [{ "title": "Rename Anyway" }, { "title": "Cancel" }] }),
|
||||
None,
|
||||
);
|
||||
tokio::pin!(request);
|
||||
let id = loop {
|
||||
if let Some(id) = h.events.lock().iter().find_map(|event| match event {
|
||||
IdeEvent::LspMessageRequest { id, message, actions, .. } if message == "Rename Anyway?" => {
|
||||
assert_eq!(actions, &["Rename Anyway".to_owned(), "Cancel".to_owned()]);
|
||||
Some(*id)
|
||||
}
|
||||
_ => None,
|
||||
}) {
|
||||
break id;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = &mut request => panic!("showMessageRequest finished before the UI event"),
|
||||
_ = tokio::time::sleep(Duration::from_millis(10)) => {}
|
||||
}
|
||||
};
|
||||
assert!(ide_lsp::answer_message_request(id, Some("Rename Anyway".into())));
|
||||
let v: Value = request.await.unwrap();
|
||||
assert_eq!(v, json!({ "title": "Rename Anyway" }));
|
||||
eventually(|| {
|
||||
h.events.lock().iter().any(|event| matches!(event, IdeEvent::LspMessageRequestDone { id: done } if *done == id))
|
||||
})
|
||||
.await;
|
||||
let v: Value = peer
|
||||
.request(
|
||||
"client/registerCapability",
|
||||
@@ -1691,8 +1740,8 @@ async fn apply_edit_hook_and_server_requests() {
|
||||
.await;
|
||||
let notifies = h.events.lock().iter().filter(|e| matches!(e, IdeEvent::Notify { .. })).count();
|
||||
assert_eq!(
|
||||
notifies, 2,
|
||||
"showMessageRequest error + showMessage warning; info and rust-analyzer's developer notices are not surfaced"
|
||||
notifies, 1,
|
||||
"showMessageRequest is now a question with actions, not a notification; info and developer notices are not surfaced"
|
||||
);
|
||||
|
||||
// Dynamically registered capability is now usable.
|
||||
@@ -2894,6 +2943,57 @@ async fn open_java_files_are_checked_again_after_a_project_update() {
|
||||
eventually(|| refreshed() == expected).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_project_update_attaches_maven_generated_sources_before_rechecking() {
|
||||
let mut caps = incremental_caps();
|
||||
caps["executeCommandProvider"]["commands"].as_array_mut().unwrap().push(json!("openidea.java.generatedSources"));
|
||||
let h = harness_for("java", "java", &[("jdtls", caps)], &[]);
|
||||
let (_, _) = h.open("App.java", "package com.example;\nclass App {}");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let write = |rel: &str, text: &str| {
|
||||
let path = h.root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
};
|
||||
write("pom.xml", "<project><artifactId>app</artifactId></project>");
|
||||
write(
|
||||
"target/generated-sources/protobuf/java/com/example/hello/Hello.java",
|
||||
"package com.example.hello;\npublic class Hello {}",
|
||||
);
|
||||
write(
|
||||
"target/generated-sources/protobuf/grpc-java/com/example/hello/HelloGrpc.java",
|
||||
"package com.example.hello;\npublic class HelloGrpc {}",
|
||||
);
|
||||
write(
|
||||
"target/generated-sources/annotations/com/example/hello/HelloMapperImpl.java",
|
||||
"package com.example.hello;\nclass HelloMapperImpl {}",
|
||||
);
|
||||
let state = h.launcher.state("jdtls");
|
||||
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
|
||||
eventually(|| {
|
||||
let requests = state.requested("workspace/executeCommand");
|
||||
let generated = requests.iter().position(|p| p["command"] == "openidea.java.generatedSources");
|
||||
let refresh = requests.iter().position(|p| p["command"] == "java.project.refreshDiagnostics");
|
||||
matches!((generated, refresh), (Some(generated), Some(refresh)) if generated < refresh)
|
||||
})
|
||||
.await;
|
||||
let requests = state.requested("workspace/executeCommand");
|
||||
let generated = requests.iter().find(|p| p["command"] == "openidea.java.generatedSources").unwrap();
|
||||
let paths: Vec<_> = generated["arguments"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|arg| (arg["path"].as_str().unwrap().to_owned(), arg["test"].as_bool().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
paths,
|
||||
vec![
|
||||
(h.root.join("target/generated-sources/protobuf/grpc-java").to_string_lossy().into_owned(), false),
|
||||
(h.root.join("target/generated-sources/protobuf/java").to_string_lossy().into_owned(), false),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn library_classes_in_jars_open_as_their_source_or_decompiled() {
|
||||
use std::io::Write;
|
||||
|
||||
@@ -10,7 +10,7 @@ mod zig;
|
||||
use crate::RunConfig;
|
||||
use ide_core::project_roots::expand_members;
|
||||
use serde_json::Value as Json;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -591,14 +591,15 @@ fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
|
||||
level = level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src")).collect();
|
||||
modules.extend(level.iter().cloned());
|
||||
}
|
||||
for module in modules {
|
||||
if !applies_spring_boot(&module) {
|
||||
let mut annotations = BootAnnotations::new(&modules);
|
||||
for module in &modules {
|
||||
if !applies_spring_boot(build, module) {
|
||||
continue;
|
||||
}
|
||||
// A budget per module: a large common library must not starve later app modules.
|
||||
let mut budget = SPRING_SCAN_FILES;
|
||||
let module_rel = (module != root).then(|| relative(root, &module).to_string_lossy().replace('\\', "/"));
|
||||
for class in spring_boot_classes(&module, &mut budget) {
|
||||
let module_rel = (module != root).then(|| relative(root, module).to_string_lossy().replace('\\', "/"));
|
||||
for class in spring_boot_classes(module, &mut budget, &mut annotations) {
|
||||
let simple = class.rsplit(['.', '$']).next().unwrap_or(&class).to_owned();
|
||||
let id = match &module_rel {
|
||||
Some(m) => format!("application:{m}:{class}"),
|
||||
@@ -612,28 +613,163 @@ fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The module's own build applies the Spring Boot plugin, and it has main sources.
|
||||
fn applies_spring_boot(module: &Path) -> bool {
|
||||
/// The module has main sources, and its build applies the Spring Boot plugin: its own build
|
||||
/// file, or a build above it in `build` that applies it to its modules (a parent POM's
|
||||
/// `<build><plugins>`, Gradle's `subprojects` / `allprojects`).
|
||||
fn applies_spring_boot(build: &Path, module: &Path) -> bool {
|
||||
if !["java", "kotlin"].iter().any(|l| module.join("src/main").join(l).is_dir()) {
|
||||
return false;
|
||||
}
|
||||
if let Some(pom) = read(&module.join("pom.xml")) {
|
||||
return pom.contains("spring-boot-maven-plugin") && !pom.contains("<packaging>pom</packaging>");
|
||||
if pom.contains("<packaging>pom</packaging>") {
|
||||
return false;
|
||||
}
|
||||
if pom.contains("spring-boot-maven-plugin") {
|
||||
return true;
|
||||
}
|
||||
} else if GRADLE_BUILDS.iter().filter_map(|n| read(&module.join(n))).any(|text| applies_boot_gradle_plugin(&text)) {
|
||||
return true;
|
||||
}
|
||||
GRADLE_BUILDS.iter().filter_map(|n| read(&module.join(n))).any(|text| {
|
||||
text.lines().any(|l| {
|
||||
let l = l.split("//").next().unwrap_or_default();
|
||||
// The plugin id (`id("org.springframework.boot")`), not a dependency (`org.springframework.boot:…`).
|
||||
["org.springframework.boot\"", "org.springframework.boot'"].iter().any(|p| l.contains(p))
|
||||
&& !l.contains("apply false")
|
||||
module.ancestors().skip(1).take_while(|dir| dir.starts_with(build)).any(|dir| {
|
||||
if let Some(pom) = read(&dir.join("pom.xml")) {
|
||||
return without_plugin_management(&pom).contains("spring-boot-maven-plugin");
|
||||
}
|
||||
GRADLE_BUILDS.iter().filter_map(|n| read(&dir.join(n))).any(|text| {
|
||||
(text.contains("subprojects") || text.contains("allprojects")) && applies_boot_gradle_plugin(&text)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Binary names of the `@SpringBootApplication` classes with a `main` under
|
||||
/// A Gradle build applying the plugin (`id("org.springframework.boot")`, `apply plugin: '…'`),
|
||||
/// not only depending on Spring Boot (`org.springframework.boot:…`).
|
||||
fn applies_boot_gradle_plugin(text: &str) -> bool {
|
||||
text.lines().any(|l| {
|
||||
let l = l.split("//").next().unwrap_or_default();
|
||||
["org.springframework.boot\"", "org.springframework.boot'"].iter().any(|p| l.contains(p))
|
||||
&& !l.contains("apply false")
|
||||
})
|
||||
}
|
||||
|
||||
/// A POM without its `<pluginManagement>` sections, which configure plugins without applying them.
|
||||
fn without_plugin_management(pom: &str) -> String {
|
||||
let mut out = String::with_capacity(pom.len());
|
||||
let mut rest = pom;
|
||||
while let Some(at) = rest.find("<pluginManagement>") {
|
||||
out.push_str(&rest[..at]);
|
||||
let Some(end) = rest[at..].find("</pluginManagement>") else { return out };
|
||||
rest = &rest[at + end + "</pluginManagement>".len()..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// Annotations that mark a Spring Boot application class: `@SpringBootApplication`,
|
||||
/// `@SpringCloudApplication`, and the project's own annotations meta-annotated with either.
|
||||
struct BootAnnotations {
|
||||
/// `src/main/{java,kotlin}` of every module, where a project annotation is looked up.
|
||||
roots: Vec<PathBuf>,
|
||||
known: HashMap<String, bool>,
|
||||
}
|
||||
|
||||
const BOOT_ANNOTATIONS: [&str; 2] = ["SpringBootApplication", "SpringCloudApplication"];
|
||||
|
||||
impl BootAnnotations {
|
||||
fn new(modules: &[PathBuf]) -> Self {
|
||||
let roots = modules
|
||||
.iter()
|
||||
.flat_map(|m| ["java", "kotlin"].map(|l| m.join("src/main").join(l)))
|
||||
.filter(|d| d.is_dir())
|
||||
.collect();
|
||||
Self { roots, known: HashMap::new() }
|
||||
}
|
||||
|
||||
/// Whether `@name`, as written in a file of `package` with `imports`, marks an application.
|
||||
fn marks_application(&mut self, name: &str, package: Option<&str>, imports: &[&str]) -> bool {
|
||||
let simple = name.rsplit('.').next().unwrap_or(name);
|
||||
if BOOT_ANNOTATIONS.contains(&simple) {
|
||||
return true;
|
||||
}
|
||||
let qualified = if name.contains('.') {
|
||||
name.to_owned()
|
||||
} else if let Some(import) = imports.iter().find(|i| i.rsplit('.').next() == Some(name)) {
|
||||
(*import).to_owned()
|
||||
} else {
|
||||
match package {
|
||||
Some(p) => format!("{p}.{name}"),
|
||||
None => name.to_owned(),
|
||||
}
|
||||
};
|
||||
if qualified.starts_with("org.springframework.") {
|
||||
return false;
|
||||
}
|
||||
if let Some(&known) = self.known.get(&qualified) {
|
||||
return known;
|
||||
}
|
||||
// Not yet known: no cycle through an annotation that names itself.
|
||||
self.known.insert(qualified.clone(), false);
|
||||
let found = self.declares_boot_annotation(&qualified);
|
||||
self.known.insert(qualified, found);
|
||||
found
|
||||
}
|
||||
|
||||
/// The project declares annotation `qualified` and annotates it as an application.
|
||||
fn declares_boot_annotation(&mut self, qualified: &str) -> bool {
|
||||
let path = qualified.replace('.', "/");
|
||||
let simple = qualified.rsplit('.').next().unwrap_or(qualified);
|
||||
let source = self
|
||||
.roots
|
||||
.iter()
|
||||
.flat_map(|r| ["java", "kt"].map(|x| r.join(format!("{path}.{x}"))))
|
||||
.find_map(|f| read(&f));
|
||||
let Some(src) = source else { return false };
|
||||
let code = strip_line_comments(&src);
|
||||
let Some(decl) = [format!("@interface {simple}"), format!("annotation class {simple}")]
|
||||
.iter()
|
||||
.find_map(|d| code.find(d.as_str()))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let (package, imports) = package_and_imports(&code);
|
||||
annotations_in(&code[..decl]).iter().any(|a| self.marks_application(a, package.as_deref(), &imports))
|
||||
}
|
||||
}
|
||||
|
||||
fn strip_line_comments(src: &str) -> String {
|
||||
src.lines().map(|l| l.split("//").next().unwrap_or_default()).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
fn package_and_imports(code: &str) -> (Option<String>, Vec<&str>) {
|
||||
let package = code
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find_map(|l| l.strip_prefix("package "))
|
||||
.map(|p| p.trim_end_matches(';').trim().to_owned())
|
||||
.filter(|p| !p.is_empty());
|
||||
let imports = code
|
||||
.lines()
|
||||
.filter_map(|l| l.trim().strip_prefix("import "))
|
||||
.map(|i| i.trim_end_matches(';').trim())
|
||||
.filter(|i| !i.starts_with("static ") && !i.ends_with('*'))
|
||||
.collect();
|
||||
(package, imports)
|
||||
}
|
||||
|
||||
/// Names of the annotations in `code` (`@Foo`, `@a.b.Foo(…)`), in order; `@interface` excluded.
|
||||
fn annotations_in(code: &str) -> Vec<&str> {
|
||||
code.match_indices('@')
|
||||
.filter_map(|(at, _)| {
|
||||
let rest = &code[at + 1..];
|
||||
let len = rest.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '.')).unwrap_or(rest.len());
|
||||
let name = rest[..len].trim_end_matches('.');
|
||||
(!name.is_empty() && name != "interface" && !name.starts_with("file:")).then_some(name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Binary names of the Spring Boot application classes with a `main` under
|
||||
/// `src/main/{java,kotlin}`, from the shallowest packages that declare one (the
|
||||
/// application class sits in the root package of the code it scans).
|
||||
fn spring_boot_classes(module: &Path, budget: &mut usize) -> Vec<String> {
|
||||
fn spring_boot_classes(module: &Path, budget: &mut usize, annotations: &mut BootAnnotations) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
let mut level: Vec<PathBuf> =
|
||||
["java", "kotlin"].iter().map(|l| module.join("src/main").join(l)).filter(|d| d.is_dir()).collect();
|
||||
@@ -661,7 +797,7 @@ fn spring_boot_classes(module: &Path, budget: &mut usize) -> Vec<String> {
|
||||
if fs::metadata(&file).is_ok_and(|m| m.len() > 256 * 1024) {
|
||||
continue;
|
||||
}
|
||||
if let Some(class) = read(&file).and_then(|src| spring_boot_class(&src, &file)) {
|
||||
if let Some(class) = read(&file).and_then(|src| spring_boot_class(&src, &file, annotations)) {
|
||||
found.push(class);
|
||||
}
|
||||
}
|
||||
@@ -672,41 +808,35 @@ fn spring_boot_classes(module: &Path, budget: &mut usize) -> Vec<String> {
|
||||
found
|
||||
}
|
||||
|
||||
/// The class to launch for a source file declaring a `@SpringBootApplication` with a `main`.
|
||||
pub(crate) fn spring_boot_class(src: &str, file: &Path) -> Option<String> {
|
||||
let code: Vec<&str> = src.lines().map(|l| l.split("//").next().unwrap_or_default()).collect();
|
||||
let code = code.join("\n");
|
||||
let at = code.find("@SpringBootApplication")?;
|
||||
let package = code
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.find_map(|l| l.strip_prefix("package "))
|
||||
.map(|p| p.trim_end_matches(';').trim().to_owned())
|
||||
.filter(|p| !p.is_empty());
|
||||
/// The class to launch for a source file declaring a Spring Boot application class with a `main`.
|
||||
fn spring_boot_class(src: &str, file: &Path, annotations: &mut BootAnnotations) -> Option<String> {
|
||||
let code = strip_line_comments(src);
|
||||
let (package, imports) = package_and_imports(&code);
|
||||
let qualify = |name: &str| match &package {
|
||||
Some(p) => format!("{p}.{name}"),
|
||||
None => name.to_owned(),
|
||||
};
|
||||
if file.extension().is_some_and(|x| x == "kt") {
|
||||
// A top-level `fun main` compiles into the file facade (`AppKt`, or `@file:JvmName`).
|
||||
if code.lines().any(|l| l.starts_with("fun main(")) {
|
||||
let jvm_name = code
|
||||
.lines()
|
||||
.find_map(|l| l.trim().strip_prefix("@file:JvmName(")?.split('"').nth(1).map(str::to_owned));
|
||||
let facade = jvm_name.unwrap_or_else(|| {
|
||||
let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let mut chars = stem.chars();
|
||||
let upper: String = chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default();
|
||||
format!("{upper}Kt")
|
||||
});
|
||||
return Some(qualify(&facade));
|
||||
}
|
||||
if !code.contains("fun main(") {
|
||||
return None;
|
||||
}
|
||||
} else if !code.contains("void main(") {
|
||||
let kotlin = file.extension().is_some_and(|x| x == "kt");
|
||||
if !(if kotlin { code.contains("fun main(") } else { code.contains("void main(") }) {
|
||||
return None;
|
||||
}
|
||||
// The annotation right before a class declaration: `@SpringBootApplication` or one carrying it.
|
||||
let at = annotations_in(&code)
|
||||
.into_iter()
|
||||
.find(|a| !a.starts_with("file:") && annotations.marks_application(a, package.as_deref(), &imports))?;
|
||||
let at = code.find(&format!("@{at}"))?;
|
||||
if kotlin && code.lines().any(|l| l.starts_with("fun main(")) {
|
||||
// A top-level `fun main` compiles into the file facade (`AppKt`, or `@file:JvmName`).
|
||||
let jvm_name =
|
||||
code.lines().find_map(|l| l.trim().strip_prefix("@file:JvmName(")?.split('"').nth(1).map(str::to_owned));
|
||||
let facade = jvm_name.unwrap_or_else(|| {
|
||||
let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let mut chars = stem.chars();
|
||||
let upper: String = chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default();
|
||||
format!("{upper}Kt")
|
||||
});
|
||||
return Some(qualify(&facade));
|
||||
}
|
||||
let name: String = code[at..]
|
||||
.split_whitespace()
|
||||
.skip_while(|t| *t != "class")
|
||||
|
||||
@@ -13,12 +13,18 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
|
||||
let src = code_only(&src);
|
||||
out.push(config(BUILD_ID, "zig build", "zig", "zig", &["build"]));
|
||||
let roots = test_roots(&src);
|
||||
let run_exes = run_step_exes(&src);
|
||||
for step in steps(&src) {
|
||||
// `install` is what plain `zig build` runs.
|
||||
if step == "install" || step == "uninstall" {
|
||||
continue;
|
||||
}
|
||||
let mut c = config(format!("zig:{step}"), format!("zig build {step}"), "zig", "zig", &["build", &step]);
|
||||
// A build step that runs an executable has no debug adapter of its own; point it at the
|
||||
// executable config, which builds first and debugs the installed binary under CodeLLDB.
|
||||
if let Some(exe) = run_exes.iter().find(|(name, _)| name == &step) {
|
||||
c.extras.params.insert("debugTarget".into(), format!("zig:exe:{}", exe.1));
|
||||
}
|
||||
if step == "test" || step.starts_with("test-") || step.starts_with("test_") {
|
||||
c = c.test();
|
||||
if let Some((_, root)) = roots.iter().find(|(name, _)| *name == step) {
|
||||
@@ -109,52 +115,51 @@ struct Executable {
|
||||
source: Option<String>,
|
||||
}
|
||||
|
||||
/// `addExecutable(.{ .name = "…", … .root_source_file = <b>.path("…") … })`: the name at the
|
||||
/// options' top level (an `imports` entry has its own `.name`) and the first root source file.
|
||||
/// `.name` and `.root_source_file` of an `addExecutable` call body (just after its `(`).
|
||||
/// The name is read at the options' top level — an `imports` entry has its own `.name`.
|
||||
fn add_executable_fields(body: &str) -> (Option<String>, Option<String>) {
|
||||
let (mut depth, mut in_string, mut escaped) = (0usize, false, false);
|
||||
let (mut name, mut source) = (None, None);
|
||||
for (i, c) in body.char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'{' | '[' => depth += 1,
|
||||
'}' | ']' => depth -= 1,
|
||||
'.' => {
|
||||
let field = &body[i + 1..];
|
||||
let value = |key: &str| field.strip_prefix(key)?.trim_start().strip_prefix('=').map(str::trim_start);
|
||||
if depth == 1 && name.is_none() {
|
||||
name = value("name").and_then(string_at);
|
||||
}
|
||||
if source.is_none()
|
||||
&& let Some(v) = value("root_source_file")
|
||||
&& let Some(call) = v.find(".path(")
|
||||
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
{
|
||||
source = string_at(&v[call + ".path(".len()..]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(name, source)
|
||||
}
|
||||
|
||||
/// `addExecutable(.{ .name = "…", … })`: the name at the options' top level and the first root source file.
|
||||
fn executables(src: &str) -> Vec<Executable> {
|
||||
let mut out: Vec<Executable> = Vec::new();
|
||||
for (start, _) in src.match_indices("addExecutable(") {
|
||||
let body = &src[start + "addExecutable(".len()..];
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
let mut name = None;
|
||||
let mut source = None;
|
||||
for (i, c) in body.char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'(' | '{' | '[' => depth += 1,
|
||||
')' | '}' | ']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
'.' => {
|
||||
let field = &body[i + 1..];
|
||||
let value =
|
||||
|key: &str| field.strip_prefix(key)?.trim_start().strip_prefix('=').map(str::trim_start);
|
||||
if depth == 2 && name.is_none() {
|
||||
name = value("name").and_then(string_at);
|
||||
}
|
||||
if source.is_none()
|
||||
&& let Some(v) = value("root_source_file")
|
||||
&& let Some(call) = v.find(".path(")
|
||||
&& v[..call].chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
{
|
||||
source = string_at(&v[call + ".path(".len()..]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let body = call_body(src, start + "addExecutable(".len());
|
||||
let (name, source) = add_executable_fields(body);
|
||||
if let Some(name) = name
|
||||
&& !name.is_empty()
|
||||
&& !out.iter().any(|e| e.name == name)
|
||||
@@ -165,6 +170,109 @@ fn executables(src: &str) -> Vec<Executable> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Variables assigned from `addExecutable` calls, mapped to the executable's name.
|
||||
fn executable_vars(src: &str) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (start, _) in src.match_indices("addExecutable(") {
|
||||
let body = call_body(src, start + "addExecutable(".len());
|
||||
let (Some(name), Some(var)) = (add_executable_fields(body).0, assigned_var(src, start)) else { continue };
|
||||
if !name.is_empty() && !out.iter().any(|(v, _)| v == var) {
|
||||
out.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Variables assigned from `b.addRunArtifact(x)` calls, mapped to `x` (an executable or test).
|
||||
fn run_artifact_vars(src: &str) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (start, _) in src.match_indices("addRunArtifact(") {
|
||||
let body = call_body(src, start + "addRunArtifact(".len());
|
||||
let arg: String = body.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
if arg.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(var) = assigned_var(src, start)
|
||||
&& !out.iter().any(|(v, _)| v == var)
|
||||
{
|
||||
out.push((var.to_owned(), arg));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Step variables assigned from `b.step("name", …)` calls, mapped to the step's name.
|
||||
fn step_vars(src: &str) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".step(\"") {
|
||||
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
|
||||
if let Some(var) = assigned_var(src, i + 1)
|
||||
&& !out.iter().any(|(v, _)| v == var)
|
||||
{
|
||||
out.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The argument of a `.dependOn(&…)` call: `after` starts just past its `&`. Stopping at the
|
||||
/// matching `)` keeps a later `addRunArtifact(` in a different step from being mistaken for this
|
||||
/// step's artifact.
|
||||
fn depend_arg(after: &str) -> &str {
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
for (i, c) in after.char_indices() {
|
||||
if in_string {
|
||||
match c {
|
||||
_ if escaped => escaped = false,
|
||||
'\\' => escaped = true,
|
||||
'"' => in_string = false,
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match c {
|
||||
'"' => in_string = true,
|
||||
'(' | '{' | '[' => depth += 1,
|
||||
')' | '}' | ']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return &after[..i];
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
after
|
||||
}
|
||||
|
||||
/// Steps whose `dependOn` runs an executable: `(step name, executable name)`. Both the inline
|
||||
/// (`step.dependOn(&b.addRunArtifact(exe).step)`) and the assigned form
|
||||
/// (`const cmd = b.addRunArtifact(exe); step.dependOn(&cmd.step)`) are handled.
|
||||
fn run_step_exes(src: &str) -> Vec<(String, String)> {
|
||||
let exes = executable_vars(src);
|
||||
let artifacts = run_artifact_vars(src);
|
||||
let steps = step_vars(src);
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".dependOn(&") {
|
||||
let Some(step_var) = receiver_var(src, i + 1) else { continue };
|
||||
let Some((_, name)) = steps.iter().find(|(v, _)| v == step_var) else { continue };
|
||||
let arg = depend_arg(&src[i + ".dependOn(&".len()..]);
|
||||
let exe_var = if let Some(at) = arg.find("addRunArtifact(") {
|
||||
let v = &arg[at + "addRunArtifact(".len()..];
|
||||
v.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect::<String>()
|
||||
} else {
|
||||
let v: String = arg.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||
artifacts.iter().find(|(var, _)| var == &v).map(|(_, exe)| exe.clone()).unwrap_or_default()
|
||||
};
|
||||
if let Some((_, exe_name)) = exes.iter().find(|(var, _)| var == &exe_var)
|
||||
&& !out.iter().any(|(n, _)| n == name)
|
||||
{
|
||||
out.push((name.clone(), exe_name.clone()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The call's argument text: from just after its `(` to the matching `)`.
|
||||
fn call_body(src: &str, start: usize) -> &str {
|
||||
let (mut depth, mut in_string, mut escaped) = (1usize, false, false);
|
||||
@@ -255,14 +363,7 @@ fn test_roots(src: &str) -> Vec<(String, String)> {
|
||||
tests.push((var.to_owned(), root));
|
||||
}
|
||||
}
|
||||
let mut steps: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".step(\"") {
|
||||
let Some(name) = string_at(&src[i + ".step(".len()..]) else { continue };
|
||||
// The match includes the dot, so the assignment ends one character earlier.
|
||||
if let Some(var) = assigned_var(src, i + 1) {
|
||||
steps.push((var.to_owned(), name));
|
||||
}
|
||||
}
|
||||
let steps = step_vars(src);
|
||||
let mut out: Vec<(String, String)> = Vec::new();
|
||||
for (i, _) in src.match_indices(".dependOn(&") {
|
||||
let Some(step) = receiver_var(src, i + 1) else { continue };
|
||||
@@ -325,6 +426,7 @@ pub fn build(b: *std.Build) void {
|
||||
}) });
|
||||
_ = tool;
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&b.addRunArtifact(exe).step);
|
||||
const tests = b.addTest(.{ .root_module = mod });
|
||||
const test_step = b.step("test", "Run tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
@@ -358,6 +460,11 @@ pub fn build(b: *std.Build) void {
|
||||
(test.command.as_str(), test.args.as_slice()),
|
||||
("zig", ["build".to_owned(), "test".to_owned()].as_slice())
|
||||
);
|
||||
// The run step has no adapter of its own, but points at the executable config that does.
|
||||
let run = out.iter().find(|c| c.id == "zig:run").unwrap();
|
||||
assert_eq!(run.debug_adapter, None);
|
||||
assert_eq!(run.extras.params.get("debugTarget").map(String::as_str), Some("zig:exe:app"));
|
||||
assert!(!out.iter().find(|c| c.id == "zig:docs").unwrap().extras.params.contains_key("debugTarget"));
|
||||
let app = out.iter().find(|c| c.id == "zig:exe:app").unwrap();
|
||||
assert_eq!(app.kind, "zig-application");
|
||||
assert!(app.command.ends_with(if cfg!(windows) { "app.exe" } else { "zig-out/bin/app" }));
|
||||
@@ -400,4 +507,36 @@ pub fn build(b: *std.Build) void {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
const ASSIGNED_RUN: &str = r#"const std = @import("std");
|
||||
pub fn build(b: *std.Build) void {
|
||||
const exe = b.addExecutable(.{ .name = "app", .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
}) });
|
||||
b.installArtifact(exe);
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
run_cmd.step.dependOn(b.getInstallStep());
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
const tests = b.addTest(.{ .root_module = b.createModule(.{
|
||||
.root_source_file = b.path("src/tally.zig"),
|
||||
}) });
|
||||
const test_step = b.step("test", "Run tests");
|
||||
test_step.dependOn(&b.addRunArtifact(tests).step);
|
||||
}
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn a_run_step_linked_through_an_assigned_command_finds_its_executable() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("build.zig"), ASSIGNED_RUN).unwrap();
|
||||
let mut out = Vec::new();
|
||||
detect(dir.path(), &mut out);
|
||||
// The test step below the run step has its own inline addRunArtifact; it must not be
|
||||
// mistaken for the run step's executable.
|
||||
let run = out.iter().find(|c| c.id == "zig:run").unwrap();
|
||||
assert_eq!(run.extras.params.get("debugTarget").map(String::as_str), Some("zig:exe:app"));
|
||||
let test = out.iter().find(|c| c.id == "zig:test").unwrap();
|
||||
assert!(!test.extras.params.contains_key("debugTarget"));
|
||||
}
|
||||
}
|
||||
@@ -399,6 +399,57 @@ fn spring_boot_applications_need_the_plugin_and_a_main() {
|
||||
assert!(!c.iter().any(|c| c.kind == "spring-boot"), "{:?}", ids(&c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spring_boot_modules_inherit_the_plugin_from_their_parent_build() {
|
||||
let main = |pkg: &str, ann: &str, cls: &str| {
|
||||
format!("package {pkg};\n{ann}\npublic class {cls} {{\n public static void main(String[] a) {{}}\n}}\n")
|
||||
};
|
||||
let parent = "<project><packaging>pom</packaging><modules><module>order</module><module>user</module>\
|
||||
<module>gateway</module></modules><build><plugins><plugin>\
|
||||
<artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>";
|
||||
let order = main("shop.order", "@SpringBootApplication", "OrderApp");
|
||||
let user = main("shop.user", "@SpringCloudApplication", "UserApp");
|
||||
// A project annotation carrying @SpringBootApplication, declared in another module.
|
||||
let gateway = main("shop.gateway", "@ShopApplication", "GatewayApp")
|
||||
.replace("package shop.gateway;\n", "package shop.gateway;\nimport shop.common.ShopApplication;\n");
|
||||
let annotation = "package shop.common;\n\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\
|
||||
@Target(ElementType.TYPE)\n@SpringBootApplication\npublic @interface ShopApplication {}\n";
|
||||
let files = [
|
||||
("pom.xml", parent.to_owned()),
|
||||
("order/pom.xml", "<project><artifactId>order</artifactId></project>".to_owned()),
|
||||
("order/src/main/java/shop/order/OrderApp.java", order),
|
||||
("user/pom.xml", "<project><artifactId>user</artifactId></project>".to_owned()),
|
||||
("user/src/main/java/shop/user/UserApp.java", user),
|
||||
("gateway/pom.xml", "<project><artifactId>gateway</artifactId></project>".to_owned()),
|
||||
("gateway/src/main/java/shop/gateway/GatewayApp.java", gateway),
|
||||
("common/src/main/java/shop/common/ShopApplication.java", annotation.to_owned()),
|
||||
];
|
||||
let files: Vec<(&str, &str)> = files.iter().map(|(p, t)| (*p, t.as_str())).collect();
|
||||
let c = detect(project(&files).path());
|
||||
for id in [
|
||||
"application:order:shop.order.OrderApp",
|
||||
"application:user:shop.user.UserApp",
|
||||
"application:gateway:shop.gateway.GatewayApp",
|
||||
] {
|
||||
assert_eq!(find(&c, id).kind, "spring-boot", "{id}");
|
||||
}
|
||||
|
||||
// A parent that only manages the plugin doesn't apply it; Gradle applies it from `subprojects`.
|
||||
let dir = project(&[
|
||||
("pom.xml", PARENT_POM),
|
||||
("app/pom.xml", "<project/>"),
|
||||
("app/src/main/java/demo/App.java", &main("demo", "@SpringBootApplication", "App")),
|
||||
]);
|
||||
assert!(!detect(dir.path()).iter().any(|c| c.kind == "spring-boot"));
|
||||
let dir = project(&[
|
||||
("settings.gradle", "include 'app'\n"),
|
||||
("build.gradle", "subprojects {\n apply plugin: 'org.springframework.boot'\n}\n"),
|
||||
("app/build.gradle", "dependencies {}\n"),
|
||||
("app/src/main/java/demo/App.java", &main("demo", "@SpringBootApplication", "App")),
|
||||
]);
|
||||
assert_eq!(find(&detect(dir.path()), "application:app:demo.App").kind, "spring-boot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_projects() {
|
||||
let dir = project(&[
|
||||
|
||||
@@ -1614,7 +1614,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(
|
||||
data_dir,
|
||||
"java-usages",
|
||||
"1.15.0",
|
||||
"1.16.0",
|
||||
include_bytes!("../../../java/java-usages/openidea-java-usages.jar"),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -360,6 +360,10 @@ pub struct Stash {
|
||||
pub index: u32,
|
||||
pub message: String,
|
||||
pub time_ms: f64,
|
||||
/// The stash commit; its changes are those against `base`.
|
||||
pub id: String,
|
||||
/// The commit the stash was made on (the stash commit's first parent).
|
||||
pub base: Option<String>,
|
||||
}
|
||||
|
||||
/// Push dialog › Push tags: every tag, or only annotated tags on the pushed commits.
|
||||
@@ -529,9 +533,12 @@ pub enum CheckoutOutcome {
|
||||
LocalChanges {
|
||||
files: Vec<String>,
|
||||
},
|
||||
/// These untracked files (repository-relative paths) would be overwritten.
|
||||
/// These untracked files (repository-relative paths) would be overwritten by the
|
||||
/// checkout; with `removed`, they would be removed by it (tracked here, absent
|
||||
/// from the target).
|
||||
UntrackedFiles {
|
||||
files: Vec<String>,
|
||||
removed: bool,
|
||||
},
|
||||
/// Local branch `local` has commits that remote branch `remote` does not.
|
||||
LocalBranchAhead {
|
||||
|
||||
@@ -158,7 +158,15 @@ pub(crate) fn stashes(r: &Repo) -> IdeResult<Vec<Stash>> {
|
||||
for (index, line) in lines.enumerate() {
|
||||
let line = line.map_err(gx)?;
|
||||
let time_ms = line.signature.time.seconds as f64 * 1000.0;
|
||||
out.push(Stash { index: index as u32, message: to_string(line.message.as_ref()), time_ms });
|
||||
let id = line.new_oid.to_owned();
|
||||
let base = repo.find_commit(id).ok().and_then(|c| c.parent_ids().next().map(|p| p.to_string()));
|
||||
out.push(Stash {
|
||||
index: index as u32,
|
||||
message: to_string(line.message.as_ref()),
|
||||
time_ms,
|
||||
id: id.to_string(),
|
||||
base,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -771,9 +771,14 @@ fn overwritten_files(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "local changes to the following files would be overwritten")
|
||||
}
|
||||
|
||||
/// Untracked files git refuses to overwrite, from its error message.
|
||||
fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "untracked working tree files would be")
|
||||
/// Untracked files git refuses to lose, from its error message: they would be *removed*
|
||||
/// by the checkout (tracked here, absent from the target) or *overwritten* by it (present
|
||||
/// in the target). Returns the files and whether they would be removed.
|
||||
fn refused_untracked(stderr: &str) -> Option<(Vec<String>, bool)> {
|
||||
if let Some(files) = listed_files(stderr, "untracked working tree files would be removed") {
|
||||
return Some((files, true));
|
||||
}
|
||||
Some((listed_files(stderr, "untracked working tree files would be")?, false))
|
||||
}
|
||||
|
||||
/// The branch git refused to check out or update because another worktree has it, from
|
||||
@@ -840,8 +845,8 @@ pub(crate) fn checkout_with(
|
||||
if let Some((branch, path)) = branch_of_other_worktree(&stderr) {
|
||||
return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() });
|
||||
}
|
||||
if let Some(files) = overwritten_untracked(&stderr) {
|
||||
return Ok(CheckoutOutcome::UntrackedFiles { files });
|
||||
if let Some((files, removed)) = refused_untracked(&stderr) {
|
||||
return Ok(CheckoutOutcome::UntrackedFiles { files, removed });
|
||||
}
|
||||
let Some(files) = overwritten_files(&stderr) else {
|
||||
return Err(cli::failure(&argv, &out.stderr, &out.stdout, out.code));
|
||||
|
||||
@@ -849,6 +849,11 @@ fn stash_push_list_apply_pop() {
|
||||
assert!(stashes[0].message.contains("WIP on main"), "{stashes:?}");
|
||||
assert!(stashes[1].message.contains("first stash"), "{stashes:?}");
|
||||
assert!(stashes[0].time_ms > 0.0);
|
||||
// Each stash lists the files it changed against the commit it was made on.
|
||||
let head = repo.head().unwrap().1.unwrap();
|
||||
assert!(stashes.iter().all(|s| s.base.as_deref() == Some(head.as_str())), "{stashes:?}");
|
||||
let files = repo.commit_files(&stashes[1].id).unwrap();
|
||||
assert_eq!(files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["s.txt"]);
|
||||
|
||||
repo.stash_apply(1, false, false).unwrap();
|
||||
assert_eq!(fx.read("s.txt"), "change 1\n");
|
||||
@@ -2074,12 +2079,37 @@ fn checkout_reports_untracked_files_it_would_overwrite() {
|
||||
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
|
||||
let opts = CheckoutOptions { mode, ..Default::default() };
|
||||
let outcome = repo.checkout_with("other", false, &opts).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()], removed: false });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(fx.read("dir/new.txt"), "mine\n");
|
||||
}
|
||||
}
|
||||
|
||||
/// Untracked on disk but tracked on the current branch and gone from the target
|
||||
/// (as after `git rm --cached`): git refuses to *remove* the file, and the outcome
|
||||
/// says so (#3980).
|
||||
#[test]
|
||||
fn checkout_reports_untracked_files_it_would_remove() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("TEST.md", "hi\n");
|
||||
fx.commit_all("base");
|
||||
fx.git(&["checkout", "-q", "-b", "feature/x"]);
|
||||
fx.git(&["rm", "-q", "TEST.md"]);
|
||||
fx.commit_all("remove TEST.md on feature/x");
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
fx.git(&["rm", "--cached", "TEST.md"]);
|
||||
fx.write("TEST.md", "local dirty version\n");
|
||||
let repo = fx.repo();
|
||||
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
|
||||
// The refusal leaves the repository untouched, so both modes see the same state.
|
||||
let opts = CheckoutOptions { mode, ..Default::default() };
|
||||
let outcome = repo.checkout_with("feature/x", false, &opts).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["TEST.md".into()], removed: true });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
assert_eq!(fx.read("TEST.md"), "local dirty version\n");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reword_keeps_local_changes_and_can_be_undone() {
|
||||
let fx = Fixture::new();
|
||||
|
||||
@@ -846,6 +846,7 @@ mod tests {
|
||||
"wrapAtMargin": false,
|
||||
"disabledPluginChecks": [],
|
||||
"doubleClickOpensDiff": null,
|
||||
"agentInstructions": "",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ On your own messages you can **Edit** (the messages after it are replaced; files
|
||||
|
||||
**Focus Agent Input** defaults to `⌘L` on macOS and `Ctrl+L` on Windows / Linux in every built-in keymap. When focus is inside your writable task conversation, in either an editor tab or the tool window, it returns focus to the message input without changing your draft, caret position or selection—even when pressed repeatedly. It does not send a message or jump through message history.
|
||||
|
||||
The shortcut does not apply to archived tasks, subagent conversations or the New Task page, and does not take focus from open popups or dialogs. Outside the task conversation, the keys keep their usual editor or terminal behavior. To change or remove the binding, open **Settings › Keymap › Agents › Focus Agent Input**.
|
||||
With focus anywhere else, the same shortcut jumps to the message input of the task shown in an editor tab or the tool window (the one you used last, if several are shown), unless a panel claims the shortcut there: in a code editor `⌘L` / `Ctrl+L` keeps its editor meaning (for example Go to Line), and in a terminal on Windows / Linux `Ctrl+L` still reaches the shell. It does not apply to archived tasks, subagent conversations or the New Task page, and does not take focus from open popups or dialogs. To change or remove the binding, open **Settings › Keymap › Agents › Focus Agent Input**.
|
||||
|
||||
**Cycle Agent Effort** defaults to `Option+T` on macOS and `Alt+T` on Windows / Linux in every built-in keymap. With focus inside New Task or your own writable task conversation, in an editor tab or the tool window, it cycles the current model's provider-advertised effort levels in order, wrapping from the last to the first. It preserves your message, selection, caret and focus, and sends nothing. Like the effort control, it changes the provider configuration; it does not promise to change a turn already running.
|
||||
|
||||
|
||||
@@ -129,6 +129,14 @@ OpenIDEA indexes Spring Web endpoints (`@RestController` / `@Controller` classes
|
||||
|
||||
Plugins can contribute endpoints of other frameworks; they get an **Open in HTTP Client** gutter icon.
|
||||
|
||||
### Feign navigation
|
||||
|
||||
In Java and Kotlin `@FeignClient` interfaces, click the **Go to Feign Endpoint** gutter arrow or use the same action from the editor menu or Find Action. On a literal mapping path such as `@GetMapping("/users/{id}")`, modifier-click or Go to Declaration also opens matching controller methods. Multiple matches use the existing declaration chooser; method declarations keep their usual Find Usages behavior.
|
||||
|
||||
The built-in index matches HTTP methods and literal paths, including whole `{variable}` segments. A literal Feign `name` or `value` narrows candidates against an unambiguous `spring.application.name` in the destination module's `src/main/resources/application.properties`, `.yml` or `.yaml` (also under `resources/config`). Configuration is never inherited from a parent module or test sources. Conflicting profile names, dynamic or missing identities, and clients with explicit/dynamic `url` retain method/path candidates. No HTTP request is sent.
|
||||
|
||||
This is source navigation, not service-discovery or effective runtime configuration resolution. Custom source sets, composed/aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns and reverse controller-to-client navigation are outside this first version. Navigation reads bounded local configuration and rechecks current controller text, including unsaved editor changes.
|
||||
|
||||
## Not supported
|
||||
|
||||
- JavaScript response handlers (`> {% ... %}`, `> handler.js`) and pre-request scripts. Handler lines are recognized and skipped.
|
||||
|
||||
@@ -80,7 +80,7 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex
|
||||
|
||||
所有内置按键映射中,**聚焦 Agent 输入框** 的默认快捷键都是 macOS 上的 `⌘L`、Windows / Linux 上的 `Ctrl+L`。焦点位于你自己的可输入任务对话中时,无论对话显示在编辑器标签页还是工具窗口中,它都会将焦点移回消息输入框,保留草稿、光标位置和选区;重复按下也不会改变这些内容。它不会发送消息,也不会跳转消息历史。
|
||||
|
||||
此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。在任务对话之外,按键保留原有的编辑器或终端行为。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
|
||||
焦点位于其他位置时,同一快捷键会跳转到编辑器标签页或工具窗口中显示的任务的消息输入框(显示多个时,选择你最近使用的那个),除非该位置有面板占用此快捷键:在代码编辑器中,`⌘L` / `Ctrl+L` 保留编辑器含义(例如“转到行”);在 Windows / Linux 的终端中,`Ctrl+L` 仍会发送给 shell。此快捷键不适用于已归档任务、子 agent 对话或“新建任务”页面,也不会从打开的弹出窗口或对话框中抢走焦点。要修改或移除绑定,请打开 **设置 › 按键映射 › 智能体 › 聚焦 Agent 输入框**。
|
||||
|
||||
所有内置按键映射中,**循环切换 Agent 思考强度** 的默认快捷键都是 macOS 上的 `Option+T`、Windows / Linux 上的 `Alt+T`。焦点位于“新建任务”或你自己的可输入任务对话中时,无论显示在编辑器标签页还是工具窗口中,它都会按提供商声明的顺序切换当前模型支持的思考强度,从最后一级循环回第一级。它会保留消息、选区、光标和焦点,不发送任何内容。与思考强度控件一样,它修改的是提供商配置,不保证改变已经运行中的轮次。
|
||||
|
||||
|
||||
@@ -129,6 +129,14 @@ OpenIDEA 会为 Java 和 Kotlin 中的 Spring Web 端点(带 `@RequestMapping`
|
||||
|
||||
插件可以提供其他框架的端点,这些端点旁会有 **在 HTTP 客户端中打开** 边栏图标。
|
||||
|
||||
### Feign 导航
|
||||
|
||||
在 Java 或 Kotlin 的 `@FeignClient` 接口中,点击装订线上的 **跳转到 Feign 端点** 箭头,或从编辑器菜单、查找操作中执行同名操作。在 `@GetMapping("/users/{id}")` 等字面量路径上,也可以使用修饰键点击或跳转到声明。有多个候选时会显示已有的声明选择器;方法声明仍保留原来的查找用法行为。
|
||||
|
||||
内置索引按 HTTP 方法和字面量路径匹配控制器,支持完整的 `{variable}` 路径段。Feign 的字面量 `name` 或 `value` 会与目标模块 `src/main/resources` 或其 `config` 子目录中 `application.properties`、`.yml`、`.yaml` 的明确 `spring.application.name` 比较。不会继承父模块或测试资源的配置。配置身份缺失、动态或有冲突,以及客户端指定显式或动态 `url` 时,仍保留方法和路径匹配的候选。导航不会发送 HTTP 请求。
|
||||
|
||||
这是源码导航,不解析服务发现或运行时生效配置。首个版本不支持自定义源码目录、组合或别名注解、继承映射、动态路径、`@RequestLine`、Ant/正则路径模式及控制器到客户端的反向导航。配置读取有数量和大小限制;跳转前会重新检查当前控制器文本,包括未保存的编辑。
|
||||
|
||||
## 暂不支持
|
||||
|
||||
- JavaScript 响应处理脚本(`> {% ... %}`、`> handler.js`)和请求前脚本。处理脚本行能被识别,但会跳过。
|
||||
|
||||
@@ -327,6 +327,23 @@ test("editor Go to Line stays available while a docked agent conversation is vis
|
||||
await expect(messageBox(page)).toHaveText(draft);
|
||||
});
|
||||
|
||||
for (const placement of ["editor", "toolWindow"] as const) {
|
||||
test(`${placement}: the shortcut jumps to the shown task's input from the project tree`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await openFromTree(page, "README.md");
|
||||
await seedTasks(page, placement);
|
||||
const box = messageBox(page);
|
||||
await box.fill(draft);
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
|
||||
await expect(box).not.toBeFocused();
|
||||
await page.keyboard.press("Meta+L");
|
||||
await expect(box).toBeFocused();
|
||||
await expect(box).toHaveText(draft);
|
||||
await expect(page.getByRole("dialog", { name: "Go to Line:Column", exact: true })).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const preset of ["intellij-windows", "vscode-windows", "eclipse-windows"]) {
|
||||
test(`${preset} uses Ctrl+L to focus the task message`, async ({ workbench: page }) => {
|
||||
await seedTasks(page, "editor");
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test.use({ video: "on" });
|
||||
|
||||
test("Feign navigation selects the named service and offers ambiguous source targets", async ({
|
||||
workbench: page,
|
||||
}, testInfo) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const { docBackend } = await import(backend);
|
||||
const files: Map<string, string> = docBackend().files;
|
||||
const root = "/dev/acme-api";
|
||||
const client = `package shop;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@FeignClient(name = "users")
|
||||
interface UserClient {
|
||||
@GetMapping("/users/{id}")
|
||||
String find();
|
||||
}`;
|
||||
files.set(`${root}/client/src/main/java/UserClient.java`, client);
|
||||
for (const service of ["users", "admin"]) {
|
||||
files.set(
|
||||
`${root}/${service}/src/main/java/UserController.java`,
|
||||
`package shop;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@RestController
|
||||
class UserController {
|
||||
@GetMapping("/users/{id}")
|
||||
String find() { return "${service}"; }
|
||||
}`,
|
||||
);
|
||||
files.set(`${root}/${service}/src/main/resources/application.properties`, `spring.application.name=${service}\n`);
|
||||
}
|
||||
window.__ipc.handlers.spring_route_sources = () =>
|
||||
[...files].filter(([p]) => p.endsWith("UserController.java")).map(([path, text]) => ({ path, text }));
|
||||
window.__ipc.handlers.fs_read_text = ({ path }) => {
|
||||
if (!files.has(String(path))) throw { kind: "notFound", message: "No fixture file" };
|
||||
return files.get(String(path));
|
||||
};
|
||||
window.__ipc.handlers.fs_read_dir = ({ path }) =>
|
||||
[
|
||||
...new Set(
|
||||
[...files.keys()]
|
||||
.filter((p) => p.startsWith(`${path}/`))
|
||||
.map((p) => p.slice(String(path).length + 1).split("/")[0]!),
|
||||
),
|
||||
].map((name) => ({
|
||||
path: `${path}/${name}`,
|
||||
name,
|
||||
kind: files.has(`${path}/${name}`) ? "file" : "dir",
|
||||
size: files.get(`${path}/${name}`)?.length ?? 0,
|
||||
mtimeMs: 0,
|
||||
ignored: false,
|
||||
excluded: false,
|
||||
hidden: false,
|
||||
}));
|
||||
window.__ipc.handlers.lsp_goto = () => [];
|
||||
await (await import(contributions)).editorService().openFile(`${root}/client/src/main/java/UserClient.java`);
|
||||
});
|
||||
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
|
||||
await page.screenshot({ path: testInfo.outputPath("feign-source.png"), animations: "disabled" });
|
||||
await page.locator('button[data-icon-source="feign"]').click();
|
||||
await expect(page.locator(".cm-content").last()).toContainText('return "users"');
|
||||
await page.screenshot({ path: testInfo.outputPath("feign-target.png"), animations: "disabled" });
|
||||
await page.evaluate(async () => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
const ipc = "/src/platform/ipc.ts";
|
||||
const path = "/dev/acme-api/admin/src/main/resources/application.properties";
|
||||
(await import(backend)).docBackend().files.set(path, "spring.application.name=users\n");
|
||||
(await import(ipc)).emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [path], removed: [] });
|
||||
await (await import(contributions)).editorService().openFile("/dev/acme-api/client/src/main/java/UserClient.java");
|
||||
});
|
||||
await page.locator('button[data-icon-source="feign"]').click();
|
||||
const chooser = page.getByRole("dialog", { name: "Choose Feign Endpoint" });
|
||||
await expect(chooser.getByRole("option")).toHaveCount(2);
|
||||
await page.screenshot({ path: testInfo.outputPath("feign-chooser.png"), animations: "disabled" });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
|
||||
await page.locator('button[data-icon-source="feign"]').click();
|
||||
await expect(chooser.getByRole("option")).toHaveCount(2);
|
||||
await page.evaluate(async () => {
|
||||
const ipc = "/src/platform/ipc.ts";
|
||||
(await import(ipc)).emitLocalIdeEvent({
|
||||
type: "fsChanged",
|
||||
created: [],
|
||||
modified: ["/dev/acme-api/admin/src/main/resources/application.properties"],
|
||||
removed: [],
|
||||
});
|
||||
});
|
||||
await chooser.getByRole("option").filter({ hasText: "admin/" }).click();
|
||||
await expect(chooser).not.toBeVisible();
|
||||
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
|
||||
// The existing declaration navigation handles mapping URLs; method names
|
||||
// retain the usual declaration-to-usages behavior.
|
||||
await page.evaluate(async () => {
|
||||
const api = "/src/editor/api.ts";
|
||||
const editor = (await import(api)).activeEditor();
|
||||
const offset = editor.view.state.doc.toString().indexOf("/users/{id}") + 2;
|
||||
editor.view.dispatch({ selection: { anchor: offset } });
|
||||
editor.view.focus();
|
||||
});
|
||||
await page.keyboard.press("Meta+b");
|
||||
const declarations = page.getByRole("dialog", { name: "Choose Declaration" });
|
||||
await expect(declarations.getByRole("option")).toHaveCount(2);
|
||||
await declarations.getByRole("option").filter({ hasText: "admin/" }).click();
|
||||
await expect(page.locator(".cm-content").last()).toContainText('return "admin"');
|
||||
});
|
||||
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
|
||||
Bundle-ManifestVersion: 2
|
||||
Bundle-Name: OpenIDEA Java usages
|
||||
Bundle-SymbolicName: ai.openidea.usages;singleton:=true
|
||||
Bundle-Version: 1.15.0
|
||||
Bundle-Version: 1.16.0
|
||||
Bundle-RequiredExecutionEnvironment: JavaSE-21
|
||||
Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core,
|
||||
org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime,
|
||||
|
||||
@@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity.
|
||||
## Rebuild and delivery
|
||||
|
||||
The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as
|
||||
`java-usages-1.15.0.jar`, and added alongside existing initialization bundles.
|
||||
`java-usages-1.16.0.jar`, and added alongside existing initialization bundles.
|
||||
Users need no compiler, Maven or Python. Manifest/install version must change
|
||||
when replacing the bundle because OSGi caches bundles.
|
||||
|
||||
@@ -136,6 +136,9 @@ Version 1.12.0 caches usages answers until the Java model or an unsaved edit cha
|
||||
Version 1.15.0 adds `openidea.java.implementationLocations`, which resolves the method an
|
||||
implementation in a dependency declares (the standard request starts at its class file); its
|
||||
reproducible SHA-256 is `c29e5455c02c245523b2e7a5861e00ae670cefc66cda33ec19fdce280f94c40c`.
|
||||
Version 1.16.0 adds `openidea.java.generatedSources`, which puts Maven plugin output such as
|
||||
protobuf and gRPC stubs on the project classpath; its reproducible SHA-256 is
|
||||
`a5feda1cae11bdea1044fb311404840b048601af037f65685973721f1eefff8b`.
|
||||
|
||||
```sh
|
||||
export PATH=/path/to/jdk25/bin:$PATH
|
||||
|
||||
Бінарний файл не відображається.
@@ -20,6 +20,9 @@
|
||||
<delegateCommandHandler class="ai.openidea.archives.RefreshArchivesCommand">
|
||||
<command id="openidea.java.refreshArchives"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.sources.GeneratedSourcesCommand">
|
||||
<command id="openidea.java.generatedSources"/>
|
||||
</delegateCommandHandler>
|
||||
<delegateCommandHandler class="ai.openidea.implementations.ImplementationTargetsCommand">
|
||||
<command id="openidea.java.implementationLocations"/>
|
||||
</delegateCommandHandler>
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package ai.openidea.sources;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.eclipse.core.resources.IFolder;
|
||||
import org.eclipse.core.resources.IProject;
|
||||
import org.eclipse.core.resources.IResource;
|
||||
import org.eclipse.core.resources.ResourcesPlugin;
|
||||
import org.eclipse.core.runtime.CoreException;
|
||||
import org.eclipse.core.runtime.IPath;
|
||||
import org.eclipse.core.runtime.IProgressMonitor;
|
||||
import org.eclipse.core.runtime.OperationCanceledException;
|
||||
import org.eclipse.core.runtime.Path;
|
||||
import org.eclipse.jdt.core.IClasspathAttribute;
|
||||
import org.eclipse.jdt.core.IClasspathEntry;
|
||||
import org.eclipse.jdt.core.IJavaProject;
|
||||
import org.eclipse.jdt.core.JavaCore;
|
||||
import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler;
|
||||
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
|
||||
|
||||
/**
|
||||
* Adds Maven plugin output (protobuf, gRPC, jOOQ, …) as source folders.
|
||||
*
|
||||
* <p>The argument is {@code [{path, test}, …]}: absolute directories the build already
|
||||
* generated. Folders this command added are marked {@code openidea.generatedSource} and
|
||||
* dropped again when they are no longer in that list, so a later reload does not keep a
|
||||
* source folder Maven has cleaned. Entries m2e or build-helper already created are left
|
||||
* as they are.
|
||||
*/
|
||||
public final class GeneratedSourcesCommand implements IDelegateCommandHandler {
|
||||
static final String MARKER = "openidea.generatedSource";
|
||||
private static final String MAVEN = "org.eclipse.m2e.core.maven2Nature";
|
||||
|
||||
private record Spec(IPath path, boolean test) {}
|
||||
|
||||
@Override
|
||||
public Object executeCommand(String command, List<Object> arguments, IProgressMonitor monitor) throws Exception {
|
||||
List<Spec> specs = specs(arguments);
|
||||
IJavaProject[] projects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()).getJavaProjects();
|
||||
int changed = 0;
|
||||
for (IJavaProject project : projects) {
|
||||
if (monitor.isCanceled()) throw new OperationCanceledException();
|
||||
if (!isMaven(project)) continue;
|
||||
if (sync(project, owned(projects, project, specs), monitor)) changed++;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static List<Spec> specs(List<Object> arguments) {
|
||||
List<Spec> specs = new ArrayList<>();
|
||||
if (arguments == null) return specs;
|
||||
for (Object argument : arguments) {
|
||||
if (!(argument instanceof Map<?, ?> map)) continue;
|
||||
if (!(map.get("path") instanceof String path) || path.isBlank()) continue;
|
||||
specs.add(new Spec(Path.fromOSString(path), Boolean.TRUE.equals(map.get("test"))));
|
||||
}
|
||||
return specs;
|
||||
}
|
||||
|
||||
/** Specs whose longest Maven project prefix is `project`. A reactor parent also prefixes its modules. */
|
||||
private static List<Spec> owned(IJavaProject[] projects, IJavaProject project, List<Spec> specs) {
|
||||
IPath location = project.getProject().getLocation();
|
||||
List<Spec> owned = new ArrayList<>();
|
||||
if (location == null) return owned;
|
||||
for (Spec spec : specs) {
|
||||
if (!location.isPrefixOf(spec.path)) continue;
|
||||
IJavaProject best = project;
|
||||
int segments = location.segmentCount();
|
||||
for (IJavaProject other : projects) {
|
||||
if (other == project || !isMaven(other)) continue;
|
||||
IPath otherLocation = other.getProject().getLocation();
|
||||
if (otherLocation != null && otherLocation.isPrefixOf(spec.path)
|
||||
&& otherLocation.segmentCount() > segments) {
|
||||
best = other;
|
||||
segments = otherLocation.segmentCount();
|
||||
}
|
||||
}
|
||||
if (best == project) owned.add(spec);
|
||||
}
|
||||
return owned;
|
||||
}
|
||||
|
||||
private static boolean sync(IJavaProject project, List<Spec> specs, IProgressMonitor monitor) {
|
||||
try {
|
||||
IPath location = project.getProject().getLocation();
|
||||
if (location == null) return false;
|
||||
Map<IPath, Boolean> wanted = new LinkedHashMap<>();
|
||||
for (Spec spec : specs) {
|
||||
if (monitor.isCanceled()) throw new OperationCanceledException();
|
||||
IPath relative = spec.path.makeRelativeTo(location);
|
||||
if (relative.isAbsolute() || relative.segmentCount() == 0) continue;
|
||||
IFolder folder = project.getProject().getFolder(relative);
|
||||
refresh(folder, monitor);
|
||||
if (folder.exists()) wanted.put(project.getPath().append(relative), spec.test);
|
||||
}
|
||||
IClasspathEntry[] raw = project.getRawClasspath();
|
||||
List<IClasspathEntry> next = new ArrayList<>();
|
||||
boolean changed = false;
|
||||
for (IClasspathEntry entry : raw) {
|
||||
if (!marked(entry)) {
|
||||
next.add(entry);
|
||||
continue;
|
||||
}
|
||||
if (wanted.containsKey(entry.getPath())) next.add(entry);
|
||||
else changed = true;
|
||||
}
|
||||
for (Map.Entry<IPath, Boolean> entry : wanted.entrySet()) {
|
||||
if (hasSource(next, entry.getKey())) continue;
|
||||
IClasspathAttribute[] attributes = entry.getValue()
|
||||
? new IClasspathAttribute[] {
|
||||
JavaCore.newClasspathAttribute(IClasspathAttribute.TEST, "true"),
|
||||
JavaCore.newClasspathAttribute(MARKER, "true")
|
||||
}
|
||||
: new IClasspathAttribute[] { JavaCore.newClasspathAttribute(MARKER, "true") };
|
||||
next.add(JavaCore.newSourceEntry(entry.getKey(), new IPath[0], new IPath[0], null, attributes));
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) return false;
|
||||
project.setRawClasspath(next.toArray(IClasspathEntry[]::new), monitor);
|
||||
return true;
|
||||
} catch (CoreException | OperationCanceledException e) {
|
||||
JavaLanguageServerPlugin.logException("Adding generated Maven sources to " + project.getElementName(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void refresh(IFolder folder, IProgressMonitor monitor) throws CoreException {
|
||||
IResource resource = folder;
|
||||
while (resource.getType() != IResource.ROOT && !resource.exists()) {
|
||||
IResource parent = resource.getParent();
|
||||
if (parent == null) return;
|
||||
resource = parent;
|
||||
}
|
||||
resource.refreshLocal(IResource.DEPTH_INFINITE, monitor);
|
||||
}
|
||||
|
||||
private static boolean marked(IClasspathEntry entry) {
|
||||
if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) return false;
|
||||
for (IClasspathAttribute attribute : entry.getExtraAttributes()) {
|
||||
if (MARKER.equals(attribute.getName()) && "true".equals(attribute.getValue())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean hasSource(List<IClasspathEntry> entries, IPath path) {
|
||||
for (IClasspathEntry entry : entries) {
|
||||
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && entry.getPath().equals(path)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isMaven(IJavaProject project) {
|
||||
IProject resource = project.getProject();
|
||||
try {
|
||||
return resource.isAccessible() && resource.hasNature(MAVEN);
|
||||
} catch (CoreException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -32,8 +32,7 @@
|
||||
"perf": "node perf/run.ts",
|
||||
"perf:rust": "node perf/rust.ts",
|
||||
"eval": "node evals/run.ts",
|
||||
"release:prepare": "node scripts/release-prepare.ts",
|
||||
"nightly:prepare": "node scripts/nightly-prepare.ts"
|
||||
"release:prepare": "node scripts/release-prepare.ts"
|
||||
},
|
||||
"simple-git-hooks": {
|
||||
"pre-commit": "pnpm lint-staged"
|
||||
|
||||
@@ -2217,8 +2217,10 @@ args = "optional-arguments" # optional
|
||||
`[capabilities]` (a manifest that lists it is refused). On grant the IDE
|
||||
records the jar's content hash and checks it again before every launch; a
|
||||
changed jar is left out, with a line in the console, until the user approves
|
||||
`java.agent` again in Settings › Plugins, which shows the agent's file name
|
||||
and arguments next to the permission. Refusing or revoking it keeps the rest
|
||||
`java.agent` again in Settings › Plugins. Settings shows the agent's file name
|
||||
and arguments next to the permission, and when the jar no longer matches the
|
||||
approved hash it shows the reason and an **Approve new jar** action. Refusing
|
||||
or revoking it keeps the rest
|
||||
of the plugin working, and the next launch has no agent.
|
||||
- The IDE adds one `-javaagent:<absolute path>[=<args>]` argument to the Java
|
||||
command line of **Application**, **Spring Boot** and **JAR Application**
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NIGHTLY_ENDPOINT, nightlyVersion, setNightlyIdentity } from "./nightly-prepare.ts";
|
||||
|
||||
describe("nightlyVersion", () => {
|
||||
it("is one patch above the current version, numbered by its stamp", () => {
|
||||
expect(nightlyVersion("0.1.39", "202611081417")).toBe("0.1.40-nightly.202611081417");
|
||||
});
|
||||
|
||||
it.each([undefined, "", "2026", "012611081417", "20261108141a"])("rejects the stamp %s", (stamp) => {
|
||||
expect(() => nightlyVersion("0.1.39", stamp)).toThrow("stamp");
|
||||
});
|
||||
|
||||
it("rejects a current version that is not a release version", () => {
|
||||
expect(() => nightlyVersion("0.1.40-nightly.202611081417", "202611081417")).toThrow("expected a version");
|
||||
});
|
||||
});
|
||||
|
||||
describe("setNightlyIdentity", () => {
|
||||
const conf = JSON.parse(setNightlyIdentity(readFileSync("src-tauri/tauri.conf.json", "utf8")));
|
||||
|
||||
it("is an app of its own that updates from the nightly manifest", () => {
|
||||
expect(conf.productName).toBe("OpenIDEA Nightly");
|
||||
expect(conf.identifier).toBe("ai.l0ng.openidea.nightly");
|
||||
expect(conf.plugins.updater.endpoints).toEqual([NIGHTLY_ENDPOINT]);
|
||||
});
|
||||
|
||||
it("leaves out the bundles that reject prerelease versions", () => {
|
||||
expect(conf.bundle.targets).not.toContain("msi");
|
||||
expect(conf.bundle.targets).not.toContain("rpm");
|
||||
expect(conf.bundle.createUpdaterArtifacts).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
/**
|
||||
* Prepares a nightly build's commit: `node scripts/nightly-prepare.ts 202611081417` sets the
|
||||
* version one patch above the current one, with that stamp as its prerelease number, in the
|
||||
* files `release:prepare` covers, and gives tauri.conf.json the nightly app's identity, so it
|
||||
* installs next to the stable app and updates from its own manifest. Prints the version.
|
||||
*/
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { cargoVersion, edit, parseVersion, setCargoVersion, setJsonVersion } from "./release-prepare.ts";
|
||||
|
||||
export const NIGHTLY_ENDPOINT = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json";
|
||||
|
||||
/** `0.1.40-nightly.202611081417` from `0.1.39`: always above the last stable version and the last nightly. */
|
||||
export function nightlyVersion(current: string, stamp: string | undefined): string {
|
||||
if (!stamp || !/^[1-9]\d{11}$/.test(stamp)) throw new Error(`expected a YYYYMMDDHHMM stamp, got ${stamp}`);
|
||||
const [major, minor, patch] = parseVersion(current).split(".").map(Number);
|
||||
return `${major}.${minor}.${patch! + 1}-nightly.${stamp}`;
|
||||
}
|
||||
|
||||
/** MSI and RPM reject prerelease versions, so a nightly build leaves them out of its bundles. */
|
||||
export function setNightlyIdentity(json: string): string {
|
||||
const conf = JSON.parse(json);
|
||||
conf.productName = "OpenIDEA Nightly";
|
||||
conf.identifier = "ai.l0ng.openidea.nightly";
|
||||
conf.bundle.targets = ["app", "dmg", "appimage", "deb", "nsis"];
|
||||
conf.plugins.updater.endpoints = [NIGHTLY_ENDPOINT];
|
||||
return `${JSON.stringify(conf, null, 2)}\n`;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const root = fileURLToPath(new URL("..", import.meta.url));
|
||||
const version = nightlyVersion(cargoVersion(readFileSync(join(root, "Cargo.toml"), "utf8")), process.argv[2]);
|
||||
|
||||
edit(join(root, "Cargo.toml"), (text) => setCargoVersion(text, version));
|
||||
edit(join(root, "package.json"), (text) => setJsonVersion(text, version));
|
||||
edit(join(root, "src-tauri/tauri.conf.json"), (text) => setNightlyIdentity(setJsonVersion(text, version)));
|
||||
const cargo = spawnSync("cargo", ["update", "--workspace"], {
|
||||
cwd: root,
|
||||
stdio: ["ignore", 2, 2],
|
||||
});
|
||||
if (cargo.status !== 0) throw new Error("cargo update --workspace failed");
|
||||
console.log(version);
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error(`nightly-prepare: ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -12,66 +12,63 @@ const run = new Function("github", "context", "core", `return (async () => {${sc
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it.each(["v0.1.42", "v0.1.43-nightly.20261112"])(
|
||||
"publishes signed portable updates for both Windows architectures alongside the installers (%s)",
|
||||
async (tag) => {
|
||||
vi.stubEnv("TAG", tag);
|
||||
vi.stubEnv("RELEASE_ID", "42");
|
||||
const version = tag.slice(1);
|
||||
const nightly = tag.includes("-nightly.");
|
||||
const bundles = [
|
||||
"OpenIDEA_aarch64.AppImage",
|
||||
"OpenIDEA_arm64.deb",
|
||||
"OpenIDEA.aarch64.rpm",
|
||||
"OpenIDEA_amd64.AppImage",
|
||||
"OpenIDEA_amd64.deb",
|
||||
"OpenIDEA.x86_64.rpm",
|
||||
"OpenIDEA_aarch64.app.tar.gz",
|
||||
"OpenIDEA_x64.app.tar.gz",
|
||||
"OpenIDEA_arm64_en-US.msi",
|
||||
"OpenIDEA_arm64-setup.exe",
|
||||
"OpenIDEA_x64_en-US.msi",
|
||||
"OpenIDEA_x64-setup.exe",
|
||||
`OpenIDEA_${version}_windows_x64_portable.zip`,
|
||||
`OpenIDEA_${version}_windows_arm64_portable.zip`,
|
||||
].filter((name) => !nightly || (!name.endsWith(".msi") && !name.endsWith(".rpm")));
|
||||
const assets = bundles.flatMap((name, id) => [
|
||||
{ name, id: id * 2 },
|
||||
{ name: `${name}.sig`, id: id * 2 + 1 },
|
||||
]);
|
||||
const upload = vi.fn();
|
||||
const failed = vi.fn();
|
||||
await run(
|
||||
{
|
||||
paginate: async () => assets,
|
||||
rest: {
|
||||
repos: {
|
||||
listReleaseAssets: vi.fn(),
|
||||
getRelease: async () => ({ data: { body: "Release notes" } }),
|
||||
getReleaseAsset: async ({ asset_id }: { asset_id: number }) => ({
|
||||
data: Buffer.from(`signature-${asset_id}\n`),
|
||||
}),
|
||||
uploadReleaseAsset: upload,
|
||||
},
|
||||
it("publishes signed portable updates for both Windows architectures alongside the installers", async () => {
|
||||
const tag = "v0.1.42";
|
||||
vi.stubEnv("TAG", tag);
|
||||
vi.stubEnv("RELEASE_ID", "42");
|
||||
const version = tag.slice(1);
|
||||
const bundles = [
|
||||
"OpenIDEA_aarch64.AppImage",
|
||||
"OpenIDEA_arm64.deb",
|
||||
"OpenIDEA.aarch64.rpm",
|
||||
"OpenIDEA_amd64.AppImage",
|
||||
"OpenIDEA_amd64.deb",
|
||||
"OpenIDEA.x86_64.rpm",
|
||||
"OpenIDEA_aarch64.app.tar.gz",
|
||||
"OpenIDEA_x64.app.tar.gz",
|
||||
"OpenIDEA_arm64_en-US.msi",
|
||||
"OpenIDEA_arm64-setup.exe",
|
||||
"OpenIDEA_x64_en-US.msi",
|
||||
"OpenIDEA_x64-setup.exe",
|
||||
`OpenIDEA_${version}_windows_x64_portable.zip`,
|
||||
`OpenIDEA_${version}_windows_arm64_portable.zip`,
|
||||
];
|
||||
const assets = bundles.flatMap((name, id) => [
|
||||
{ name, id: id * 2 },
|
||||
{ name: `${name}.sig`, id: id * 2 + 1 },
|
||||
]);
|
||||
const upload = vi.fn();
|
||||
const failed = vi.fn();
|
||||
await run(
|
||||
{
|
||||
paginate: async () => assets,
|
||||
rest: {
|
||||
repos: {
|
||||
listReleaseAssets: vi.fn(),
|
||||
getRelease: async () => ({ data: { body: "Release notes" } }),
|
||||
getReleaseAsset: async ({ asset_id }: { asset_id: number }) => ({
|
||||
data: Buffer.from(`signature-${asset_id}\n`),
|
||||
}),
|
||||
uploadReleaseAsset: upload,
|
||||
},
|
||||
},
|
||||
{ repo: { owner: "l0ng-ai", repo: "openidea" } },
|
||||
{ notice: vi.fn(), info: vi.fn(), setFailed: failed },
|
||||
);
|
||||
expect(failed).not.toHaveBeenCalled();
|
||||
const manifest = JSON.parse(upload.mock.calls[0]![0].data);
|
||||
for (const [arch, filename] of [
|
||||
["x86_64", "x64"],
|
||||
["aarch64", "arm64"],
|
||||
]) {
|
||||
const name = `OpenIDEA_${version}_windows_${filename}_portable.zip`;
|
||||
const sig = assets.find((a) => a.name === `${name}.sig`)!;
|
||||
expect(manifest.platforms[`windows-${arch}-portable`]).toEqual({
|
||||
signature: `signature-${sig.id}`,
|
||||
url: `https://github.com/l0ng-ai/openidea/releases/download/${tag}/${name}`,
|
||||
});
|
||||
expect(manifest.platforms[`windows-${arch}`].url).toContain(nightly ? "-setup.exe" : "_en-US.msi");
|
||||
expect(manifest.platforms[`windows-${arch}-nsis`].url).toContain("-setup.exe");
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
{ repo: { owner: "l0ng-ai", repo: "openidea" } },
|
||||
{ notice: vi.fn(), info: vi.fn(), setFailed: failed },
|
||||
);
|
||||
expect(failed).not.toHaveBeenCalled();
|
||||
const manifest = JSON.parse(upload.mock.calls[0]![0].data);
|
||||
for (const [arch, filename] of [
|
||||
["x86_64", "x64"],
|
||||
["aarch64", "arm64"],
|
||||
]) {
|
||||
const name = `OpenIDEA_${version}_windows_${filename}_portable.zip`;
|
||||
const sig = assets.find((a) => a.name === `${name}.sig`)!;
|
||||
expect(manifest.platforms[`windows-${arch}-portable`]).toEqual({
|
||||
signature: `signature-${sig.id}`,
|
||||
url: `https://github.com/l0ng-ai/openidea/releases/download/${tag}/${name}`,
|
||||
});
|
||||
expect(manifest.platforms[`windows-${arch}`].url).toContain("_en-US.msi");
|
||||
expect(manifest.platforms[`windows-${arch}-nsis`].url).toContain("-setup.exe");
|
||||
}
|
||||
});
|
||||
@@ -480,10 +480,9 @@ fn config_endpoints<R: tauri::Runtime>(app: &AppHandle<R>) -> Vec<String> {
|
||||
|
||||
/// The endpoints tried in order: `source` first, the other source when it fails or has
|
||||
/// no manifest. Bundles are signed, so either source's manifest and downloads verify.
|
||||
/// No official endpoint (a build without updates) means no mirror either. Nightly builds
|
||||
/// aren't mirrored: the mirror's manifest would move them to the stable version.
|
||||
fn source_endpoints(official: Vec<String>, source: UpdateSource, nightly: bool) -> Vec<String> {
|
||||
if official.is_empty() || nightly {
|
||||
/// No official endpoint (a build without updates) means no mirror either.
|
||||
fn source_endpoints(official: Vec<String>, source: UpdateSource) -> Vec<String> {
|
||||
if official.is_empty() {
|
||||
return official;
|
||||
}
|
||||
let mirror = vec![CNB_ENDPOINT.to_string()];
|
||||
@@ -493,10 +492,6 @@ fn source_endpoints(official: Vec<String>, source: UpdateSource, nightly: bool)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_nightly(version: &str) -> bool {
|
||||
version.contains("-nightly.")
|
||||
}
|
||||
|
||||
fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plugin_updater::Updater>> {
|
||||
use tauri_plugin_updater::UpdaterExt;
|
||||
if !updates_configured(app) {
|
||||
@@ -504,7 +499,7 @@ fn updater(app: &AppHandle, source: UpdateSource) -> IdeResult<Option<tauri_plug
|
||||
}
|
||||
let endpoints = match update_endpoint_env() {
|
||||
Some(url) => vec![url],
|
||||
None => source_endpoints(config_endpoints(app), source, is_nightly(&app.package_info().version.to_string())),
|
||||
None => source_endpoints(config_endpoints(app), source),
|
||||
};
|
||||
let endpoints = endpoints
|
||||
.iter()
|
||||
@@ -703,7 +698,7 @@ pub async fn app_release_notes(
|
||||
) -> IdeResult<Option<BTreeMap<String, String>>> {
|
||||
let endpoints = match update_endpoint_env() {
|
||||
Some(url) => vec![url],
|
||||
None => source_endpoints(config_endpoints(&app), source, is_nightly(&app.package_info().version.to_string())),
|
||||
None => source_endpoints(config_endpoints(&app), source),
|
||||
};
|
||||
let client = ide_http::client::shared()?;
|
||||
for endpoint in endpoints {
|
||||
@@ -830,22 +825,10 @@ mod tests {
|
||||
#[test]
|
||||
fn chosen_source_is_tried_first_and_the_other_after_it() {
|
||||
let github = "https://github.com/l0ng-ai/openidea/releases/latest/download/latest.json".to_string();
|
||||
assert_eq!(
|
||||
source_endpoints(vec![github.clone()], UpdateSource::Github, false),
|
||||
[github.clone(), CNB_ENDPOINT.into()]
|
||||
);
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb, false), [CNB_ENDPOINT.into(), github]);
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Github), [github.clone(), CNB_ENDPOINT.into()]);
|
||||
assert_eq!(source_endpoints(vec![github.clone()], UpdateSource::Cnb), [CNB_ENDPOINT.into(), github]);
|
||||
// A build without an update endpoint stays without one.
|
||||
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb, false).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_builds_update_from_their_own_manifest_whatever_the_source() {
|
||||
let nightly = "https://github.com/l0ng-ai/openidea/releases/download/nightly/latest.json".to_string();
|
||||
assert_eq!(source_endpoints(vec![nightly.clone()], UpdateSource::Cnb, true), vec![nightly.clone()]);
|
||||
assert_eq!(source_endpoints(vec![nightly.clone()], UpdateSource::Github, true), [nightly]);
|
||||
assert!(is_nightly("0.1.40-nightly.202611081417"));
|
||||
assert!(!is_nightly("0.1.40"));
|
||||
assert!(source_endpoints(Vec::new(), UpdateSource::Cnb).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -29,8 +29,9 @@ pub async fn window_group_select(window: WebviewWindow, label: String) -> IdeRes
|
||||
#[desktop_command(trust = always)]
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn window_group_detach(window: WebviewWindow) -> IdeResult<()> {
|
||||
groups::detach(window.app_handle(), window.label())?;
|
||||
pub async fn window_group_detach(window: WebviewWindow, label: String) -> IdeResult<()> {
|
||||
groups::select(window.app_handle(), window.label(), &label)?;
|
||||
groups::detach(window.app_handle(), &label)?;
|
||||
groups::persist(window.app_handle()).await
|
||||
}
|
||||
|
||||
|
||||
@@ -180,29 +180,6 @@ unsafe extern "C-unwind" fn should_terminate(_this: *mut AnyObject, _selector: S
|
||||
|
||||
static APP: std::sync::OnceLock<AppHandle> = std::sync::OnceLock::new();
|
||||
|
||||
/// Escape the page leaves unhandled reaches the window as `cancelOperation:`, on which NSWindow
|
||||
/// leaves full screen, so pressing Escape once more after closing a popup left full screen. The
|
||||
/// IDE's windows answer it with nothing; View › Appearance › Toggle Full Screen (⌃⌘F) leaves it.
|
||||
pub fn keep_full_screen_on_escape() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| unsafe {
|
||||
let Some(class) = AnyClass::get(c"TaoWindow") else {
|
||||
tracing::warn!("no TaoWindow class: Escape leaves full screen");
|
||||
return;
|
||||
};
|
||||
let imp: Imp = std::mem::transmute(ignore_cancel_operation as CancelOperation);
|
||||
let class = class as *const AnyClass as *mut AnyClass;
|
||||
let added = objc2::ffi::class_addMethod(class, objc2::sel!(cancelOperation:), imp, c"v@:@".as_ptr());
|
||||
if !added.as_bool() {
|
||||
tracing::warn!("could not handle cancelOperation:");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
type CancelOperation = unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject);
|
||||
|
||||
unsafe extern "C-unwind" fn ignore_cancel_operation(_this: *mut AnyObject, _selector: Sel, _sender: *mut AnyObject) {}
|
||||
|
||||
/// Whether AppKit is handling a key press right now. A menu item performed at this point
|
||||
/// was chosen by its key equivalent: a click, arrow keys plus Return and accessibility
|
||||
/// presses all run with a non-key current event.
|
||||
|
||||
@@ -730,8 +730,6 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
|
||||
decorate_csd(&window);
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::page_swipe::install(&window);
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::macos::keep_full_screen_on_escape();
|
||||
apply_zoom(app, &window);
|
||||
#[cfg(target_os = "macos")]
|
||||
align_titlebar(app, &window, app.try_state::<WindowsState>().is_some_and(|w| w.opens_project(window.label())));
|
||||
|
||||
@@ -330,6 +330,7 @@ lsp_java_move trusted project_host bin
|
||||
lsp_java_move_destinations trusted project_host bindings async
|
||||
lsp_java_source_types trusted project_host bindings async
|
||||
lsp_library_sources trusted project_host bindings async
|
||||
lsp_message_request_answer trusted project_host bindings sync
|
||||
lsp_prepare_rename trusted project_host bindings async
|
||||
lsp_prepare_type_hierarchy trusted project_host bindings async
|
||||
lsp_references trusted project_host bindings async
|
||||
|
||||
+39
-4
@@ -790,6 +790,11 @@ export const commands = {
|
||||
/** Set for non-`file:` targets, e.g. `jdt://contents/…`. */
|
||||
uri?: string | null,
|
||||
} | null, IdeError>(__TAURI_INVOKE("lsp_library_sources", { request, uri, pos, sources })),
|
||||
/**
|
||||
* Answers a server's `window/showMessageRequest` question (`null`: dismissed). It runs where the
|
||||
* language server runs: the question waits in that process, a remote project's server included.
|
||||
*/
|
||||
lspMessageRequestAnswer: (id: number, choice: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_message_request_answer", { id, choice })),
|
||||
lspPrepareRename: (doc: DocId, pos: Pos) => typedError<{
|
||||
start: Pos,
|
||||
end: Pos,
|
||||
@@ -1807,7 +1812,7 @@ export const commands = {
|
||||
/** Closes several project tabs one by one (each asks about its own unsaved changes), then selects `keep`. */
|
||||
windowGroupCloseTabs: (keep: string, labels: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_close_tabs", { keep, labels })),
|
||||
windowGroupCurrent: () => typedError<WindowTab[], IdeError>(__TAURI_INVOKE("window_group_current")),
|
||||
windowGroupDetach: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_detach")),
|
||||
windowGroupDetach: (label: string) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_detach", { label })),
|
||||
windowGroupMerge: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_merge")),
|
||||
windowGroupReorder: (labels: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_reorder", { labels })),
|
||||
windowGroupRestore: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_restore")),
|
||||
@@ -3288,8 +3293,12 @@ export type CheckoutOptions = {
|
||||
export type CheckoutOutcome = { kind: "done" } |
|
||||
/** These local changes (repository-relative paths) would be overwritten. */
|
||||
{ kind: "localChanges"; files: string[] } |
|
||||
/** These untracked files (repository-relative paths) would be overwritten. */
|
||||
{ kind: "untrackedFiles"; files: string[] } |
|
||||
/**
|
||||
* These untracked files (repository-relative paths) would be overwritten by the
|
||||
* checkout; with `removed`, they would be removed by it (tracked here, absent
|
||||
* from the target).
|
||||
*/
|
||||
{ kind: "untrackedFiles"; files: string[]; removed: boolean } |
|
||||
/** Local branch `local` has commits that remote branch `remote` does not. */
|
||||
{ kind: "localBranchAhead"; local: string; remote: string } |
|
||||
/**
|
||||
@@ -3574,6 +3583,8 @@ export type CommitSettings = {
|
||||
* `Settings::default()`, or `SettingsStore::set` rejects the key as unknown.
|
||||
*/
|
||||
doubleClickOpensDiff?: boolean | null,
|
||||
/** Team conventions for Generate Commit Message with Agent, added to its prompt. */
|
||||
agentInstructions?: string,
|
||||
};
|
||||
|
||||
export type Commit_Deserialize = {
|
||||
@@ -6619,7 +6630,15 @@ label?: string | null; status: ServerStatus; message: string | null } |
|
||||
* A language server asked clients to re-request one kind of data for its
|
||||
* open documents (`workspace/inlayHint/refresh`, …), e.g. after indexing.
|
||||
*/
|
||||
{ type: "lspRefresh"; server: ServerId; kind: LspRefreshKind } | { type: "terminalExited"; terminal: TerminalId; code: number | null } | { type: "runExited"; run: RunId; code: number | null } | { type: "debug"; session: DebugSessionId; event: DebugEvent } | { type: "notify"; level: NotifyLevel; title: string; body: string | null } |
|
||||
{ type: "lspRefresh"; server: ServerId; kind: LspRefreshKind } |
|
||||
/**
|
||||
* A language server asked the user to choose an action, e.g. Dart's
|
||||
* "Renamed field will be invisible in …" warning during a rename. Answered
|
||||
* with `lsp_message_request_answer`; the server cancels if we reply null.
|
||||
*/
|
||||
{ type: "lspMessageRequest"; id: number; server: string; message: string; actions: string[] } |
|
||||
/** The request was answered or timed out; every window drops its dialog. */
|
||||
{ type: "lspMessageRequestDone"; id: number } | { type: "terminalExited"; terminal: TerminalId; code: number | null } | { type: "runExited"; run: RunId; code: number | null } | { type: "debug"; session: DebugSessionId; event: DebugEvent } | { type: "notify"; level: NotifyLevel; title: string; body: string | null } |
|
||||
/**
|
||||
* A setting was written (any window); the windows it concerns (all for a
|
||||
* global value, the project's for a project value) re-read their effective settings.
|
||||
@@ -8863,6 +8882,8 @@ export type PluginInfo = {
|
||||
homepage: string | null,
|
||||
changeNotes: string | null,
|
||||
icon: PluginIcon | null,
|
||||
/** The Java agent this plugin declares, and whether it is still approved. */
|
||||
javaAgent: PluginJavaAgent | null,
|
||||
source: PluginSource,
|
||||
/** Package directory. */
|
||||
path: IpcPath,
|
||||
@@ -8897,6 +8918,16 @@ export type PluginInfo = {
|
||||
extensionPoints: ExtensionPointInfo[],
|
||||
};
|
||||
|
||||
/** The Java agent a plugin contributes, for Settings › Plugins. */
|
||||
export type PluginJavaAgent = {
|
||||
/** The jar's file name. */
|
||||
fileName: string,
|
||||
/** The optional argument passed after `=`. */
|
||||
args: string | null,
|
||||
/** The jar still has the hash recorded when `java.agent` was granted. */
|
||||
approved: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
* Commands of this module the remote server answers.
|
||||
* Versioned plugin visuals, refreshed after the editor synchronizes its buffer.
|
||||
@@ -10768,6 +10799,10 @@ export type Stash = {
|
||||
index: number,
|
||||
message: string,
|
||||
timeMs: number | null,
|
||||
/** The stash commit; its changes are those against `base`. */
|
||||
id: string,
|
||||
/** The commit the stash was made on (the stash commit's first parent). */
|
||||
base: string | null,
|
||||
};
|
||||
|
||||
/** A plugin's status bar item. */
|
||||
|
||||
@@ -570,14 +570,24 @@ function copyReference(reference: Promise<string>) {
|
||||
}
|
||||
}
|
||||
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
const path = slot.model.path;
|
||||
const { doc, selection } = view.state;
|
||||
const line = doc.lineAt(selection.main.head).number;
|
||||
/** The selected lines (1-based), leaving out the one a selection ends at the start of. */
|
||||
function selectedLines(state: EditorState): { first: number; last: number } {
|
||||
const { doc, selection } = state;
|
||||
const { from, to } = selection.main;
|
||||
// The selected lines, leaving out the one a selection ends at the start of.
|
||||
const first = doc.lineAt(from).number;
|
||||
const last = Math.max(first, doc.lineAt(to).number - (to > from && doc.lineAt(to).from === to ? 1 : 0));
|
||||
return { first, last };
|
||||
}
|
||||
|
||||
/** `path:12`, or `path:12-18` for a selection over several lines. */
|
||||
function pathWithLines(state: EditorState, path: string): string {
|
||||
const { first, last } = selectedLines(state);
|
||||
return `${pathToCopy("relative", path)}:${first}${last > first ? `-${last}` : ""}`;
|
||||
}
|
||||
|
||||
function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
const path = slot.model.path;
|
||||
const { first, last } = selectedLines(view.state);
|
||||
const contributed = menuGroupItems("copyPath", {
|
||||
paths: [path],
|
||||
line: first - 1,
|
||||
@@ -603,7 +613,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) {
|
||||
{
|
||||
id: "editor.copyPathWithLineNumber",
|
||||
label: "Path with line number",
|
||||
value: `${pathToCopy("relative", path)}:${line}`,
|
||||
value: pathWithLines(view.state, path),
|
||||
},
|
||||
];
|
||||
const popup: Extract<LspPopup, { kind: "list" }> = {
|
||||
@@ -1280,12 +1290,7 @@ export function registerEditorActions(): () => void {
|
||||
when: TEXT_WHEN,
|
||||
run: ({ arg }) => {
|
||||
if (typeof arg === "string") copyEditorPath(arg);
|
||||
else
|
||||
withView((view, slot) =>
|
||||
copyEditorPath(
|
||||
`${pathToCopy("relative", slot.model.path)}:${view.state.doc.lineAt(view.state.selection.main.head).number}`,
|
||||
),
|
||||
)();
|
||||
else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path)))();
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -77,6 +77,39 @@ describe("foldsFromRanges", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("hides the closing line of a multiline import at the end of an import run", () => {
|
||||
const s = EditorState.create({
|
||||
doc: [
|
||||
"import { ZodError } from 'zod'",
|
||||
"import { Library } from './library.js'",
|
||||
"import {",
|
||||
" creationPromptVersion,",
|
||||
" generateCreationIntent,",
|
||||
" validateCreationIntent,",
|
||||
" validationPromptVersion,",
|
||||
" type CreationAgentConfig,",
|
||||
" type CreationIntent,",
|
||||
" type IntentValidation,",
|
||||
"} from './mastra/agents/creation-assistant.js'",
|
||||
"",
|
||||
].join("\n"),
|
||||
});
|
||||
expect(foldsFromRanges(s, [{ start_line: 0, end_line: 10, kind: "imports" }])).toEqual([
|
||||
{ from: s.doc.line(1).to, to: s.doc.line(11).to, kind: "imports" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a bare closing delimiter of an import block visible", () => {
|
||||
const go = EditorState.create({ doc: 'package main\n\nimport (\n "fmt"\n "os"\n)\n' });
|
||||
expect(foldsFromRanges(go, [{ start_line: 2, end_line: 5, kind: "imports" }])).toEqual([
|
||||
{ from: go.doc.line(3).to, to: go.doc.line(6).from, kind: "imports" },
|
||||
]);
|
||||
const rust = EditorState.create({ doc: "use a::{\n b,\n c,\n};\n" });
|
||||
expect(foldsFromRanges(rust, [{ start_line: 0, end_line: 3, kind: "imports" }])).toEqual([
|
||||
{ from: rust.doc.line(1).to, to: rust.doc.line(4).from, kind: "imports" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("folds a custom region from its start marker through its end marker", () => {
|
||||
const s = EditorState.create({
|
||||
doc: "class A {\n //region Fields\n int a;\n //endregion\n}\n",
|
||||
|
||||
@@ -65,8 +65,10 @@ export function foldsFromRanges(state: EditorState, ranges: readonly FoldRange[]
|
||||
}
|
||||
const start = allmanHeader(state, first);
|
||||
const trimmed = end.text.trimStart();
|
||||
// `}` / `)` / `]` on the last line stays visible after the placeholder, like IDEA.
|
||||
const to = /^[}\])]/.test(trimmed) ? end.from + (end.text.length - trimmed.length) : end.to;
|
||||
// `}` / `)` / `]` on the last line stays visible after the placeholder, like IDEA. An import
|
||||
// run ending in `} from '…'` hides that whole statement; a bare `)` / `};` still shows.
|
||||
const delimiter = r.kind === "imports" ? /^[}\])]+[;,]?$/.test(trimmed.trimEnd()) : /^[}\])]/.test(trimmed);
|
||||
const to = delimiter ? end.from + (end.text.length - trimmed.length) : end.to;
|
||||
if (to > start.to) out.push({ from: start.to, to, kind: r.kind });
|
||||
}
|
||||
return out.sort((a, b) => a.from - b.from || b.to - a.to);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { LanguageDescription, type Language } from "@codemirror/language";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { logWarning } from "./highlight";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
import { fencedCodeMode, findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
describe("language modes", () => {
|
||||
it("distinguishes PHP classes, method declarations and fields for imported schemes", async () => {
|
||||
@@ -309,4 +310,109 @@ describe("language modes", () => {
|
||||
expect(support?.language).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
const keywordHighlighter = tagHighlighter([{ tag: t.keyword, class: "keyword" }]);
|
||||
|
||||
function keywords(language: Language, source: string) {
|
||||
const found: string[] = [];
|
||||
highlightTree(language.parser.parse(source), keywordHighlighter, (from, to) => found.push(source.slice(from, to)));
|
||||
return found;
|
||||
}
|
||||
|
||||
it("colours TOML keys as keywords in files, lock files and ```toml code blocks", async () => {
|
||||
for (const path of ["/p/Cargo.toml", "/p/uv.lock"]) {
|
||||
const support = await loadSupport(findLanguageDescription("TOML", path)!);
|
||||
expect(keywords(support!.language, '[package]\nname = "x"'), path).toEqual(["package", "name"]);
|
||||
}
|
||||
const fenced = fencedCodeMode("toml")!;
|
||||
expect(fenced.name).toBe("TOML");
|
||||
const language =
|
||||
fenced.language instanceof LanguageDescription ? (await fenced.language.load()).language : fenced.language;
|
||||
expect(keywords(language, 'name = "x"')).toEqual(["name"]);
|
||||
});
|
||||
|
||||
const propertiesHighlighter = tagHighlighter([
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
{ tag: t.operator, class: "operator" },
|
||||
{ tag: t.string, class: "string" },
|
||||
{ tag: t.comment, class: "comment" },
|
||||
{ tag: t.heading, class: "heading" },
|
||||
]);
|
||||
|
||||
function highlightProperties(language: Language, source: string) {
|
||||
const found: Array<[string, string]> = [];
|
||||
highlightTree(language.parser.parse(source), propertiesHighlighter, (from, to, style) =>
|
||||
found.push([source.slice(from, to), style]),
|
||||
);
|
||||
return found;
|
||||
}
|
||||
|
||||
it("colours properties and .env keys as keywords, the first separator as an operator and the whole value as a string", async () => {
|
||||
const support = await loadSupport(findLanguageDescription("Properties files", "/p/.env")!);
|
||||
const source = [
|
||||
"APP_NAME=core-user",
|
||||
"DATABASE_URL=postgres://u:p@h:5432/db",
|
||||
"APP_KEY=base64:abc==",
|
||||
"key = value",
|
||||
"key: value",
|
||||
"export A=b",
|
||||
"# c",
|
||||
"[section]",
|
||||
"a=b\\",
|
||||
" c",
|
||||
"=x",
|
||||
// A blank line ends a continued value.
|
||||
"d=e\\",
|
||||
"",
|
||||
"f=g",
|
||||
].join("\n");
|
||||
expect(highlightProperties(support!.language, source)).toEqual([
|
||||
["APP_NAME", "keyword"],
|
||||
["=", "operator"],
|
||||
["core-user", "string"],
|
||||
["DATABASE_URL", "keyword"],
|
||||
["=", "operator"],
|
||||
["postgres://u:p@h:5432/db", "string"],
|
||||
["APP_KEY", "keyword"],
|
||||
["=", "operator"],
|
||||
["base64:abc==", "string"],
|
||||
["key ", "keyword"],
|
||||
["=", "operator"],
|
||||
[" value", "string"],
|
||||
["key", "keyword"],
|
||||
[":", "operator"],
|
||||
[" value", "string"],
|
||||
["export A", "keyword"],
|
||||
["=", "operator"],
|
||||
["b", "string"],
|
||||
["# c", "comment"],
|
||||
["[section]", "heading"],
|
||||
["a", "keyword"],
|
||||
["=", "operator"],
|
||||
["b\\", "string"],
|
||||
[" c", "string"],
|
||||
["=", "operator"],
|
||||
["x", "string"],
|
||||
["d", "keyword"],
|
||||
["=", "operator"],
|
||||
["e\\", "string"],
|
||||
["f", "keyword"],
|
||||
["=", "operator"],
|
||||
["g", "string"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("colours properties keys in ```ini and ```properties code blocks", async () => {
|
||||
for (const info of ["ini", "properties"]) {
|
||||
const fenced = fencedCodeMode(info)!;
|
||||
expect(fenced.name, info).toBe("Properties files");
|
||||
const language =
|
||||
fenced.language instanceof LanguageDescription ? (await fenced.language.load()).language : fenced.language;
|
||||
expect(highlightProperties(language, "a=b"), info).toEqual([
|
||||
["a", "keyword"],
|
||||
["=", "operator"],
|
||||
["b", "string"],
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -195,6 +195,14 @@ const OWN_MODES = [
|
||||
);
|
||||
},
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: "TOML",
|
||||
load: async () => new LanguageSupport(StreamLanguage.define((await import("./toml")).tomlParser)),
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: "Properties files",
|
||||
load: async () => new LanguageSupport((await import("./properties")).propertiesLanguage),
|
||||
}),
|
||||
LanguageDescription.of({
|
||||
name: "Markdown",
|
||||
extensions: ["md", "markdown", "mkd"],
|
||||
|
||||
@@ -57,6 +57,7 @@ import { stringClipboard } from "./stringClipboard";
|
||||
import { filterCopiedText } from "./clipboard";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { codeLensPositions } from "./codeLens";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
// --- soft wraps ---------------------------------------------------------------
|
||||
|
||||
@@ -452,9 +453,10 @@ export function resetConfiguredEditorsFontZoom(origin: EditorView): void {
|
||||
/** Exported for tests: the ⌘/Ctrl+wheel handler of the prefs compartment. */
|
||||
export const wheelZoom = EditorView.domEventHandlers({
|
||||
wheel(e, view) {
|
||||
if (!e.metaKey && !e.ctrlKey) return false;
|
||||
const step = wheelZoomStep(e);
|
||||
if (step === null) return false;
|
||||
e.preventDefault();
|
||||
stepConfiguredEditorsFontZoom(view, e.deltaY < 0 ? 1 : -1);
|
||||
if (step) stepConfiguredEditorsFontZoom(view, step);
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* `.properties`, `.ini`, `.env` and Godot resources, coloured like IntelliJ's Properties and
|
||||
* DotEnv highlighters: the key is KEYWORD, the first `=` or `:` is OPERATION_SIGN and the rest
|
||||
* of the line (with its continuation lines) is STRING. The legacy mode finds the parts; its
|
||||
* own `def` and `quote` styles would read as a variable and plain text.
|
||||
*/
|
||||
import { StreamLanguage, type StreamParser } from "@codemirror/language";
|
||||
import { properties } from "@codemirror/legacy-modes/mode/properties";
|
||||
|
||||
/** The legacy state with the one field read here, plus the line's separator. */
|
||||
interface State {
|
||||
nextMultiline: boolean;
|
||||
separated: boolean;
|
||||
}
|
||||
|
||||
const parser: StreamParser<State> = {
|
||||
name: properties.name,
|
||||
startState: (indentUnit) => ({ ...(properties.startState!(indentUnit) as State), separated: false }),
|
||||
// CodeMirror skips `token` on empty lines; a blank line ends a continued value.
|
||||
blankLine(state) {
|
||||
state.nextMultiline = false;
|
||||
},
|
||||
token(stream, state) {
|
||||
if (stream.sol() && !state.nextMultiline) state.separated = false;
|
||||
const style = properties.token(stream, state);
|
||||
if (style === "def") return "keyword";
|
||||
if (style === "quote") return "string";
|
||||
// The legacy mode returns null only for `=` and `:`.
|
||||
if (style === null) {
|
||||
if (state.separated) return "string";
|
||||
state.separated = true;
|
||||
return "operator";
|
||||
}
|
||||
return style;
|
||||
},
|
||||
};
|
||||
|
||||
export const propertiesLanguage = StreamLanguage.define(parser);
|
||||
@@ -0,0 +1,337 @@
|
||||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { StreamLanguage } from "@codemirror/language";
|
||||
import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
|
||||
import { tomlParser } from "./toml";
|
||||
|
||||
const language = StreamLanguage.define(tomlParser);
|
||||
|
||||
const highlighter = tagHighlighter([
|
||||
{ tag: t.keyword, class: "keyword" },
|
||||
{ tag: t.string, class: "string" },
|
||||
{ tag: t.number, class: "number" },
|
||||
{ tag: t.standard(t.variableName), class: "builtin" },
|
||||
{ tag: t.comment, class: "comment" },
|
||||
{ tag: t.escape, class: "escape" },
|
||||
{ tag: t.invalid, class: "invalid" },
|
||||
]);
|
||||
|
||||
function highlighted(source: string) {
|
||||
const found: Array<[string, string]> = [];
|
||||
highlightTree(language.parser.parse(source), highlighter, (from, to, style) =>
|
||||
found.push([source.slice(from, to), style]),
|
||||
);
|
||||
return found;
|
||||
}
|
||||
|
||||
describe("TOML highlighting", () => {
|
||||
// IntelliJ's colour settings demo (plugins/toml highlighterDemoText.toml). Its two escape lines
|
||||
// tag only the escapes; the keys and string bodies around them get KEY and STRING there too.
|
||||
it("colours IntelliJ's TOML demo like IntelliJ", () => {
|
||||
const demo = [
|
||||
"# This is a TOML document.",
|
||||
"",
|
||||
'title = "TOML Example"',
|
||||
'description = """',
|
||||
" Multiline",
|
||||
" description",
|
||||
'"""',
|
||||
"date = 2019-11-04T07:32:00-08:00",
|
||||
"",
|
||||
"[database]",
|
||||
'server = "192.168.1.1"',
|
||||
"ports = [ 8001, 8001, 8002 ]",
|
||||
'"connection_max" = 5000',
|
||||
"enabled = true",
|
||||
"",
|
||||
"[servers]",
|
||||
"alpha = { ip = '10.0.0.1', dc = \"eqdc10\" }",
|
||||
"beta = { ip = '10.0.0.2', dc = \"eqdc10\" }",
|
||||
"",
|
||||
"[clients]",
|
||||
'data = [ ["gamma", "delta"], [1.0, 2.0] ]',
|
||||
"",
|
||||
"hosts = [",
|
||||
' "alpha",',
|
||||
' "omega",',
|
||||
"]",
|
||||
"",
|
||||
'valid-escapes = """\\tline \\"1\\"',
|
||||
" line\\u00202",
|
||||
" line 3\\U0000002E",
|
||||
'"""',
|
||||
'invalid-escapes = "\\a \\u20 \\U0020"',
|
||||
].join("\n");
|
||||
expect(highlighted(demo)).toEqual([
|
||||
["# This is a TOML document.", "comment"],
|
||||
["title", "keyword"],
|
||||
['"TOML Example"', "string"],
|
||||
["description", "keyword"],
|
||||
['"""', "string"],
|
||||
[" Multiline", "string"],
|
||||
[" description", "string"],
|
||||
['"""', "string"],
|
||||
["date", "keyword"],
|
||||
["2019-11-04T07:32:00-08:00", "builtin"],
|
||||
["database", "keyword"],
|
||||
["server", "keyword"],
|
||||
['"192.168.1.1"', "string"],
|
||||
["ports", "keyword"],
|
||||
["8001", "number"],
|
||||
["8001", "number"],
|
||||
["8002", "number"],
|
||||
['"connection_max"', "string"],
|
||||
["5000", "number"],
|
||||
["enabled", "keyword"],
|
||||
["true", "builtin"],
|
||||
["servers", "keyword"],
|
||||
["alpha", "keyword"],
|
||||
["ip", "keyword"],
|
||||
["'10.0.0.1'", "string"],
|
||||
["dc", "keyword"],
|
||||
['"eqdc10"', "string"],
|
||||
["beta", "keyword"],
|
||||
["ip", "keyword"],
|
||||
["'10.0.0.2'", "string"],
|
||||
["dc", "keyword"],
|
||||
['"eqdc10"', "string"],
|
||||
["clients", "keyword"],
|
||||
["data", "keyword"],
|
||||
['"gamma"', "string"],
|
||||
['"delta"', "string"],
|
||||
["1.0", "number"],
|
||||
["2.0", "number"],
|
||||
["hosts", "keyword"],
|
||||
['"alpha"', "string"],
|
||||
['"omega"', "string"],
|
||||
["valid-escapes", "keyword"],
|
||||
['"""', "string"],
|
||||
["\\t", "escape"],
|
||||
["line ", "string"],
|
||||
['\\"', "escape"],
|
||||
["1", "string"],
|
||||
['\\"', "escape"],
|
||||
[" line", "string"],
|
||||
["\\u0020", "escape"],
|
||||
["2", "string"],
|
||||
[" line 3", "string"],
|
||||
["\\U0000002E", "escape"],
|
||||
['"""', "string"],
|
||||
["invalid-escapes", "keyword"],
|
||||
['"', "string"],
|
||||
["\\a", "invalid"],
|
||||
[" ", "string"],
|
||||
["\\u", "invalid"],
|
||||
["20 ", "string"],
|
||||
["\\U", "invalid"],
|
||||
['0020"', "string"],
|
||||
]);
|
||||
});
|
||||
|
||||
// IntelliJ's TomlHighlightingAnnotatorTest: numbers, dates and booleans can be keys too.
|
||||
it("colours numbers and dates as values and bare keys of any shape as keys", () => {
|
||||
expect(
|
||||
highlighted(
|
||||
[
|
||||
'k1= "foo"',
|
||||
'k2."k3".k4 = "bar"',
|
||||
'123 = "baz"',
|
||||
'2019-11-08 = "qqq"',
|
||||
"true = 1",
|
||||
"k5 = { k6 = 123, k7 = 2019-11-08 }",
|
||||
"[foo.bar]",
|
||||
].join("\n"),
|
||||
),
|
||||
).toEqual([
|
||||
["k1", "keyword"],
|
||||
['"foo"', "string"],
|
||||
["k2", "keyword"],
|
||||
['"k3"', "string"],
|
||||
["k4", "keyword"],
|
||||
['"bar"', "string"],
|
||||
["123", "keyword"],
|
||||
['"baz"', "string"],
|
||||
["2019-11-08", "keyword"],
|
||||
['"qqq"', "string"],
|
||||
["true", "keyword"],
|
||||
["1", "number"],
|
||||
["k5", "keyword"],
|
||||
["k6", "keyword"],
|
||||
["123", "number"],
|
||||
["k7", "keyword"],
|
||||
["2019-11-08", "builtin"],
|
||||
["foo", "keyword"],
|
||||
["bar", "keyword"],
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["t = 07:32:00", [["07:32:00", "builtin"]]],
|
||||
// A time needs seconds: this is two numbers around a stray colon, as in IntelliJ's lexer.
|
||||
[
|
||||
"t = 07:32",
|
||||
[
|
||||
["07", "number"],
|
||||
["32", "number"],
|
||||
],
|
||||
],
|
||||
[
|
||||
"d = 2019-11-08 # c",
|
||||
[
|
||||
["2019-11-08", "builtin"],
|
||||
["# c", "comment"],
|
||||
],
|
||||
],
|
||||
["d = 1979-05-27 07:32:00Z", [["1979-05-27 07:32:00Z", "builtin"]]],
|
||||
["d = 1979-05-27T00:32:00.999999+07:00", [["1979-05-27T00:32:00.999999+07:00", "builtin"]]],
|
||||
["n = +inf", [["+inf", "number"]]],
|
||||
["n = 1_000", [["1_000", "number"]]],
|
||||
["n = 6.626e-34", [["6.626e-34", "number"]]],
|
||||
["n = 0xdead_beef", [["0xdead_beef", "number"]]],
|
||||
["n = 0o755", [["0o755", "number"]]],
|
||||
["n = 0b1101", [["0b1101", "number"]]],
|
||||
// Not a number (a hex digit has to follow `0x`) or not a boolean: a bare key to IntelliJ's lexer.
|
||||
["n = 0x_1", [["0x_1", "keyword"]]],
|
||||
["b = trueish", [["trueish", "keyword"]]],
|
||||
["s = 'C:\\Users\\nodejs'", [["'C:\\Users\\nodejs'", "string"]]],
|
||||
['s = """"q""""', [['""""q""""', "string"]]],
|
||||
["s = ''''q''''", [["''''q''''", "string"]]],
|
||||
[
|
||||
's = "\\uD800"',
|
||||
[
|
||||
['"', "string"],
|
||||
["\\uD800", "invalid"],
|
||||
['"', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
's = "\\U0010FFFF\\U00110000"',
|
||||
[
|
||||
['"', "string"],
|
||||
["\\U0010FFFF", "escape"],
|
||||
["\\U00110000", "invalid"],
|
||||
['"', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
's = "\\e"',
|
||||
[
|
||||
['"', "string"],
|
||||
["\\e", "invalid"],
|
||||
['"', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
's = "\\\\"',
|
||||
[
|
||||
['"', "string"],
|
||||
["\\\\", "escape"],
|
||||
['"', "string"],
|
||||
],
|
||||
],
|
||||
// A line-ending backslash trims the line break in a multi-line basic string only.
|
||||
[
|
||||
's = """a \\\n b"""',
|
||||
[
|
||||
['"""a ', "string"],
|
||||
["\\", "escape"],
|
||||
[' b"""', "string"],
|
||||
],
|
||||
],
|
||||
// Whitespace may follow that backslash.
|
||||
[
|
||||
's = """a \\ \t\n b"""',
|
||||
[
|
||||
['"""a ', "string"],
|
||||
["\\ \t", "escape"],
|
||||
[' b"""', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
's = "a \\\nb = 1',
|
||||
[
|
||||
['"a ', "string"],
|
||||
["\\", "invalid"],
|
||||
["b", "keyword"],
|
||||
["1", "number"],
|
||||
],
|
||||
],
|
||||
[
|
||||
"k = 'a'.b",
|
||||
[
|
||||
["'a'", "string"],
|
||||
["b", "keyword"],
|
||||
],
|
||||
],
|
||||
[" [dependencies]", [["dependencies", "keyword"]]],
|
||||
["[[bin]]", [["bin", "keyword"]]],
|
||||
[
|
||||
'[ "a b" . c ]',
|
||||
[
|
||||
['"a b"', "string"],
|
||||
["c", "keyword"],
|
||||
],
|
||||
],
|
||||
["x = [{}, 1]", [["1", "number"]]],
|
||||
[
|
||||
"x = [{ a = 1 }, { b = [2, { c = 3 }] }]",
|
||||
[
|
||||
["a", "keyword"],
|
||||
["1", "number"],
|
||||
["b", "keyword"],
|
||||
["2", "number"],
|
||||
["c", "keyword"],
|
||||
["3", "number"],
|
||||
],
|
||||
],
|
||||
[
|
||||
'features = [\n "derive", # serde\n 1,\n]\nb = true',
|
||||
[
|
||||
['"derive"', "string"],
|
||||
["# serde", "comment"],
|
||||
["1", "number"],
|
||||
["b", "keyword"],
|
||||
["true", "builtin"],
|
||||
],
|
||||
],
|
||||
// A nested array at column 0 is no table header.
|
||||
[
|
||||
"x = [\n[1],\n[true]\n]\ny = 2",
|
||||
[
|
||||
["1", "number"],
|
||||
["true", "builtin"],
|
||||
["y", "keyword"],
|
||||
["2", "number"],
|
||||
],
|
||||
],
|
||||
// An unclosed array while typing: the next key line starts over.
|
||||
[
|
||||
'deps = [\n[package]\nname = "x"',
|
||||
[
|
||||
["package", "keyword"],
|
||||
["name", "keyword"],
|
||||
['"x"', "string"],
|
||||
],
|
||||
],
|
||||
[
|
||||
'deps = [\nname = "x"',
|
||||
[
|
||||
["name", "keyword"],
|
||||
['"x"', "string"],
|
||||
],
|
||||
],
|
||||
// An unclosed single-line string ends with its line.
|
||||
[
|
||||
's = "abc\nk = 1',
|
||||
[
|
||||
['"abc', "string"],
|
||||
["k", "keyword"],
|
||||
["1", "number"],
|
||||
],
|
||||
],
|
||||
] as Array<[string, Array<[string, string]>]>)("colours %j", (source, values) => {
|
||||
const found = highlighted(source);
|
||||
const key = source.match(/^[A-Za-z0-9_-]+(?= ?=)/)?.[0];
|
||||
expect(found).toEqual(key ? [[key, "keyword"], ...values] : values);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* TOML coloured like IntelliJ's TOML plugin (TomlHighlighter, TomlHighlightingAnnotator): a bare
|
||||
* key is KEYWORD wherever it stands (headers, dotted keys, inline tables), even when it reads as
|
||||
* a number, date or boolean; booleans and dates are PREDEFINED_SYMBOL; escapes in basic strings
|
||||
* are valid or invalid as in TomlEscapeLexer. `=`, brackets, `,` and `.` stay plain. Values
|
||||
* follow the TOML 1.0 lexer (TomlLexer.flex), so a time needs its seconds.
|
||||
*/
|
||||
import type { StreamParser, StringStream } from "@codemirror/language";
|
||||
|
||||
type Delimiter = '"' | "'" | '"""' | "'''";
|
||||
|
||||
export interface TomlState {
|
||||
/** The string being read; a multi-line one carries over to the next lines. */
|
||||
string: Delimiter | null;
|
||||
/** Open arrays and inline tables, innermost last. */
|
||||
stack: Array<"array" | "inline">;
|
||||
position: "key" | "value";
|
||||
}
|
||||
|
||||
const KEY_PART = String.raw`(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')`;
|
||||
const DOTTED_KEY = String.raw`${KEY_PART}(?:\s*\.\s*${KEY_PART})*`;
|
||||
/** A key/value line ends a container left open by a typo; no valid array or inline table holds one. */
|
||||
const NEW_ENTRY = new RegExp(String.raw`^\s*${DOTTED_KEY}\s*=`);
|
||||
|
||||
const BARE_KEY = /^[A-Za-z0-9_-]+/;
|
||||
const DATE_TIME =
|
||||
/^(?:\d{4}-\d{2}-\d{2}(?:[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?)?|\d{2}:\d{2}:\d{2}(?:\.\d+)?)(?:[Zz]|[+-]\d{2}:\d{2})?/;
|
||||
const BOOLEAN = /^(?:true|false)/;
|
||||
const DEC_INT = String.raw`[-+]?(?:0|[1-9](?:_?\d)*)`;
|
||||
const DIGITS = String.raw`\d(?:_?\d)*`;
|
||||
const NUMBERS = [
|
||||
new RegExp(String.raw`^${DEC_INT}(?:[eE][-+]?${DIGITS}|\.${DIGITS}(?:[eE][-+]?${DIGITS})?)`),
|
||||
/^[-+]?(?:inf|nan)/,
|
||||
/^0x[0-9a-fA-F](?:_?[0-9a-fA-F])*/,
|
||||
/^0o[0-7](?:_?[0-7])*/,
|
||||
/^0b[01](?:_?[01])*/,
|
||||
new RegExp(`^${DEC_INT}`),
|
||||
// Leading zeros: a key in IntelliJ's lexer, a number where a value stands.
|
||||
/^-?\d+/,
|
||||
];
|
||||
|
||||
function matchLength(stream: StringStream, pattern: RegExp): number {
|
||||
const match = stream.match(pattern, false) as RegExpMatchArray | null;
|
||||
return match ? match[0].length : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Numbers, dates and booleans by the longest match, as JFlex picks. A longer bare word is a
|
||||
* bare key to IntelliJ's lexer, which colours it as one wherever it stands.
|
||||
*/
|
||||
function scalar(stream: StringStream): string | null {
|
||||
const word = matchLength(stream, BARE_KEY);
|
||||
const date = matchLength(stream, DATE_TIME);
|
||||
const bool = matchLength(stream, BOOLEAN);
|
||||
const number = Math.max(...NUMBERS.map((pattern) => matchLength(stream, pattern)));
|
||||
const longest = Math.max(date, bool, number);
|
||||
if (longest === 0 || longest < word) {
|
||||
if (!word) {
|
||||
stream.next();
|
||||
return null;
|
||||
}
|
||||
stream.pos += word;
|
||||
return "keyword";
|
||||
}
|
||||
stream.pos += longest;
|
||||
return number === longest ? "number" : "builtin";
|
||||
}
|
||||
|
||||
function isScalarValue(value: number): boolean {
|
||||
return value <= 0xd7ff || (value >= 0xe000 && value <= 0x10ffff);
|
||||
}
|
||||
|
||||
function escape(stream: StringStream, multiline: boolean): string {
|
||||
stream.next();
|
||||
// A line-ending backslash, whitespace after it allowed, trims the line break of a multi-line string.
|
||||
if (multiline && stream.match(/^[ \t]*$/)) return "escape";
|
||||
const ch = stream.next();
|
||||
if (ch === undefined) return "invalid";
|
||||
if (ch === "u" || ch === "U") {
|
||||
const hex = stream.match(ch === "u" ? /^[0-9a-fA-F]{4}/ : /^[0-9a-fA-F]{8}/) as RegExpMatchArray | null;
|
||||
return hex && isScalarValue(parseInt(hex[0], 16)) ? "escape" : "invalid";
|
||||
}
|
||||
return 'btnfr"\\'.includes(ch) ? "escape" : "invalid";
|
||||
}
|
||||
|
||||
function stringBody(stream: StringStream, state: TomlState): string {
|
||||
const delimiter = state.string!;
|
||||
const quote = delimiter.charAt(0);
|
||||
const basic = quote === '"';
|
||||
if (basic && stream.peek() === "\\") return escape(stream, delimiter === '"""');
|
||||
while (!stream.eol()) {
|
||||
if (basic && stream.peek() === "\\") return "string";
|
||||
if (stream.match(delimiter)) {
|
||||
// A multi-line string may end in up to two quotes of its own right before the closing three.
|
||||
if (delimiter.length === 3) for (let i = 0; i < 2 && stream.eat(quote); i++);
|
||||
state.string = null;
|
||||
return "string";
|
||||
}
|
||||
stream.next();
|
||||
}
|
||||
if (delimiter.length === 1) state.string = null;
|
||||
return "string";
|
||||
}
|
||||
|
||||
function openString(stream: StringStream, state: TomlState): boolean {
|
||||
const quote = stream.match(/^(?:"""|'''|"|')/) as RegExpMatchArray | null;
|
||||
if (quote) state.string = quote[0] as Delimiter;
|
||||
return quote !== null;
|
||||
}
|
||||
|
||||
export const tomlParser: StreamParser<TomlState> = {
|
||||
name: "toml",
|
||||
startState: () => ({ string: null, stack: [], position: "key" }),
|
||||
token(stream, state) {
|
||||
if (stream.sol()) {
|
||||
if (state.string === '"' || state.string === "'") state.string = null;
|
||||
if (!state.string && (!state.stack.length || NEW_ENTRY.test(stream.string))) {
|
||||
state.stack = [];
|
||||
state.position = "key";
|
||||
}
|
||||
}
|
||||
if (state.string) return stringBody(stream, state);
|
||||
if (stream.eatSpace()) return null;
|
||||
if (stream.peek() === "#") {
|
||||
stream.skipToEnd();
|
||||
return "comment";
|
||||
}
|
||||
if (openString(stream, state)) return "string";
|
||||
const top = state.stack[state.stack.length - 1];
|
||||
if (state.position === "key") {
|
||||
if (stream.match(BARE_KEY)) return "keyword";
|
||||
const ch = stream.next();
|
||||
if (ch === "=") state.position = "value";
|
||||
else if (ch === "}" && top === "inline") {
|
||||
state.stack.pop();
|
||||
state.position = "value";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const ch = stream.peek();
|
||||
if (ch === "[" || ch === "{") {
|
||||
stream.next();
|
||||
state.stack.push(ch === "[" ? "array" : "inline");
|
||||
if (ch === "{") state.position = "key";
|
||||
return null;
|
||||
}
|
||||
if (ch === "]" || ch === "}") {
|
||||
stream.next();
|
||||
if (top === (ch === "]" ? "array" : "inline")) state.stack.pop();
|
||||
return null;
|
||||
}
|
||||
if (ch === ",") {
|
||||
stream.next();
|
||||
if (top === "inline") state.position = "key";
|
||||
return null;
|
||||
}
|
||||
return scalar(stream);
|
||||
},
|
||||
languageData: { commentTokens: { line: "#" } },
|
||||
};
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getIndentation } from "@codemirror/language";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { findLanguageDescription, loadSupport } from "./languages";
|
||||
|
||||
describe("vue language mode", () => {
|
||||
@@ -23,4 +25,31 @@ describe("vue language mode", () => {
|
||||
expect(tree).toContain("Declaration");
|
||||
expect(tree).not.toContain("SassVariableName");
|
||||
});
|
||||
|
||||
it("indents the top-level <template>'s children only, not <script setup> or <style> code", async () => {
|
||||
const support = await loadSupport(findLanguageDescription("Vue", "/p/a.vue")!);
|
||||
const doc = [
|
||||
"<template>",
|
||||
"<div>",
|
||||
"</div>",
|
||||
"</template>",
|
||||
'<script setup lang="ts">',
|
||||
"const a = 1",
|
||||
"function f() {",
|
||||
"return a",
|
||||
"}",
|
||||
"</script>",
|
||||
"<style>",
|
||||
".a { color: red; }",
|
||||
"</style>",
|
||||
].join("\n");
|
||||
const state = EditorState.create({ doc, extensions: [support!, EditorState.tabSize.of(2)] });
|
||||
const indent = (line: number) => getIndentation(state, state.doc.line(line).from);
|
||||
expect(indent(2)).toBe(2);
|
||||
expect(indent(6)).toBe(0);
|
||||
expect(indent(7)).toBe(0);
|
||||
expect(indent(8)).toBe(2);
|
||||
expect(indent(10)).toBe(0);
|
||||
expect(indent(12)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -4,24 +4,38 @@
|
||||
* stock `vue()` parses every `<style>` as plain CSS, which loses the SCSS
|
||||
* colours.
|
||||
*/
|
||||
import { LanguageSupport } from "@codemirror/language";
|
||||
import { indentNodeProp, LanguageSupport, type LRLanguage, type TreeIndentContext } from "@codemirror/language";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { sassLanguage } from "@codemirror/lang-sass";
|
||||
import { vue } from "@codemirror/lang-vue";
|
||||
|
||||
/**
|
||||
* WebStorm's Vue code style indents the children of the top-level `<template>` only: code in
|
||||
* `<script setup>` or `<style>` starts at the margin, as `npm create vue` writes it.
|
||||
*/
|
||||
function elementIndent(context: TreeIndentContext): number | null {
|
||||
const after = /^(\s*)(<\/)?/.exec(context.textAfter)!;
|
||||
const node = context.node;
|
||||
if (node.to <= context.pos + after[0].length) return context.continue();
|
||||
const tag = node.firstChild?.getChild("TagName");
|
||||
const flat =
|
||||
node.parent?.name === "Document" && !!tag && context.state.sliceDoc(tag.from, tag.to).toLowerCase() !== "template";
|
||||
return context.lineIndent(node.from) + (after[2] || flat ? 0 : context.unit);
|
||||
}
|
||||
|
||||
export function vueLanguage(): LanguageSupport {
|
||||
return vue({
|
||||
base: html({
|
||||
selfClosingTags: true,
|
||||
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
|
||||
// nesting; only an explicit SCSS/Sass dialect re-parses it.
|
||||
nestedLanguages: [
|
||||
{
|
||||
tag: "style",
|
||||
attrs: (a) => a.lang === "scss" || a.lang === "sass",
|
||||
parser: sassLanguage.parser,
|
||||
},
|
||||
],
|
||||
}),
|
||||
const base = html({
|
||||
selfClosingTags: true,
|
||||
// `<style>` without `lang` (or with `lang="css"`) keeps HTML's own CSS
|
||||
// nesting; only an explicit SCSS/Sass dialect re-parses it.
|
||||
nestedLanguages: [
|
||||
{
|
||||
tag: "style",
|
||||
attrs: (a) => a.lang === "scss" || a.lang === "sass",
|
||||
parser: sassLanguage.parser,
|
||||
},
|
||||
],
|
||||
});
|
||||
const language = (base.language as LRLanguage).configure({ props: [indentNodeProp.add({ Element: elementIndent })] });
|
||||
return vue({ base: new LanguageSupport(language, base.support) });
|
||||
}
|
||||
@@ -154,6 +154,18 @@ describe("editor Copy Path/Reference chooser", () => {
|
||||
expect(writeText).toHaveBeenCalledExactlyOnceWith(path);
|
||||
});
|
||||
|
||||
it("copies a selection over several lines as path:first-last", async () => {
|
||||
const view = ctrl.activeSlot!.view!;
|
||||
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("A {}") } });
|
||||
await executeAction("editor.copyPathReference");
|
||||
const item = popup().items.find((item) => item.id === "editor.copyPathWithLineNumber")!;
|
||||
expect(item.preview).toBe("src/A.java:1-2");
|
||||
// A selection that ends at the start of a line leaves that line out.
|
||||
view.dispatch({ selection: { anchor: 0, head: documentText.indexOf("class") } });
|
||||
await executeAction("editor.copyPathWithLineNumber");
|
||||
await vi.waitFor(() => expect(writeText).toHaveBeenLastCalledWith("src/A.java:1"));
|
||||
});
|
||||
|
||||
it("uses path:line off a symbol and ignores stale reference resolution", async () => {
|
||||
ctrl.activeSlot!.view!.dispatch({ selection: { anchor: documentText.length - 1 } });
|
||||
await executeAction("editor.copyPathReference");
|
||||
|
||||
@@ -4,6 +4,7 @@ import { EditorView } from "@codemirror/view";
|
||||
import { useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { fontZoom, resetAllEditorsFontZoom, setFontZoom, stepAllEditorsFontZoom, wheelZoom } from "./cm/prefs";
|
||||
import { resetWheelZoomGesture } from "@/platform/wheelZoom";
|
||||
|
||||
const zoomOf = (view: EditorView) => view.state.field(fontZoom, false);
|
||||
|
||||
@@ -19,6 +20,7 @@ describe("editor font zoom (active editor by default, all editors when configure
|
||||
return view;
|
||||
};
|
||||
beforeEach(() => {
|
||||
resetWheelZoomGesture();
|
||||
resetAllEditorsFontZoom();
|
||||
useProject.setState({ settings: null });
|
||||
});
|
||||
@@ -45,6 +47,16 @@ describe("editor font zoom (active editor by default, all editors when configure
|
||||
expect(zoomOf(second)).toBe(-1);
|
||||
});
|
||||
|
||||
it("doesn't zoom from the inertia of a scroll when ⌘/Ctrl is pressed during it", () => {
|
||||
const view = makeView();
|
||||
const plain = new WheelEvent("wheel", { bubbles: true, cancelable: true, deltaY: -40 });
|
||||
view.contentDOM.dispatchEvent(plain);
|
||||
const coasting = new WheelEvent("wheel", { bubbles: true, cancelable: true, metaKey: true, deltaY: -20 });
|
||||
view.contentDOM.dispatchEvent(coasting);
|
||||
expect(coasting.defaultPrevented).toBe(false);
|
||||
expect(zoomOf(view)).toBe(0);
|
||||
});
|
||||
|
||||
it("zooms every open editor from ⌘/Ctrl+wheel when wheelZoomScope is 'all' (#2480)", () => {
|
||||
useProject.setState({ settings: { editor: { general: { wheelZoomScope: "all" } } } } as never);
|
||||
const first = makeView();
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* The documentation view with its history toolbar, as IDEA's one documentation
|
||||
* component: the F1 popup, the hover and the Documentation tool window show it.
|
||||
*/
|
||||
import { useEffect, useRef, type KeyboardEvent } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import clsx from "clsx";
|
||||
import { useStore } from "zustand";
|
||||
import { IconButton, selectableText } from "@/ui";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import {
|
||||
docLinkHandler,
|
||||
docStep,
|
||||
editDocSource,
|
||||
linkSignatureTypes,
|
||||
moveDocPopupToWindow,
|
||||
type DocHistory,
|
||||
type DocHost,
|
||||
type HoverDoc,
|
||||
} from "./docs";
|
||||
import { renderMarkup } from "./markdown";
|
||||
import styles from "./Popups.module.css";
|
||||
|
||||
export function DomContent({ build, className }: { build: () => HTMLElement; className?: string }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const node = build();
|
||||
el.replaceChildren(node);
|
||||
return () => el.replaceChildren();
|
||||
// Built once per popup.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
return <div ref={ref} className={className} />;
|
||||
}
|
||||
|
||||
export function DocView({ host, history, themeClasses }: { host: DocHost; history: DocHistory; themeClasses: string }) {
|
||||
const entry = history.entries[history.index];
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
|
||||
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
docStep(host, e.key === "ArrowLeft" ? -1 : 1);
|
||||
} else if (e.key === "F4" && entry?.source) {
|
||||
e.preventDefault();
|
||||
void editDocSource(host);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div
|
||||
tabIndex={-1}
|
||||
data-lsp-doc={typeof host === "object" ? "hover" : host}
|
||||
className={clsx(themeClasses, host === "window" ? styles.docWindowFrame : styles.docFrame)}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{entry && (
|
||||
<DomContent
|
||||
key={`${history.index}:${history.entries.length}`}
|
||||
className={clsx(styles.docBody, selectableText)}
|
||||
build={() => {
|
||||
const dom = renderMarkup(entry.markup, entry.language, docLinkHandler(host));
|
||||
linkSignatureTypes(dom, host, entry);
|
||||
return dom;
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div className={styles.docToolbar}>
|
||||
<IconButton
|
||||
icon="arrow-left"
|
||||
size="small"
|
||||
title="Back"
|
||||
shortcut="←"
|
||||
disabled={history.index === 0}
|
||||
onClick={() => docStep(host, -1)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-right"
|
||||
size="small"
|
||||
title="Forward"
|
||||
shortcut="→"
|
||||
disabled={history.index >= history.entries.length - 1}
|
||||
onClick={() => docStep(host, 1)}
|
||||
/>
|
||||
<span className={styles.spacer} />
|
||||
{entry?.source && (
|
||||
<IconButton
|
||||
icon="edit"
|
||||
size="small"
|
||||
title="Edit Source"
|
||||
shortcut="F4"
|
||||
onClick={() => void editDocSource(host)}
|
||||
/>
|
||||
)}
|
||||
{host !== "window" && (
|
||||
<IconButton
|
||||
icon="open-in-tool-window"
|
||||
size="small"
|
||||
title="Show in Documentation Tool Window"
|
||||
shortcut={(host === "popup" && shortcutLabel("code.quickDocumentation")) || undefined}
|
||||
onClick={() => moveDocPopupToWindow(host)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HoverDocView({ doc }: { doc: HoverDoc }) {
|
||||
return <DocView host={doc} history={useStore(doc)} themeClasses="" />;
|
||||
}
|
||||
|
||||
/** Mounts a hover's documentation into its CodeMirror tooltip; returns its unmount. */
|
||||
export function mountHoverDoc(el: HTMLElement, doc: HoverDoc): () => void {
|
||||
const root = createRoot(el);
|
||||
root.render(<HoverDocView doc={doc} />);
|
||||
return () => queueMicrotask(() => root.unmount());
|
||||
}
|
||||
@@ -232,10 +232,11 @@
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
|
||||
/* Fits its content up to a cap; resized (`data-resized`), it keeps that size and the body scrolls. */
|
||||
.docPopup {
|
||||
max-width: min(600px, 90vw);
|
||||
max-height: 420px;
|
||||
overflow: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.docScope {
|
||||
display: contents;
|
||||
@@ -243,6 +244,24 @@
|
||||
.docFrame {
|
||||
outline: none;
|
||||
}
|
||||
.docPopup .docFrame {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.docPopup:not([data-resized]) .docFrame {
|
||||
max-width: min(600px, 90vw);
|
||||
max-height: 420px;
|
||||
}
|
||||
.docPopup .docBody {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
.docPopup .docToolbar {
|
||||
flex: none;
|
||||
}
|
||||
.docWindowFrame {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
@@ -271,6 +290,13 @@
|
||||
.docBody {
|
||||
padding: 10px 14px;
|
||||
}
|
||||
/* Go signatures: a type name opens its documentation (`linkSignatureTypes` in docs.ts). */
|
||||
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName) {
|
||||
cursor: pointer;
|
||||
}
|
||||
.docBody :global(.cm-lsp-markdown > pre:first-of-type > code.language-go .tok-typeName:hover) {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.defPopup {
|
||||
width: min(640px, 90vw);
|
||||
max-height: 460px;
|
||||
|
||||
@@ -16,9 +16,14 @@ vi.mock("@/workbench/contributions", async (orig) => {
|
||||
|
||||
const { LspPopups, DocumentationWindow } = await import("./Popups");
|
||||
const { closePopup, openPopup, useLspPopup } = await import("./popupStore");
|
||||
const { useDocWindow, pushHistory, stepHistory, hoverCandidates } = await import("./docs");
|
||||
const { useDocWindow, hoverDoc, pushHistory, stepHistory, hoverCandidates } = await import("./docs");
|
||||
const { mountHoverDoc } = await import("./DocView");
|
||||
const { hoverSource } = await import("./hover");
|
||||
import popupStyles from "./Popups.module.css";
|
||||
import { registerImportsOnPasteActions } from "./importsOnPaste";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { CONTRIBUTED_HOVER, type ContributedHover } from "@/editor/api";
|
||||
|
||||
const loc = (path: string, line: number): Location => ({
|
||||
path,
|
||||
@@ -252,6 +257,77 @@ describe("documentation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("hover documentation", () => {
|
||||
const text = (value: string) => ({ markup: { kind: "plaintext" as const, value }, language: null });
|
||||
const frame = (el: Element) => el.querySelector<HTMLElement>('[data-lsp-doc="hover"]')!;
|
||||
afterEach(() => document.body.replaceChildren());
|
||||
|
||||
it("shows the hovered documentation in the same view as F1's", async () => {
|
||||
const docHover: ContributedHover = (state, pos) => {
|
||||
const w = state.wordAt(pos);
|
||||
return w ? { from: w.from, to: w.to, markdown: "hovered docs" } : null;
|
||||
};
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "query.FlightPlan",
|
||||
extensions: [EditorState.languageData.of(() => [{ [CONTRIBUTED_HOVER]: docHover }])],
|
||||
}),
|
||||
parent: document.body.appendChild(document.createElement("div")),
|
||||
});
|
||||
const tooltip = await hoverSource(view, 2);
|
||||
let created!: { dom: HTMLElement; destroy: () => void };
|
||||
await act(async () => {
|
||||
created = tooltip!.create() as typeof created;
|
||||
document.body.appendChild(created.dom);
|
||||
});
|
||||
expect(frame(created.dom).textContent).toContain("hovered docs");
|
||||
expect(screen.getByRole("button", { name: "Back" })).toBeTruthy();
|
||||
created.destroy();
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it("walks its history with ← / →; Edit Source closes the hover", async () => {
|
||||
const close = vi.fn();
|
||||
const source = vi.fn(async () => loc("/p/b.ts", 3));
|
||||
const doc = hoverDoc(text("first"), close);
|
||||
doc.setState({ entries: [text("first"), { ...text("second"), source }], index: 1 });
|
||||
const el = document.body.appendChild(document.createElement("div"));
|
||||
await act(async () => void mountHoverDoc(el, doc));
|
||||
expect(frame(el).textContent).toContain("second");
|
||||
fireEvent.keyDown(frame(el), { key: "ArrowLeft" });
|
||||
expect(frame(el).textContent).toContain("first");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Forward" }));
|
||||
expect(frame(el).textContent).toContain("second");
|
||||
fireEvent.keyDown(frame(el), { key: "F4" });
|
||||
await vi.waitFor(() =>
|
||||
expect(openFile).toHaveBeenCalledWith("/p/b.ts", { selection: { line: 3, col: 4 }, focus: true }),
|
||||
);
|
||||
expect(close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps each hover's history apart (an editor shown again brings its hover back)", async () => {
|
||||
const [a, b] = [hoverDoc(text("in a.go"), vi.fn()), hoverDoc(text("in b.rs"), vi.fn())];
|
||||
const [elA, elB] = [0, 1].map(() => document.body.appendChild(document.createElement("div")));
|
||||
await act(async () => {
|
||||
mountHoverDoc(elA!, a);
|
||||
mountHoverDoc(elB!, b);
|
||||
});
|
||||
await act(async () => b.setState({ entries: [text("in b.rs"), text("followed in b.rs")], index: 1 }));
|
||||
expect(frame(elA!).textContent).toContain("in a.go");
|
||||
expect(frame(elB!).textContent).toContain("followed in b.rs");
|
||||
});
|
||||
|
||||
it("moves its history to the Documentation tool window", async () => {
|
||||
const close = vi.fn();
|
||||
const el = document.body.appendChild(document.createElement("div"));
|
||||
await act(async () => void mountHoverDoc(el, hoverDoc(text("hovered"), close)));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show in Documentation Tool Window" }));
|
||||
expect(close).toHaveBeenCalled();
|
||||
expect(show).toHaveBeenCalledWith("documentation", true);
|
||||
expect(useDocWindow.getState().entries[0]?.markup.value).toBe("hovered");
|
||||
});
|
||||
});
|
||||
|
||||
describe("quick definition popup", () => {
|
||||
it("switches between several definitions with ← / → and edits the source with F4", () => {
|
||||
openPopup({
|
||||
|
||||
@@ -28,17 +28,9 @@ import {
|
||||
type ListPreview,
|
||||
type LspPopup,
|
||||
} from "./popupStore";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import {
|
||||
docLinkHandler,
|
||||
docStep,
|
||||
editDocSource,
|
||||
moveDocPopupToWindow,
|
||||
useDocWindow,
|
||||
type DocHistory,
|
||||
type DocHost,
|
||||
} from "./docs";
|
||||
import { renderCode, renderMarkup } from "./markdown";
|
||||
import { DOC_MIN_HEIGHT, DOC_MIN_WIDTH, loadDocSize, saveDocSize, useDocWindow } from "./docs";
|
||||
import { DocView, DomContent } from "./DocView";
|
||||
import { renderCode } from "./markdown";
|
||||
import { describeSummary } from "./workspaceEdit";
|
||||
import { useUsagesStatus } from "./navigation";
|
||||
import styles from "./Popups.module.css";
|
||||
@@ -352,90 +344,6 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
|
||||
);
|
||||
}
|
||||
|
||||
function DomContent({ build, className }: { build: () => HTMLElement; className?: string }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const node = build();
|
||||
el.replaceChildren(node);
|
||||
return () => el.replaceChildren();
|
||||
// Built once per popup.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
return <div ref={ref} className={className} />;
|
||||
}
|
||||
|
||||
/** Documentation with its history toolbar; shared by the popup and the Documentation tool window. */
|
||||
function DocView({ host, history, themeClasses }: { host: DocHost; history: DocHistory; themeClasses: string }) {
|
||||
const entry = history.entries[history.index];
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
|
||||
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
docStep(host, e.key === "ArrowLeft" ? -1 : 1);
|
||||
} else if (e.key === "F4" && entry?.source) {
|
||||
e.preventDefault();
|
||||
void editDocSource(host);
|
||||
}
|
||||
};
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
tabIndex={-1}
|
||||
data-lsp-doc={host}
|
||||
className={clsx(themeClasses, host === "popup" ? styles.docFrame : styles.docWindowFrame)}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{entry && (
|
||||
<DomContent
|
||||
key={`${history.index}:${history.entries.length}`}
|
||||
className={clsx(styles.docBody, selectableText)}
|
||||
build={() => renderMarkup(entry.markup, entry.language, docLinkHandler(host))}
|
||||
/>
|
||||
)}
|
||||
<div className={styles.docToolbar}>
|
||||
<IconButton
|
||||
icon="arrow-left"
|
||||
size="small"
|
||||
title="Back"
|
||||
shortcut="←"
|
||||
disabled={history.index === 0}
|
||||
onClick={() => docStep(host, -1)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-right"
|
||||
size="small"
|
||||
title="Forward"
|
||||
shortcut="→"
|
||||
disabled={history.index >= history.entries.length - 1}
|
||||
onClick={() => docStep(host, 1)}
|
||||
/>
|
||||
<span className={styles.spacer} />
|
||||
{entry?.source && (
|
||||
<IconButton
|
||||
icon="edit"
|
||||
size="small"
|
||||
title="Edit Source"
|
||||
shortcut="F4"
|
||||
onClick={() => void editDocSource(host)}
|
||||
/>
|
||||
)}
|
||||
{host === "popup" && (
|
||||
<IconButton
|
||||
icon="open-in-tool-window"
|
||||
size="small"
|
||||
title="Show in Documentation Tool Window"
|
||||
shortcut={shortcutLabel("code.quickDocumentation") || undefined}
|
||||
onClick={() => moveDocPopupToWindow()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
|
||||
const focusSeq = useLspPopup((s) => s.focusSeq);
|
||||
const scope = useRef<HTMLDivElement>(null);
|
||||
@@ -444,6 +352,7 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
|
||||
if (focusSeq !== opened.current)
|
||||
scope.current?.querySelector<HTMLElement>("[data-lsp-doc]")?.focus({ preventScroll: true });
|
||||
}, [focusSeq]);
|
||||
const [initialSize] = useState(loadDocSize);
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
@@ -453,6 +362,11 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
|
||||
className={styles.docPopup}
|
||||
// As in IDEA the popup leaves the keyboard to the editor until F1 focuses it.
|
||||
autoFocus={false}
|
||||
resizable="both"
|
||||
minWidth={DOC_MIN_WIDTH}
|
||||
minHeight={DOC_MIN_HEIGHT}
|
||||
initialSize={initialSize}
|
||||
onResized={saveDocSize}
|
||||
>
|
||||
<div ref={scope} data-testid="doc-popup" className={styles.docScope}>
|
||||
<DocView host="popup" history={popup} themeClasses={popup.themeClasses} />
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { WorkspaceSymbol } from "@/bindings";
|
||||
|
||||
const GOROOT = "/go/src";
|
||||
const files: Record<string, string> = {
|
||||
"/p/cmd/main.go": 'package main\n\nimport (\n\t"fmt"\n\tst "example.com/p/store"\n\t_ "embed"\n)\n',
|
||||
"/p/store/store.go": 'package store\n\nimport "time"\n\ntype Note struct{ At time.Time }\n',
|
||||
"/p/conv/conv.go": 'package conv\n\nimport (\n\tam "example.com/p/a/model"\n\tbm "example.com/p/b/model"\n)\n',
|
||||
[`${GOROOT}/builtin/builtin.go`]:
|
||||
"package builtin\n\n// bool is…\ntype bool bool\n\nconst (\n\ttrue = 0 == 0\n)\n\ntype error interface {\n\tError() string\n}\n\nfunc len(v Type) int\n",
|
||||
};
|
||||
|
||||
const sym = (name: string, container: string, path: string, line = 3): WorkspaceSymbol => ({
|
||||
name,
|
||||
kind: "struct",
|
||||
container,
|
||||
location: { path, range: { start: { line, col: 5 }, end: { line, col: 9 } } },
|
||||
});
|
||||
|
||||
// What gopls answers per query (names come back qualified as the query is).
|
||||
const index: Record<string, WorkspaceSymbol[]> = {
|
||||
"fmt.Println": [
|
||||
sym("fmt.Println", "fmt", "/go/src/fmt/print.go", 305),
|
||||
sym("fmt.Fprintln", "fmt", "/go/src/fmt/print.go"),
|
||||
],
|
||||
"log.Logger.Printf": [sym("log.Logger.Printf", "log", "/go/src/log/log.go", 265)],
|
||||
"store.Note": [sym("store.Note", "example.com/p/store", "/p/store/store.go", 4)],
|
||||
"time.Time": [sym("time.Time", "time", "/go/src/time/time.go", 135)],
|
||||
Note: [
|
||||
sym("Note", "example.com/p/store", "/p/store/store.go", 4),
|
||||
sym("Note", "example.com/p/other", "/p/other/x.go"),
|
||||
],
|
||||
"model.Item": [
|
||||
sym("model.Item", "example.com/p/a/model", "/p/a/model/model.go"),
|
||||
sym("model.Item", "example.com/p/b/model", "/p/b/model/model.go"),
|
||||
],
|
||||
"yaml.Node": [sym("yaml.Node", "gopkg.in/yaml.v3", "/mod/yaml/yaml.go")],
|
||||
};
|
||||
const queries: string[] = [];
|
||||
|
||||
vi.mock("@tauri-apps/api/core", () => ({ Channel: class {} }));
|
||||
vi.mock("@/platform/ipc", async (orig) => ({
|
||||
...(await orig<typeof import("@/platform/ipc")>()),
|
||||
commands: {
|
||||
lspWorkspaceSymbols: async (_id: number, q: string) => {
|
||||
queries.push(q);
|
||||
return { status: "ok", data: index[q] ?? [] };
|
||||
},
|
||||
sdkProjectLibraries: async () => ({
|
||||
status: "ok",
|
||||
data: [{ name: "Go SDK", kind: "go", roots: [{ name: "src", path: GOROOT }] }],
|
||||
}),
|
||||
},
|
||||
}));
|
||||
vi.mock("../files", () => ({ readFileLines: async (p: string) => files[p]?.split("\n") ?? null }));
|
||||
|
||||
const { goImports, goPackageName, pkgGoDevLink, resolveGoRef, findInPackage, signatureRef } = await import("./go");
|
||||
|
||||
describe("pkg.go.dev links", () => {
|
||||
it.each([
|
||||
["https://pkg.go.dev/fmt#Println", { importPath: "fmt", name: "Println" }],
|
||||
["https://pkg.go.dev/log#Logger.Printf", { importPath: "log", name: "Logger.Printf" }],
|
||||
[
|
||||
"https://pkg.go.dev/golang.org/x/[email protected]/language#Tag",
|
||||
{ importPath: "golang.org/x/text/language", name: "Tag" },
|
||||
],
|
||||
["https://pkg.go.dev/fmt", null],
|
||||
["https://pkg.go.dev/fmt#hdr-Printing", null],
|
||||
["https://go.dev/doc#Println", null],
|
||||
["file:///go/src/fmt/print.go#L1", null],
|
||||
])("%s", (href, want) => expect(pkgGoDevLink(href)).toEqual(want));
|
||||
|
||||
it.each([
|
||||
["fmt", "Println", { path: "/go/src/fmt/print.go", line: 305, col: 5 }],
|
||||
["log", "Logger.Printf", { path: "/go/src/log/log.go", line: 265, col: 5 }],
|
||||
["example.com/nowhere", "Missing", null],
|
||||
])("finds %s#%s only by its exact name in that package", async (path, name, want) => {
|
||||
expect(await findInPackage(path, name)).toEqual(want);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Go names", () => {
|
||||
it("reads import names, aliases and package names", () => {
|
||||
expect([...goImports(files["/p/cmd/main.go"]!)]).toEqual([
|
||||
["fmt", "fmt"],
|
||||
["st", "example.com/p/store"],
|
||||
]);
|
||||
expect([...goImports('package x\nimport y "a/b"\nimport "c/d.v2"')]).toEqual([
|
||||
["y", "a/b"],
|
||||
["d", "c/d.v2"],
|
||||
]);
|
||||
expect(["gopkg.in/yaml.v3", "github.com/google/go-cmp/cmp", "x/go-redis/v9", "a/b-go"].map(goPackageName)).toEqual([
|
||||
"yaml",
|
||||
"cmp",
|
||||
"redis",
|
||||
"b",
|
||||
]);
|
||||
});
|
||||
|
||||
it("splits a qualified name in a signature", () => {
|
||||
const text = "func (s *st.Store) Get(id int) (st.Note, error)";
|
||||
expect(signatureRef(text, 12, 17)).toEqual({ qualifier: "st", name: "Store" });
|
||||
expect(signatureRef(text, 26, 29)).toEqual({ qualifier: null, name: "int" });
|
||||
});
|
||||
|
||||
const current = "/p/cmd/main.go";
|
||||
it.each<
|
||||
[string, { qualifier: string | null; name: string }, { declaring: string | null; current: string | null }, unknown]
|
||||
>([
|
||||
[
|
||||
"alias of the file asked in",
|
||||
{ qualifier: "st", name: "Note" },
|
||||
{ declaring: null, current },
|
||||
"/p/store/store.go",
|
||||
],
|
||||
[
|
||||
"import of the declaring file",
|
||||
{ qualifier: "time", name: "Time" },
|
||||
{ declaring: "/p/store/store.go", current },
|
||||
"/go/src/time/time.go",
|
||||
],
|
||||
[
|
||||
"package no file imports, unique",
|
||||
{ qualifier: "yaml", name: "Node" },
|
||||
{ declaring: null, current },
|
||||
"/mod/yaml/yaml.go",
|
||||
],
|
||||
["same package name twice: ambiguous", { qualifier: "model", name: "Item" }, { declaring: null, current }, null],
|
||||
[
|
||||
"unqualified, in the declaring package",
|
||||
{ qualifier: null, name: "Note" },
|
||||
{ declaring: "/p/store/store.go", current },
|
||||
"/p/store/store.go",
|
||||
],
|
||||
[
|
||||
"unqualified, not in that package",
|
||||
{ qualifier: null, name: "Note" },
|
||||
{ declaring: "/p/cmd/main.go", current },
|
||||
null,
|
||||
],
|
||||
["not found", { qualifier: "st", name: "Missing" }, { declaring: null, current }, null],
|
||||
[
|
||||
"builtin type",
|
||||
{ qualifier: null, name: "error" },
|
||||
{ declaring: null, current },
|
||||
`${GOROOT}/builtin/builtin.go:9:5`,
|
||||
],
|
||||
[
|
||||
"builtin constant",
|
||||
{ qualifier: null, name: "true" },
|
||||
{ declaring: null, current },
|
||||
`${GOROOT}/builtin/builtin.go:6:1`,
|
||||
],
|
||||
[
|
||||
"builtin function",
|
||||
{ qualifier: null, name: "len" },
|
||||
{ declaring: null, current },
|
||||
`${GOROOT}/builtin/builtin.go:13:5`,
|
||||
],
|
||||
])("%s", async (_, ref, ctx, want) => {
|
||||
const t = await resolveGoRef(ref, ctx);
|
||||
const got = t && (t.path.includes("builtin") ? `${t.path}:${t.line}:${t.col}` : t.path);
|
||||
expect(got).toEqual(want);
|
||||
});
|
||||
|
||||
it("an alias meaning different packages in the two files is ambiguous", async () => {
|
||||
files["/p/other.go"] = 'package other\n\nimport st "example.com/p/stuff"\n';
|
||||
expect(await resolveGoRef({ qualifier: "st", name: "Note" }, { declaring: "/p/other.go", current })).toBeNull();
|
||||
expect(queries).not.toContain("stuff.Note");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Go documentation links (gopls), resolved to declarations through `workspace/symbol`
|
||||
* so their documentation opens in place, as in GoLand:
|
||||
* - `https://pkg.go.dev/<import path>#<Name>` (or `#<Type>.<Method>`) links;
|
||||
* - type names in a signature: `pkg.Name` by the import the qualifier names, `Name` in the
|
||||
* documented symbol's package, predeclared names (`string`, `error`…) in `builtin`.
|
||||
* Only a unique exact match counts: nothing is guessed from the name alone.
|
||||
*/
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import { call, commands, nextRequestId, type LibraryGroup, type WorkspaceSymbol } from "@/platform/ipc";
|
||||
import { symbols, unique, type DocTarget } from "./symbols";
|
||||
import { dirname } from "@/platform/project";
|
||||
import { readFileLines } from "../files";
|
||||
|
||||
/** A name in a Go signature: `pkg.Name` (`qualifier` = `pkg`) or `Name`. */
|
||||
export interface GoRef {
|
||||
qualifier: string | null;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/** Where a signature comes from: its declaration's file and the file the documentation was asked in. */
|
||||
export interface GoRefContext {
|
||||
declaring: string | null;
|
||||
current: string | null;
|
||||
}
|
||||
|
||||
const IDENT = "[A-Za-z_][A-Za-z0-9_]*";
|
||||
|
||||
/** `https://pkg.go.dev/<import path>[@version]#<Name>` or `#<Type>.<Method>`; null for other links. */
|
||||
export function pkgGoDevLink(href: string): { importPath: string; name: string } | null {
|
||||
// Malformed URLs and escapes are no links.
|
||||
try {
|
||||
const url = new URL(href);
|
||||
if (url.hostname !== "pkg.go.dev") return null;
|
||||
const name = decodeURIComponent(url.hash.slice(1));
|
||||
const importPath = decodeURIComponent(url.pathname.slice(1)).replace(/@[^/]*/, "");
|
||||
if (!importPath || !new RegExp(`^${IDENT}(\\.${IDENT})?$`).test(name)) return null;
|
||||
return { importPath, name };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The package name an import path usually declares (`…/yaml.v3` → `yaml`, `…/go-cmp/v2` → `cmp`).
|
||||
* ponytail: a heuristic, used only to query and for packages no file at hand imports.
|
||||
*/
|
||||
export function goPackageName(importPath: string): string {
|
||||
const parts = importPath.split("/");
|
||||
let last = parts[parts.length - 1] ?? "";
|
||||
if (/^v\d+$/.test(last) && parts.length > 1) last = parts[parts.length - 2]!;
|
||||
return last
|
||||
.replace(/\.v\d+$/, "")
|
||||
.replace(/^go-|-go$/, "")
|
||||
.replace(/\W/g, "_");
|
||||
}
|
||||
|
||||
/** Import name → import path of a Go file's imports (aliases, groups; `_` and `.` imports skipped). */
|
||||
export function goImports(text: string): Map<string, string> {
|
||||
const imports = new Map<string, string>();
|
||||
const spec = new RegExp(`^\\s*(?:(${IDENT}|\\.)\\s+)?"([^"]+)"`);
|
||||
for (const m of text.matchAll(/^import\s*(?:\(([\s\S]*?)\)|(.*))$/gm)) {
|
||||
for (const line of (m[1] ?? m[2] ?? "").split("\n")) {
|
||||
const s = spec.exec(line);
|
||||
if (!s || s[1] === "_" || s[1] === ".") continue;
|
||||
imports.set(s[1] ?? goPackageName(s[2]!), s[2]!);
|
||||
}
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
|
||||
/** The name at [from, to) of a signature's text, with the `pkg.` written before it. */
|
||||
export function signatureRef(text: string, from: number, to: number): GoRef {
|
||||
const q = new RegExp(`(?:^|[^\\w.])(${IDENT})\\.$`).exec(text.slice(0, from));
|
||||
return { qualifier: q?.[1] ?? null, name: text.slice(from, to) };
|
||||
}
|
||||
|
||||
const PREDECLARED = new Set(
|
||||
(
|
||||
"any bool byte comparable complex64 complex128 error float32 float64 int int8 int16 int32 int64 rune " +
|
||||
"string uint uint8 uint16 uint32 uint64 uintptr true false iota nil append cap clear close complex " +
|
||||
"copy delete imag len make max min new panic print println real recover"
|
||||
).split(" "),
|
||||
);
|
||||
|
||||
/** Whether `s` is `name` itself, as found by a query qualified with `qualifier` or not. */
|
||||
function named(s: WorkspaceSymbol, qualifier: string, name: string): boolean {
|
||||
return s.name === name || s.name === `${qualifier}.${name}`;
|
||||
}
|
||||
|
||||
/** `name` (`Name` or `Type.Method`) declared in the package at `importPath`. */
|
||||
export async function findInPackage(importPath: string, name: string): Promise<DocTarget | null> {
|
||||
const pkg = goPackageName(importPath);
|
||||
const inPackage = (list: WorkspaceSymbol[]) => list.filter((s) => s.container === importPath && named(s, pkg, name));
|
||||
const hits = inPackage(await symbols(`${pkg}.${name}`));
|
||||
return unique(hits.length ? hits : inPackage(await symbols(name)));
|
||||
}
|
||||
|
||||
async function importsOf(path: string | null): Promise<Map<string, string>> {
|
||||
const lines = path ? await readFileLines(path).catch(() => null) : null;
|
||||
return goImports(lines?.join("\n") ?? "");
|
||||
}
|
||||
|
||||
async function goSourceRoot(): Promise<string | null> {
|
||||
const groups = await call(commands.sdkProjectLibraries(nextRequestId(), new Channel<LibraryGroup[]>())).catch(
|
||||
() => [],
|
||||
);
|
||||
return groups.find((g) => g.kind === "go")?.roots[0]?.path ?? null;
|
||||
}
|
||||
|
||||
/** A predeclared name's declaration in `$GOROOT/src/builtin/builtin.go`. */
|
||||
async function builtin(name: string): Promise<DocTarget | null> {
|
||||
const src = await goSourceRoot();
|
||||
if (!src) return null;
|
||||
const path = `${src}/builtin/builtin.go`;
|
||||
const lines = (await readFileLines(path).catch(() => null)) ?? [];
|
||||
const decl = new RegExp(`^(?:(?:type|func|var|const)\\s+|\\t)(${name})\\b`);
|
||||
for (let line = 0; line < lines.length; line++) {
|
||||
const m = decl.exec(lines[line]!);
|
||||
if (m) return { path, line, col: m[0].length - name.length };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Where a name in a Go signature is declared; null when it isn't found exactly once. */
|
||||
export async function resolveGoRef(ref: GoRef, ctx: GoRefContext): Promise<DocTarget | null> {
|
||||
const { qualifier, name } = ref;
|
||||
if (!qualifier) {
|
||||
if (PREDECLARED.has(name)) return builtin(name);
|
||||
const file = ctx.declaring ?? ctx.current;
|
||||
if (!file) return null;
|
||||
const dir = dirname(file);
|
||||
return unique((await symbols(name)).filter((s) => s.name === name && dirname(s.location.path) === dir));
|
||||
}
|
||||
// A function's signature is qualified by the imports of the file asked about; a type's
|
||||
// declaration is its source text, qualified by the declaring file's imports.
|
||||
const files = [...new Set([ctx.declaring, ctx.current])];
|
||||
const paths = new Set((await Promise.all(files.map(importsOf))).map((m) => m.get(qualifier)).filter((p) => !!p));
|
||||
if (paths.size > 1) return null;
|
||||
const [path] = paths;
|
||||
if (path) return findInPackage(path, name);
|
||||
// A package neither file imports: gopls names it by its package name.
|
||||
return unique(
|
||||
(await symbols(`${qualifier}.${name}`)).filter(
|
||||
(s) => !!s.container && goPackageName(s.container) === qualifier && named(s, qualifier, name),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/** Web documentation links a language server's convention lets us resolve to a declaration. */
|
||||
import { findInPackage, pkgGoDevLink } from "./go";
|
||||
import { findRustItem, rustDocLink } from "./rust";
|
||||
import type { DocTarget } from "./symbols";
|
||||
|
||||
/** Looks up the declaration `href` documents; null when no language's rule reads the link. */
|
||||
export function docUrlResolver(href: string): (() => Promise<DocTarget | null>) | null {
|
||||
const go = pkgGoDevLink(href);
|
||||
if (go) return () => findInPackage(go.importPath, go.name);
|
||||
const rust = rustDocLink(href);
|
||||
if (rust) return () => findRustItem(rust);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { WorkspaceSymbol } from "@/bindings";
|
||||
|
||||
const LIB = "/rust/lib/rustlib/src/rust/library";
|
||||
const REG = "/home/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f";
|
||||
const files: Record<string, string> = {
|
||||
[`${LIB}/std/src/ffi/mod.rs`]: "\n\npub use self::os_str::{OsStr, OsString};\n",
|
||||
};
|
||||
|
||||
const sym = (name: string, path: string, container: string | null = null, line = 3): WorkspaceSymbol => ({
|
||||
name,
|
||||
kind: "struct",
|
||||
container,
|
||||
location: { path, range: { start: { line, col: 11 }, end: { line, col: 14 } } },
|
||||
});
|
||||
|
||||
// What rust-analyzer answers per query (`*` = the dependencies instead of the workspace, `#` = every kind).
|
||||
const index: Record<string, WorkspaceSymbol[]> = {
|
||||
"ExitCode*": [
|
||||
sym("ExitCode", `${LIB}/std/src/process.rs`),
|
||||
sym("ExitCode", `${LIB}/std/src/sys/process/mod.rs`),
|
||||
sym("ExitCode", `${LIB}/std/src/sys/process/unix/common.rs`),
|
||||
],
|
||||
"HashMap*": [
|
||||
sym("HashMap", `${LIB}/vendor/hashbrown-0.17.1/src/map.rs`),
|
||||
sym("HashMap", `${LIB}/std/src/collections/mod.rs`),
|
||||
sym("HashMap", `${LIB}/std/src/collections/hash/map.rs`),
|
||||
],
|
||||
"OsString*": [sym("OsString", `${LIB}/std/src/ffi/os_str.rs`), sym("OsString", `${LIB}/std/src/ffi/mod.rs`, null, 2)],
|
||||
"From*": [sym("From", `${LIB}/core/src/convert/mod.rs`)],
|
||||
"push*#": [
|
||||
sym("push", `${LIB}/alloc/src/vec/mod.rs`, "Vec<T, A>"),
|
||||
sym("push", `${LIB}/alloc/src/string.rs`, "String"),
|
||||
],
|
||||
"None*#": [sym("None", `${LIB}/core/src/option.rs`, "Option")],
|
||||
"exit*#": [sym("exit", `${LIB}/std/src/process.rs`), sym("exit", `${REG}/libc-0.2.170/src/unix/mod.rs`)],
|
||||
Sku: [sym("Sku", "/work/rust-app/src/lib.rs")],
|
||||
"Sku*": [sym("Sku", `${REG}/other-1.0.0/src/lib.rs`)],
|
||||
"parse#": [sym("parse", "/work/rust-app/src/parser.rs"), sym("parse", "/work/rust-app/src/lib.rs", "Sku")],
|
||||
"Value*": [sym("Value", `${REG}/serde_json-1.0.140/src/value/mod.rs`)],
|
||||
Twice: [sym("Twice", "/work/a/src/lib.rs"), sym("Twice", "/work/b/src/lib.rs")],
|
||||
};
|
||||
|
||||
vi.mock("@/platform/ipc", async (orig) => ({
|
||||
...(await orig<typeof import("@/platform/ipc")>()),
|
||||
commands: { lspWorkspaceSymbols: async (_id: number, q: string) => ({ status: "ok", data: index[q] ?? [] }) },
|
||||
}));
|
||||
vi.mock("../files", () => ({ readFileLines: async (p: string) => files[p]?.split("\n") ?? [] }));
|
||||
|
||||
const { rustDocLink, findRustItem } = await import("./rust");
|
||||
const { docUrlResolver } = await import("./index");
|
||||
|
||||
describe("rustdoc links", () => {
|
||||
it.each([
|
||||
[
|
||||
"https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html",
|
||||
{ crate: "std", modules: ["process"], kind: "struct", name: "ExitCode", member: null },
|
||||
],
|
||||
[
|
||||
"https://doc.rust-lang.org/nightly/alloc/vec/struct.Vec.html#method.push",
|
||||
{ crate: "alloc", modules: ["vec"], kind: "struct", name: "Vec", member: "push" },
|
||||
],
|
||||
[
|
||||
"https://doc.rust-lang.org/stable/alloc/vec/struct.Vec.html#capacity-and-reallocation",
|
||||
{ crate: "alloc", modules: ["vec"], kind: "struct", name: "Vec", member: null },
|
||||
],
|
||||
[
|
||||
"https://docs.rs/inventory/0.1.0/inventory/struct.Sku.html",
|
||||
{ crate: "inventory", modules: [], kind: "struct", name: "Sku", member: null },
|
||||
],
|
||||
[
|
||||
"https://docs.rs/serde-json/latest/serde_json/value/enum.Value.html",
|
||||
{ crate: "serde_json", modules: ["value"], kind: "enum", name: "Value", member: null },
|
||||
],
|
||||
["https://doc.rust-lang.org/stable/alloc/fmt/index.html", null],
|
||||
["https://doc.rust-lang.org/nightly/core/primitive.char.html", null],
|
||||
["https://doc.rust-lang.org/stable/core/iter/book/ch03-05-control-flow.html", null],
|
||||
["https://docs.rs/serde", null],
|
||||
["https://crates.io/keywords/hasher", null],
|
||||
["https://docs.rs/x/1/x/struct.%E0%A4%A.html", null],
|
||||
])("%s", (href, want) => expect(rustDocLink(href)).toEqual(want));
|
||||
|
||||
const at = (path: string, line = 3) => ({ path, line, col: 11 });
|
||||
it.each([
|
||||
[
|
||||
"std struct, among private copies",
|
||||
"https://doc.rust-lang.org/stable/std/process/struct.ExitCode.html",
|
||||
at(`${LIB}/std/src/process.rs`),
|
||||
],
|
||||
[
|
||||
"module path into a private submodule's file",
|
||||
"https://doc.rust-lang.org/stable/std/collections/hash/map/struct.HashMap.html",
|
||||
at(`${LIB}/std/src/collections/hash/map.rs`),
|
||||
],
|
||||
[
|
||||
"re-export left out",
|
||||
"https://doc.rust-lang.org/stable/std/ffi/struct.OsString.html",
|
||||
at(`${LIB}/std/src/ffi/os_str.rs`),
|
||||
],
|
||||
["trait", "https://doc.rust-lang.org/stable/core/convert/trait.From.html", at(`${LIB}/core/src/convert/mod.rs`)],
|
||||
[
|
||||
"method of its type only",
|
||||
"https://doc.rust-lang.org/stable/alloc/vec/struct.Vec.html#method.push",
|
||||
at(`${LIB}/alloc/src/vec/mod.rs`),
|
||||
],
|
||||
[
|
||||
"enum variant",
|
||||
"https://doc.rust-lang.org/stable/core/option/enum.Option.html#variant.None",
|
||||
at(`${LIB}/core/src/option.rs`),
|
||||
],
|
||||
[
|
||||
"function, other crate's same name left out",
|
||||
"https://doc.rust-lang.org/stable/std/process/fn.exit.html",
|
||||
at(`${LIB}/std/src/process.rs`),
|
||||
],
|
||||
[
|
||||
"the project's own crate (docs.rs)",
|
||||
"https://docs.rs/inventory/0.1.0/inventory/struct.Sku.html",
|
||||
at("/work/rust-app/src/lib.rs"),
|
||||
],
|
||||
[
|
||||
"own module function, not a method",
|
||||
"https://docs.rs/inventory/0.1.0/inventory/parser/fn.parse.html",
|
||||
at("/work/rust-app/src/parser.rs"),
|
||||
],
|
||||
[
|
||||
"registry crate",
|
||||
"https://docs.rs/serde_json/1.0.140/serde_json/value/enum.Value.html",
|
||||
at(`${REG}/serde_json-1.0.140/src/value/mod.rs`),
|
||||
],
|
||||
["registry crate of another version name", "https://docs.rs/serde_json/1.0.140/other/value/enum.Value.html", null],
|
||||
["two local crates: ambiguous", "https://docs.rs/a/0.1.0/a/struct.Twice.html", null],
|
||||
["not found", "https://doc.rust-lang.org/stable/std/process/struct.Missing.html", null],
|
||||
["member not found", "https://doc.rust-lang.org/stable/alloc/string/struct.String.html#method.push_front", null],
|
||||
])("%s", async (_, href, want) => {
|
||||
expect(await findRustItem(rustDocLink(href)!)).toEqual(want);
|
||||
});
|
||||
|
||||
it("is one of the languages documentation links resolve for", async () => {
|
||||
expect(docUrlResolver("https://example.com/x")).toBeNull();
|
||||
expect(await docUrlResolver("https://doc.rust-lang.org/stable/core/convert/trait.From.html")!()).toEqual(
|
||||
at(`${LIB}/core/src/convert/mod.rs`),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Rust documentation links (rust-analyzer): intra-doc links come as rustdoc URLs —
|
||||
* `https://doc.rust-lang.org/<channel>/<crate>/<module…>/<kind>.<Name>.html[#method.<m>]`
|
||||
* for the standard library, `https://docs.rs/<package>/<version>/<crate>/…` for other crates,
|
||||
* the project's own included. They resolve through `workspace/symbol` by name, the crate and
|
||||
* module the URL names and, for a member, its type; only a unique match counts.
|
||||
*/
|
||||
import type { WorkspaceSymbol } from "@/platform/ipc";
|
||||
import { readFileLines } from "../files";
|
||||
import { symbols, unique, type DocTarget } from "./symbols";
|
||||
|
||||
export interface RustDocLink {
|
||||
crate: string;
|
||||
/** Module path inside the crate (`["collections", "hash", "map"]`). */
|
||||
modules: string[];
|
||||
/** Item kind as rustdoc names its page (`struct`, `fn`, `trait`…). */
|
||||
kind: string;
|
||||
name: string;
|
||||
/** `#method.push`, `#variant.None`…: that member of the item. */
|
||||
member: string | null;
|
||||
}
|
||||
|
||||
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
const MEMBER = /^(?:method|tymethod|variant|structfield|associatedconstant|associatedtype)\.([A-Za-z_][A-Za-z0-9_]*)$/;
|
||||
/** Pages of items `workspace/symbol` lists (not modules, primitives or keywords). */
|
||||
const ITEM_KINDS = new Set(["struct", "enum", "trait", "union", "type", "fn", "macro", "constant", "static"]);
|
||||
const TYPE_KINDS = new Set(["struct", "enum", "trait", "union", "type"]);
|
||||
|
||||
/** A rustdoc item URL on doc.rust-lang.org or docs.rs; null for other links. */
|
||||
export function rustDocLink(href: string): RustDocLink | null {
|
||||
// Malformed URLs and escapes are no links.
|
||||
try {
|
||||
const url = new URL(href);
|
||||
const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
|
||||
// doc.rust-lang.org/<channel>/<crate>/…; docs.rs/<package>/<version>/<crate>/…
|
||||
const skip = url.hostname === "doc.rust-lang.org" ? 1 : url.hostname === "docs.rs" ? 2 : -1;
|
||||
if (skip < 0 || parts.length < skip + 2) return null;
|
||||
const [crate, ...rest] = parts.slice(skip);
|
||||
const page = /^(\w+)\.(\w+)\.html$/.exec(rest.pop()!);
|
||||
if (!page || !ITEM_KINDS.has(page[1]!) || ![crate, ...rest].every((p) => IDENT.test(p!))) return null;
|
||||
const member = MEMBER.exec(decodeURIComponent(url.hash.slice(1)))?.[1] ?? null;
|
||||
return { crate: crate!, modules: rest, kind: page[1]!, name: page[2]!, member };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `path` can be `link`'s module of its crate: the module's file or a file under its
|
||||
* directory. Files of the standard library and of downloaded crates also have to be that crate;
|
||||
* the project's own crates can't be told apart by path.
|
||||
*/
|
||||
export function inModule(path: string, link: Pick<RustDocLink, "crate" | "modules">): boolean {
|
||||
const m = /^(.*\/)?([^/]+)\/src\/(.*)$/.exec(path);
|
||||
if (!m) return false;
|
||||
const [, parent = "", dir, file] = m;
|
||||
const crateDir = link.crate.replace(/_/g, "[-_]");
|
||||
const packaged = /\/(?:registry\/src\/[^/]+|library\/vendor)\/$/.test(parent);
|
||||
if (/\/library\/$/.test(parent) ? dir !== link.crate : packaged && !new RegExp(`^${crateDir}-\\d`).test(dir!))
|
||||
return false;
|
||||
if (!link.modules.length) return true;
|
||||
const mod = link.modules.join("/");
|
||||
return file === `${mod}.rs` || file!.startsWith(`${mod}/`);
|
||||
}
|
||||
|
||||
/** The type a member's symbol belongs to, as rust-analyzer names its container (`Vec<T, A>` → `Vec`). */
|
||||
function ownerName(s: WorkspaceSymbol): string {
|
||||
return (s.container ?? "").replace(/<.*$/, "").trim();
|
||||
}
|
||||
|
||||
/** A `use` line: rust-analyzer lists re-exports too, but the declaration is what's meant. */
|
||||
async function isReexport(s: WorkspaceSymbol): Promise<boolean> {
|
||||
const line = (await readFileLines(s.location.path).catch(() => null))?.[s.location.range.start.line] ?? "";
|
||||
return /^\s*(?:pub(?:\([^)]*\))?\s+)?use\b/.test(line);
|
||||
}
|
||||
|
||||
/** Where `link` is declared, when exactly one symbol fits it. */
|
||||
export async function findRustItem(link: RustDocLink): Promise<DocTarget | null> {
|
||||
const name = link.member ?? link.name;
|
||||
// rust-analyzer's query markers: `*` searches the dependencies (instead of the workspace),
|
||||
// `#` every kind of symbol (not only types).
|
||||
// A common name (`Vec::new`) can be past rust-analyzer's 128 results; such links open in the browser.
|
||||
const all = link.member || !TYPE_KINDS.has(link.kind) ? "#" : "";
|
||||
const found = await Promise.all([symbols(`${name}${all}`), symbols(`${name}*${all}`)]);
|
||||
const hits = found
|
||||
.flat()
|
||||
.filter((s) => s.name === name && (!link.member || ownerName(s) === link.name) && inModule(s.location.path, link));
|
||||
const declared = await Promise.all(hits.map(async (s) => !(await isReexport(s))));
|
||||
return unique(hits.filter((_, i) => declared[i]));
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/** `workspace/symbol` lookups shared by the per-language documentation link rules. */
|
||||
import { call, commands, nextRequestId, type WorkspaceSymbol } from "@/platform/ipc";
|
||||
|
||||
export interface DocTarget {
|
||||
path: string;
|
||||
line: number;
|
||||
col: number;
|
||||
}
|
||||
|
||||
export async function symbols(query: string): Promise<WorkspaceSymbol[]> {
|
||||
return call(commands.lspWorkspaceSymbols(nextRequestId(), query)).catch(() => []);
|
||||
}
|
||||
|
||||
/** The one place `hits` name (the same place listed twice counts once); null when none or several. */
|
||||
export function unique(hits: WorkspaceSymbol[]): DocTarget | null {
|
||||
const places = new Map(
|
||||
hits.map((s) => {
|
||||
const { path, range } = s.location;
|
||||
return [`${path}:${range.start.line}:${range.start.col}`, { path, ...range.start }] as const;
|
||||
}),
|
||||
);
|
||||
return places.size === 1 ? [...places.values()][0]! : null;
|
||||
}
|
||||
+115
-26
@@ -3,14 +3,18 @@
|
||||
* their documentation in place (⌘-click opens the source instead), ← / →
|
||||
* walk the history, Edit Source (F4) jumps to the declaration, and F1 on a
|
||||
* focused popup moves it to the Documentation tool window, which then shows
|
||||
* F1's documentation instead of a popup while it is open.
|
||||
* F1's documentation instead of a popup while it is open. The hover's
|
||||
* documentation is the same view with its own history.
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
import { create, createStore, type StoreApi } from "zustand";
|
||||
import { commands, nextRequestId, type Location } from "@/platform/ipc";
|
||||
import { hasPrimaryModifier } from "@/platform/keymap";
|
||||
import { editorService, maybeEditorService, toolWindowService } from "@/workbench/contributions";
|
||||
import { closePopup, updatePopup, useLspPopup, type DocEntry } from "./popupStore";
|
||||
import { isEmptyMarkup, languageForPath, sourceLink, type DocLinkHandler } from "./markdown";
|
||||
import { isEmptyMarkup, languageForPath, openDocLink, sourceLink, type DocLinkHandler } from "./markdown";
|
||||
import { resolveGoRef, signatureRef } from "./docLinks/go";
|
||||
import { docUrlResolver } from "./docLinks";
|
||||
import type { DocTarget } from "./docLinks/symbols";
|
||||
import { lspRequest } from "./lsp";
|
||||
import { readFileLines, withDocument } from "./files";
|
||||
|
||||
@@ -54,33 +58,79 @@ export function showInDocWindow(entry: DocEntry, themeClasses: string) {
|
||||
toolWindowService().show(DOCUMENTATION_WINDOW, false);
|
||||
}
|
||||
|
||||
/** F1 on a focused documentation popup: the popup's history moves to the tool window. */
|
||||
export function moveDocPopupToWindow(): boolean {
|
||||
/** F1 on a focused documentation popup: the popup's (or the hover's) history moves to the tool window. */
|
||||
export function moveDocPopupToWindow(host: "popup" | HoverDoc = "popup"): boolean {
|
||||
const h = history(host);
|
||||
if (!h) return false;
|
||||
const popup = useLspPopup.getState().popup;
|
||||
if (popup?.kind !== "doc") return false;
|
||||
useDocWindow.setState({ entries: popup.entries, index: popup.index, themeClasses: popup.themeClasses });
|
||||
closePopup();
|
||||
const themeClasses = host === "popup" && popup?.kind === "doc" ? popup.themeClasses : "";
|
||||
useDocWindow.setState((s) => ({ entries: h.entries, index: h.index, themeClasses: themeClasses || s.themeClasses }));
|
||||
closeHost(host);
|
||||
toolWindowService().show(DOCUMENTATION_WINDOW, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Hover documentation: each hover tooltip keeps its own history (an editor that comes back
|
||||
// into view brings its open hover back too).
|
||||
|
||||
interface HoverDocState extends DocHistory {
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
export type HoverDoc = StoreApi<HoverDocState>;
|
||||
|
||||
export function hoverDoc(entry: DocEntry, close: () => void): HoverDoc {
|
||||
return createStore<HoverDocState>(() => ({ entries: [entry], index: 0, close }));
|
||||
}
|
||||
|
||||
/** The size the documentation popup was last resized to, kept across sessions as IDEA does. */
|
||||
const DOC_SIZE_KEY = "openidea.lsp.docPopupSize";
|
||||
export const DOC_MIN_WIDTH = 240;
|
||||
export const DOC_MIN_HEIGHT = 120;
|
||||
|
||||
export function loadDocSize(): { w: number; h: number } | null {
|
||||
try {
|
||||
const v = JSON.parse(localStorage.getItem(DOC_SIZE_KEY) ?? "null") as { w?: unknown; h?: unknown } | null;
|
||||
return typeof v?.w === "number" && typeof v.h === "number" ? { w: v.w, h: v.h } : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveDocSize(size: { w: number; h: number }) {
|
||||
try {
|
||||
localStorage.setItem(DOC_SIZE_KEY, JSON.stringify(size));
|
||||
} catch {
|
||||
// Storage unavailable: the next popup opens at its default size.
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Shared by the popup and the tool window
|
||||
|
||||
/** Where a doc view keeps its history: the popup or the tool window. */
|
||||
export type DocHost = "popup" | "window";
|
||||
/** Where a doc view keeps its history: the F1 popup, the hover or the tool window. */
|
||||
export type DocHost = "popup" | "window" | HoverDoc;
|
||||
|
||||
function history(host: DocHost): DocHistory | null {
|
||||
if (host === "window") return useDocWindow.getState();
|
||||
if (typeof host === "object") return host.getState();
|
||||
const p = useLspPopup.getState().popup;
|
||||
return p?.kind === "doc" ? p : null;
|
||||
}
|
||||
|
||||
function setHistory(host: DocHost, h: DocHistory) {
|
||||
if (host === "window") useDocWindow.setState(h);
|
||||
else if (typeof host === "object") host.setState(h);
|
||||
else updatePopup("doc", h);
|
||||
}
|
||||
|
||||
/** Closes the popup or the hover a link or Edit Source leaves; the tool window stays. */
|
||||
function closeHost(host: DocHost) {
|
||||
if (host === "popup") closePopup();
|
||||
else if (typeof host === "object") host.getState().close();
|
||||
}
|
||||
|
||||
export function docStep(host: DocHost, delta: -1 | 1) {
|
||||
const h = history(host);
|
||||
if (h) setHistory(host, { entries: h.entries, index: stepHistory(h, delta) });
|
||||
@@ -92,7 +142,7 @@ export async function editDocSource(host: DocHost): Promise<boolean> {
|
||||
const entry = h?.entries[h.index];
|
||||
const loc = (await entry?.source?.().catch(() => null)) ?? null;
|
||||
if (!loc) return false;
|
||||
if (host === "popup") closePopup();
|
||||
closeHost(host);
|
||||
await editorService().openFile(loc.path, {
|
||||
selection: { line: loc.range.start.line, col: loc.range.start.col },
|
||||
focus: true,
|
||||
@@ -130,37 +180,76 @@ async function docAt(target: { path: string; line: number; col: number }): Promi
|
||||
path: target.path,
|
||||
range: { start: { line: target.line, col }, end: { line: target.line, col } },
|
||||
};
|
||||
return { markup: hover.contents, language: languageForPath(target.path), source: async () => location };
|
||||
return {
|
||||
markup: hover.contents,
|
||||
language: languageForPath(target.path),
|
||||
file: target.path,
|
||||
source: async () => location,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Shows `target`'s documentation as the next history step; without any, opens its source. */
|
||||
async function followTo(host: DocHost, target: DocTarget) {
|
||||
const entry = await docAt(target).catch(() => null);
|
||||
const h = history(host);
|
||||
if (!entry || !h) {
|
||||
closeHost(host);
|
||||
void maybeEditorService()?.openFile(target.path, {
|
||||
selection: { line: target.line, col: target.col },
|
||||
focus: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setHistory(host, pushHistory(h, entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* Link clicks in a documentation view: a source link shows that symbol's
|
||||
* documentation in the same view (⌘-click opens the source instead).
|
||||
* documentation in the same view (⌘-click opens the source instead); so does
|
||||
* a web link a language's rule (`docLinks/`) finds the symbol of, others open in the browser.
|
||||
*/
|
||||
export function docLinkHandler(host: DocHost): DocLinkHandler {
|
||||
return (href, e) => {
|
||||
const target = sourceLink(href);
|
||||
if (!target || hasPrimaryModifier(e)) {
|
||||
if (host === "popup" && target) closePopup();
|
||||
const web = target ? null : docUrlResolver(href);
|
||||
if ((!target && !web) || hasPrimaryModifier(e)) {
|
||||
if (target) closeHost(host);
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
const entry = await docAt(target).catch(() => null);
|
||||
const h = history(host);
|
||||
if (!entry || !h) {
|
||||
if (host === "popup") closePopup();
|
||||
void maybeEditorService()?.openFile(target.path, {
|
||||
selection: { line: target.line, col: target.col },
|
||||
focus: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
setHistory(host, pushHistory(h, entry));
|
||||
const found = target ?? (web && (await web().catch(() => null)));
|
||||
if (found) await followTo(host, found);
|
||||
else openDocLink(href);
|
||||
})();
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
/** The signature block of gopls documentation, whose type names `linkSignatureTypes` follows. */
|
||||
const GO_SIGNATURE = ":scope > pre:first-of-type > code.language-go";
|
||||
|
||||
/**
|
||||
* Go: a click on a type name in the signature shows that type's documentation
|
||||
* in the same view, when the name resolves to exactly one declaration.
|
||||
*/
|
||||
export function linkSignatureTypes(dom: HTMLElement, host: DocHost, entry: DocEntry) {
|
||||
dom.addEventListener("click", (e) => {
|
||||
const name = (e.target as Element | null)?.closest?.(".tok-typeName");
|
||||
const code = dom.querySelector(GO_SIGNATURE);
|
||||
if (!name || !code?.contains(name) || !document.getSelection()?.isCollapsed) return;
|
||||
const before = document.createRange();
|
||||
before.setStart(code, 0);
|
||||
before.setEndBefore(name);
|
||||
const from = before.toString().length;
|
||||
const ref = signatureRef(code.textContent ?? "", from, from + (name.textContent ?? "").length);
|
||||
void (async () => {
|
||||
const declaring = (await entry.source?.().catch(() => null))?.path ?? null;
|
||||
const target = await resolveGoRef(ref, { declaring, current: entry.file ?? null }).catch(() => null);
|
||||
if (target) await followTo(host, target);
|
||||
})();
|
||||
});
|
||||
}
|
||||
@@ -35,9 +35,14 @@ const hintField = StateField.define<Hint | null>({
|
||||
pos: h.pos,
|
||||
above: true,
|
||||
strictSide: false,
|
||||
create: () => {
|
||||
create: (view) => {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `cm-lsp-hint cm-lsp-hint-${h.tone}`;
|
||||
// Clicked or focused (a value tree expanded in it): the user works in the hint, so
|
||||
// it stays until an edit, a caret move or Escape.
|
||||
const keep = () => clearTimeout(timers.get(view));
|
||||
dom.addEventListener("pointerdown", keep);
|
||||
dom.addEventListener("focusin", keep);
|
||||
dom.setAttribute("role", "status");
|
||||
if (h.pending) dom.dataset.pending = "true";
|
||||
Object.assign(dom.dataset, h.data);
|
||||
@@ -63,7 +68,8 @@ const timers = new WeakMap<EditorView, ReturnType<typeof setTimeout>>();
|
||||
export function showHint(
|
||||
view: EditorView,
|
||||
content: Hint["content"],
|
||||
opts: { pos?: number; tone?: Hint["tone"]; timeout?: number; pending?: boolean; data?: Hint["data"] } = {},
|
||||
/** `timeout: null`: the hint stays until an edit, a caret move or Escape. */
|
||||
opts: { pos?: number; tone?: Hint["tone"]; timeout?: number | null; pending?: boolean; data?: Hint["data"] } = {},
|
||||
) {
|
||||
const pos = opts.pos ?? view.state.selection.main.head;
|
||||
const effects: StateEffect<unknown>[] = [
|
||||
@@ -72,6 +78,7 @@ export function showHint(
|
||||
if (!view.state.field(hintField, false)) effects.push(StateEffect.appendConfig.of(hintExtension()));
|
||||
view.dispatch({ effects });
|
||||
clearTimeout(timers.get(view));
|
||||
if (opts.timeout === null) return;
|
||||
timers.set(
|
||||
view,
|
||||
// Also while the view is hidden: it would show the hint again when its tab is shown.
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { diagnosticsAt, type PlacedDiagnostic, type EditorDiagnostic } from "./diagnostics";
|
||||
import { isEmptyMarkup, languageForPath, renderMarkup } from "./markdown";
|
||||
import { isEmptyMarkup, languageForPath } from "./markdown";
|
||||
import { selectableText } from "@/ui/selectableText";
|
||||
import { docOf, lspRequest, reportLspError } from "./lsp";
|
||||
import { requestNavigation } from "./configurationNavigation";
|
||||
@@ -28,7 +28,8 @@ import { showHint } from "./hint";
|
||||
import { caretAnchor, focusPopup, openPopup, useLspPopup, type DefinitionTarget, type DocEntry } from "./popupStore";
|
||||
import { selectedLookupDoc, showLookupDocs } from "./completion";
|
||||
import { readFileLines, targetLabel, withDocument } from "./files";
|
||||
import { docWindowVisible, moveDocPopupToWindow, showInDocWindow } from "./docs";
|
||||
import { docWindowVisible, hoverDoc, moveDocPopupToWindow, showInDocWindow } from "./docs";
|
||||
import { mountHoverDoc } from "./DocView";
|
||||
import { structure } from "@/editor/structure";
|
||||
import { basename } from "@/platform/project";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
@@ -178,7 +179,7 @@ export async function hoverSource(view: EditorView, pos: number) {
|
||||
const word = view.state.wordAt(pos);
|
||||
if (word) ({ from, to } = word);
|
||||
}
|
||||
const lang = docOf(view)?.uiMode ?? null;
|
||||
const entry = hover && docEntry(view, pos, hover);
|
||||
return {
|
||||
pos: from,
|
||||
end: to,
|
||||
@@ -187,8 +188,11 @@ export async function hoverSource(view: EditorView, pos: number) {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `cm-lsp-hover ${selectableText}`;
|
||||
if (diags.length) dom.appendChild(renderDiagnostics(view, diags));
|
||||
if (hover) dom.appendChild(renderMarkup(hover.contents, lang));
|
||||
return { dom };
|
||||
if (!entry) return { dom };
|
||||
// The same documentation view as F1's popup: links open in place, ← / →, Edit Source.
|
||||
dom.classList.add("cm-lsp-hover-doc");
|
||||
const doc = hoverDoc(entry, () => view.dispatch({ effects: closeHoverTooltips }));
|
||||
return { dom, destroy: mountHoverDoc(dom.appendChild(document.createElement("div")), doc) };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -239,6 +243,20 @@ function definitionOf(doc: number, pos: Pos): () => Promise<Location | null> {
|
||||
));
|
||||
}
|
||||
|
||||
/** The documentation `hover` shows for `pos`, with its declaration for Edit Source. */
|
||||
function docEntry(view: EditorView, pos: number, hover: Hover): DocEntry {
|
||||
const ctx = docOf(view);
|
||||
return {
|
||||
markup: hover.contents,
|
||||
language: ctx?.uiMode ?? null,
|
||||
file: ctx?.path,
|
||||
source:
|
||||
ctx && !constructAt(view.state, pos, ctx.language)
|
||||
? definitionOf(ctx.doc, offsetToPos(view.state.doc, pos))
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function showDoc(view: EditorView, entry: DocEntry, at: number) {
|
||||
if (docWindowVisible()) {
|
||||
showInDocWindow(entry, view.themeClasses);
|
||||
@@ -287,19 +305,7 @@ export async function quickDocumentation(view: EditorView) {
|
||||
showHint(view, "No documentation found");
|
||||
return;
|
||||
}
|
||||
const ctx = docOf(view);
|
||||
showDoc(
|
||||
view,
|
||||
{
|
||||
markup: hover.contents,
|
||||
language: ctx?.uiMode ?? null,
|
||||
source:
|
||||
ctx && !constructAt(view.state, pos, ctx.language)
|
||||
? definitionOf(ctx.doc, offsetToPos(view.state.doc, pos))
|
||||
: undefined,
|
||||
},
|
||||
hover.range ? rangeToOffsets(view.state.doc, hover.range).from : pos,
|
||||
);
|
||||
showDoc(view, docEntry(view, pos, hover), hover.range ? rangeToOffsets(view.state.doc, hover.range).from : pos);
|
||||
} catch (e) {
|
||||
reportLspError(view, e, true);
|
||||
}
|
||||
|
||||
@@ -68,6 +68,7 @@ describe("sourceLink", () => {
|
||||
it("reads the file and position a documentation link names", () => {
|
||||
project("C:/repo");
|
||||
expect(sourceLink("file:///C:/repo/src/a.py#L12,5")).toEqual({ path: "/C:/repo/src/a.py", line: 11, col: 4 });
|
||||
expect(sourceLink("file:///p/src/cart.ts#L20%2C3")).toEqual({ path: "/p/src/cart.ts", line: 19, col: 2 });
|
||||
expect(sourceLink("https://example.com/a.py")).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -208,7 +208,8 @@ export function sourceLink(href: string): { path: string; line: number; col: num
|
||||
const path = decodeURIComponent(url.pathname);
|
||||
// Documentation is text someone else wrote.
|
||||
if (onOtherShare(path, useProject.getState().project?.root ?? "")) return null;
|
||||
const m = /^#?L?(\d+)(?:[,:](\d+))?/.exec(url.hash.slice(1));
|
||||
// typescript-language-server encodes the comma (`#L20%2C3`).
|
||||
const m = /^#?L?(\d+)(?:[,:](\d+))?/.exec(url.hash.slice(1).replace(/%2C/gi, ","));
|
||||
return {
|
||||
path,
|
||||
line: m ? Math.max(0, Number(m[1]) - 1) : 0,
|
||||
|
||||
@@ -48,6 +48,8 @@ export interface DiffLine {
|
||||
export interface DocEntry {
|
||||
markup: Markup;
|
||||
language: string | null;
|
||||
/** The file the documentation was asked about in (its imports qualify Go signatures). */
|
||||
file?: string;
|
||||
/** Declaration of the documented element (Edit Source), resolved on demand. */
|
||||
source?: () => Promise<Location | null>;
|
||||
}
|
||||
|
||||
@@ -225,10 +225,11 @@ export const lspTheme = EditorView.theme({
|
||||
".cm-tooltip.cm-tooltip-hover": { ...tooltipSurface, display: "flex", flexDirection: "column" },
|
||||
".cm-tooltip-hover > .cm-tooltip-section": { minHeight: 0, flexShrink: 1 },
|
||||
".cm-lsp-hover": { maxWidth: "580px", maxHeight: "380px", overflow: "auto", padding: "10px 14px" },
|
||||
".cm-lsp-hover-diagnostics + .cm-lsp-markdown": {
|
||||
borderTop: "1px solid var(--border-popup)",
|
||||
margin: "10px -14px 0",
|
||||
padding: "10px 14px 0",
|
||||
// With documentation the doc view pads its own body and keeps its toolbar at the bottom.
|
||||
".cm-lsp-hover.cm-lsp-hover-doc": { padding: "0" },
|
||||
".cm-lsp-hover-doc > .cm-lsp-hover-diagnostics": {
|
||||
padding: "10px 14px",
|
||||
borderBottom: "1px solid var(--border-popup)",
|
||||
},
|
||||
".cm-lsp-diag": {
|
||||
display: "flex",
|
||||
|
||||
@@ -33,7 +33,7 @@ import { executeAction } from "@/platform/actions";
|
||||
import { call, commands, onIdeEvent } from "@/platform/ipc";
|
||||
import { isSameOrInside } from "@/platform/paths";
|
||||
import { basename, relativeDir, useProject } from "@/platform/project";
|
||||
import { notifications, useEditorShown, type EditorInput } from "@/workbench/contributions";
|
||||
import { notifications, useEditorShown, useToolWindowShown, type EditorInput } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import {
|
||||
Button,
|
||||
@@ -150,7 +150,7 @@ import {
|
||||
useAgentCommands,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
import { setFocusedSession, focusedSession, type FocusedSession } from "./sessionFocus";
|
||||
import { setFocusedSession, focusedSession, registerReachableSession, type FocusedSession } from "./sessionFocus";
|
||||
import { taskMenu } from "./taskActions";
|
||||
import styles from "./Session.module.css";
|
||||
|
||||
@@ -225,7 +225,10 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
const { fitWindowWidth } = useAgentSettings();
|
||||
const sessionRoot = useRef<HTMLDivElement>(null);
|
||||
const { fontZoom, zoomStyle } = useAgentFontZoomSurface(sessionRoot, sessionKey(id), docked, !!task);
|
||||
const canFocusInput = shown && !!task && task.status !== "archived" && !view;
|
||||
// A docked task is on screen while its tool window is; a tab's own `shown` is its editor slot's.
|
||||
const toolWindowShown = useToolWindowShown();
|
||||
const onScreen = docked ? toolWindowShown : shown;
|
||||
const canFocusInput = onScreen && !!task && task.status !== "archived" && !view;
|
||||
const session = useMemo<FocusedSession>(
|
||||
() => ({
|
||||
openFind: () => {
|
||||
@@ -247,6 +250,9 @@ function TaskSession({ id, docked }: { id: string; docked: boolean }) {
|
||||
if (focusedSession() === session) setFocusedSession(null);
|
||||
};
|
||||
}, [session, shown]);
|
||||
useLayoutEffect(() => {
|
||||
if (session.focusInput) return registerReachableSession(session);
|
||||
}, [session]);
|
||||
if (!task) return <EmptyState title="This agent task no longer exists" />;
|
||||
return (
|
||||
<div
|
||||
@@ -400,6 +406,11 @@ function SessionStatus({
|
||||
>
|
||||
{/* Where the task works, in one quiet line like the new-task page: project (in a workspace), branch, worktree. */}
|
||||
<span className={styles.where} title={task.cwd}>
|
||||
{/* Which agent runs the task: with several tasks side by side, this tells their answers apart. */}
|
||||
<span className={styles.fact} title={providerName(task.provider)}>
|
||||
<Icon name={providerIcon(task.provider)} size={13} />
|
||||
<span className={styles.factText}>{providerName(task.provider)}</span>
|
||||
</span>
|
||||
{project?.workspace && projectName && (
|
||||
<span className={styles.fact}>
|
||||
<Icon name="folder" size={13} />
|
||||
|
||||
@@ -112,6 +112,15 @@ describe("commitMessagePrompt", () => {
|
||||
it("leaves out the style hint without earlier commits", () => {
|
||||
expect(commitMessagePrompt(PATCH, 72, [])).not.toContain("latest commits");
|
||||
});
|
||||
|
||||
it("adds the project's commit conventions before the recent subjects", () => {
|
||||
const prompt = commitMessagePrompt(PATCH, 72, ["fix: y"], " Use Conventional Commits.\nPrefix the issue key. ");
|
||||
const conventions = prompt.indexOf("Follow these conventions for commit messages here:\nUse Conventional Commits.");
|
||||
expect(conventions).toBeGreaterThan(0);
|
||||
expect(prompt).toContain("Prefix the issue key.\n");
|
||||
expect(conventions).toBeLessThan(prompt.indexOf("latest commits"));
|
||||
expect(commitMessagePrompt(PATCH, 72, [], " \n ")).not.toContain("conventions");
|
||||
});
|
||||
});
|
||||
|
||||
describe("commitMessageOf", () => {
|
||||
|
||||
@@ -44,7 +44,12 @@ export function fitPatch(patch: string, budget = PATCH_BUDGET, perFile = FILE_BU
|
||||
return omitted.length ? `${out}\nDiff omitted for: ${omitted.join(", ")}\n` : out;
|
||||
}
|
||||
|
||||
export function commitMessagePrompt(patch: string, subjectLimit: number, recentSubjects: readonly string[]): string {
|
||||
export function commitMessagePrompt(
|
||||
patch: string,
|
||||
subjectLimit: number,
|
||||
recentSubjects: readonly string[],
|
||||
instructions = "",
|
||||
): string {
|
||||
const lines = [
|
||||
"Write a commit message",
|
||||
"",
|
||||
@@ -54,6 +59,8 @@ export function commitMessagePrompt(patch: string, subjectLimit: number, recentS
|
||||
"- Don't edit files or run commands. The whole diff is below.",
|
||||
"- Reply with the commit message only: no quotes, no code fence, no commentary.",
|
||||
];
|
||||
// The project's own conventions (Settings › Version Control › Commit) come before the style of recent commits.
|
||||
if (instructions.trim()) lines.push("", "Follow these conventions for commit messages here:", instructions.trim());
|
||||
if (recentSubjects.length) {
|
||||
lines.push(
|
||||
"",
|
||||
@@ -250,7 +257,12 @@ async function generate(): Promise<void> {
|
||||
|
||||
const { commit } = workflowSettings().vcs;
|
||||
const subjects = await recentSubjects(changes.roots[0]);
|
||||
const prompt = commitMessagePrompt(changes.patch, commit.limitSubject ? commit.subjectLimit : 72, subjects);
|
||||
const prompt = commitMessagePrompt(
|
||||
changes.patch,
|
||||
commit.limitSubject ? commit.subjectLimit : 72,
|
||||
subjects,
|
||||
commit.agentInstructions,
|
||||
);
|
||||
let task: AgentTask | undefined;
|
||||
let release = () => {};
|
||||
try {
|
||||
|
||||
@@ -373,6 +373,11 @@ describe("composer UI during submission", () => {
|
||||
expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();
|
||||
});
|
||||
|
||||
it("names the task's agent under the composer", () => {
|
||||
render(<SessionEditor input={{ kind: SESSION_KIND, key: sessionKey("A"), data: { task: "A" } }} />);
|
||||
expect(screen.getByTitle("Codex")).toHaveTextContent("Codex");
|
||||
});
|
||||
|
||||
it("clears an unchanged session draft after only moving the caret", async () => {
|
||||
const response = deferred();
|
||||
backend.prompt.mockReturnValue(response.promise);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { create } from "zustand";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerFontZoomSurface, useEditorShown, useEditorTabId, useToolWindowShown } from "@/workbench/contributions";
|
||||
import { wheelZoomStep } from "@/platform/wheelZoom";
|
||||
|
||||
const MIN_FONT_ZOOM = -6;
|
||||
const MAX_FONT_ZOOM = 36;
|
||||
@@ -74,10 +75,12 @@ export function useAgentFontZoomSurface(
|
||||
if (!active || !el) return;
|
||||
const step = (delta: number) => stepAgentSurfaceFontZoom(surfaceKey, delta);
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
if ((!e.ctrlKey && !e.metaKey) || e.deltaY === 0 || !editorPrefs().general.wheelZoom) return;
|
||||
if (!editorPrefs().general.wheelZoom) return;
|
||||
const zoom = wheelZoomStep(e);
|
||||
if (zoom === null) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
step(e.deltaY < 0 ? 1 : -1);
|
||||
if (zoom) step(zoom);
|
||||
};
|
||||
el.addEventListener("wheel", onWheel, { capture: true, passive: false });
|
||||
const release = registerFontZoomSurface(el, step, { isolated: true });
|
||||
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
providerIcon,
|
||||
} from "./model";
|
||||
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
|
||||
import { focusedSession } from "./sessionFocus";
|
||||
import { focusedSession, inputSession } from "./sessionFocus";
|
||||
import { cycleFocusedEffort } from "./effortFocus";
|
||||
import { clearAgentTabFontZoom } from "./fontZoom";
|
||||
import {
|
||||
@@ -227,11 +227,13 @@ export function activate(): () => void {
|
||||
{
|
||||
id: "agents.focusInput",
|
||||
title: "Focus Agent Input",
|
||||
description: "Focuses the message input of the current agent task without moving the caret.",
|
||||
description:
|
||||
"Focuses the message input of the current agent task, or of the one on screen when focus is elsewhere and no panel claims the shortcut, without moving the caret.",
|
||||
category: "Agents",
|
||||
when: "agentSessionFocus && agentInputAvailable",
|
||||
keyWhen: "agentSessionFocus && !popupOpen",
|
||||
run: () => focusedSession()?.focusInput?.(),
|
||||
when: "agentInputAvailable",
|
||||
// In a task view it wins over the editor's Go to Line; elsewhere it yields wherever that applies.
|
||||
keyWhen: "!popupOpen && (agentSessionFocus || !(textEditorActive && (editorFocus || !toolWindowFocus)))",
|
||||
run: () => inputSession()?.focusInput?.(),
|
||||
},
|
||||
{
|
||||
id: "agents.cycleEffort",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** The agent session holding focus, for actions scoped to that task view. */
|
||||
/** The agent session holding focus, and those shown elsewhere, for actions scoped to a task view. */
|
||||
import { setContext } from "@/platform/context";
|
||||
|
||||
export interface FocusedSession {
|
||||
@@ -7,11 +7,34 @@ export interface FocusedSession {
|
||||
}
|
||||
|
||||
let focused: FocusedSession | null = null;
|
||||
/** Sessions on screen that accept input, least recently focused first. */
|
||||
let reachable: FocusedSession[] = [];
|
||||
|
||||
/** The session `Focus Agent Input` targets: the focused one, else the most recently used shown one. */
|
||||
export function inputSession(): FocusedSession | null {
|
||||
if (focused) return focused.focusInput ? focused : null;
|
||||
return reachable.at(-1) ?? null;
|
||||
}
|
||||
|
||||
function publish() {
|
||||
setContext("agentSessionFocus", !!focused);
|
||||
setContext("agentInputAvailable", !!inputSession());
|
||||
}
|
||||
|
||||
export function setFocusedSession(session: FocusedSession | null) {
|
||||
focused = session;
|
||||
setContext("agentSessionFocus", !!session);
|
||||
setContext("agentInputAvailable", !!session?.focusInput);
|
||||
if (session && reachable.includes(session)) reachable = [...reachable.filter((s) => s !== session), session];
|
||||
publish();
|
||||
}
|
||||
|
||||
/** Lists a shown session that accepts input as a target for the shortcut; returns a disposer. */
|
||||
export function registerReachableSession(session: FocusedSession): () => void {
|
||||
reachable = [...reachable.filter((s) => s !== session), session];
|
||||
publish();
|
||||
return () => {
|
||||
reachable = reachable.filter((s) => s !== session);
|
||||
publish();
|
||||
};
|
||||
}
|
||||
|
||||
export const focusedSession = () => focused;
|
||||
@@ -445,68 +445,6 @@ describe("Check for Updates", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("automatic nightly update prompts", () => {
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const update = (currentVersion: string): UpdateInfo => ({
|
||||
version: "0.1.41",
|
||||
currentVersion,
|
||||
notes: null,
|
||||
date: null,
|
||||
});
|
||||
const startupCheck = async (currentVersion: string) => {
|
||||
notes = [];
|
||||
await notifyUpdate(update(currentVersion));
|
||||
return notes.length;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.useFakeTimers({ toFake: ["Date"], now: 10 * DAY });
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("leaves stable prompts to the backend announcement policy", async () => {
|
||||
expect(await startupCheck("0.1.40")).toBe(1);
|
||||
expect(await startupCheck("0.1.40")).toBe(1);
|
||||
});
|
||||
|
||||
it("asks a nightly build at most once a day", async () => {
|
||||
const nightly = "0.1.41-nightly.202611081417";
|
||||
expect(await startupCheck(nightly)).toBe(1);
|
||||
vi.setSystemTime(11 * DAY - 1);
|
||||
expect(await startupCheck(nightly)).toBe(0);
|
||||
vi.setSystemTime(11 * DAY);
|
||||
expect(await startupCheck(nightly)).toBe(1);
|
||||
});
|
||||
|
||||
it("does not prompt twice a day for periodic nightly checks, but always answers a manual check", async () => {
|
||||
const nightly = "0.1.41-nightly.202611081417";
|
||||
const dispose = installUpdateChecks();
|
||||
await tick();
|
||||
try {
|
||||
const available = updateListeners.get("updateAvailable")!;
|
||||
available({ update: update(nightly) });
|
||||
await tick();
|
||||
expect(notes).toHaveLength(1);
|
||||
vi.setSystemTime(10 * DAY + 4 * 60 * 60 * 1000);
|
||||
available({ update: { ...update(nightly), version: "0.1.42-nightly.202611090200" } });
|
||||
await tick();
|
||||
expect(notes).toHaveLength(1);
|
||||
const done = checkForUpdates();
|
||||
check.resolve(ok({ enabled: true, update: update(nightly) }));
|
||||
await done;
|
||||
expect(notes.at(-1)).toMatchObject({ title: "OpenIDEA 0.1.41 is available", userInitiated: true });
|
||||
notes = [];
|
||||
vi.setSystemTime(11 * DAY);
|
||||
available({ update: { ...update(nightly), version: "0.1.42-nightly.202611091400" } });
|
||||
await tick();
|
||||
expect(notes).toHaveLength(1);
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateSource", () => {
|
||||
const withSettings = (updateSource: string | undefined, locale: string | undefined) =>
|
||||
useProject.setState({ settings: { general: { updateSource }, appearance: { locale } } as unknown as Settings });
|
||||
|
||||
@@ -121,17 +121,6 @@ async function runCheck() {
|
||||
}
|
||||
}
|
||||
|
||||
const NIGHTLY_PROMPT_KEY = "openidea.update.nightlyPromptedAt";
|
||||
const NIGHTLY_PROMPT_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** Nightly builds come out more often than anyone wants to be asked: at most one prompt a day. */
|
||||
function nightlyPromptDue(now = Date.now()): boolean {
|
||||
const last = Number(localStorage.getItem(NIGHTLY_PROMPT_KEY));
|
||||
if (now - last < NIGHTLY_PROMPT_INTERVAL_MS) return false;
|
||||
localStorage.setItem(NIGHTLY_PROMPT_KEY, String(now));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Start one backend schedule after this window can receive its notifications. */
|
||||
export function installUpdateChecks(): () => void {
|
||||
let disposed = false;
|
||||
@@ -167,7 +156,6 @@ export async function notifyUpdate(update: UpdateInfo, userInitiated = false): P
|
||||
);
|
||||
if (!claimed) return;
|
||||
}
|
||||
if (!userInitiated && update.currentVersion.includes("-nightly.") && !nightlyPromptDue()) return;
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: t("app.update.available", { version: update.version }),
|
||||
|
||||
@@ -406,7 +406,10 @@ export function windowActions(): Action[] {
|
||||
title: "Move Tab to New Window",
|
||||
category: t("app.category.window"),
|
||||
when: "windowGrouped",
|
||||
run: () => call(commands.windowGroupDetach()),
|
||||
run: async ({ arg }) => {
|
||||
const label = typeof arg === "string" ? arg : useWindowGroup.getState().tabs.find((tab) => tab.current)?.label;
|
||||
if (label) await call(commands.windowGroupDetach(label));
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "window.selectTab",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const opened = vi.hoisted(() => [] as string[]);
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const ipc = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const doc = (path: string) => Promise.resolve({ status: "ok", data: { id: 3, path } });
|
||||
return {
|
||||
...ipc,
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
...ipc.commands,
|
||||
docOpen: (path: string) => (opened.push(`file ${path}`), doc(path)),
|
||||
docOpenVirtual: (uri: string) => (opened.push(`virtual ${uri}`), doc(uri)),
|
||||
docClose: () => Promise.resolve(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { withDocument } = await import("./ipc");
|
||||
|
||||
describe("withDocument", () => {
|
||||
it("opens a library type through its language server, a project file from disk", async () => {
|
||||
const uri = "jdt://contents/java.base/java.util/UUID.class?=demo/%5C/jdk%5C/lib%5C/jrt-fs.jar%60java.base";
|
||||
await withDocument(uri, async (doc) => doc);
|
||||
await withDocument("/p/src/App.java", async (doc) => doc);
|
||||
expect(opened).toEqual([`virtual ${uri}`, "file /p/src/App.java"]);
|
||||
});
|
||||
});
|
||||
@@ -134,7 +134,8 @@ export async function readManyFileLines(
|
||||
export async function withDocument<T>(path: string, fn: (doc: number) => Promise<T>): Promise<T> {
|
||||
const open = editorsFor(path)[0];
|
||||
if (open) return fn(open.ctx.doc);
|
||||
const info = await lspRequest(() => commands.docOpen(path));
|
||||
// Library types (`jdt://…`) are documents the language server provides, not files on disk.
|
||||
const info = await lspRequest(() => (isVirtualUri(path) ? commands.docOpenVirtual(path) : commands.docOpen(path)));
|
||||
try {
|
||||
return await fn(info.id);
|
||||
} finally {
|
||||
|
||||
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача