diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a9ad0e2..9054f05 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,7 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.100.0 with: components: rustfmt, clippy - uses: Swatinem/rust-cache@v2 @@ -56,12 +56,19 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.100.0 with: targets: x86_64-pc-windows-msvc - uses: Swatinem/rust-cache@v2 + - uses: actions/setup-node@v4 + with: + node-version: 22 - name: Test the native Windows backend run: cargo test --workspace --locked --target x86_64-pc-windows-msvc + - name: Build the native backend for run integration + run: cargo build --locked -p lithe-java-backend --target x86_64-pc-windows-msvc + - name: Execute current main and an individual JUnit method + run: node scripts/run/actions.mjs target/x86_64-pc-windows-msvc/debug/lithe-java-backend.exe package: name: Build and verify the macOS packages @@ -77,9 +84,15 @@ jobs: node-version: 22 # scripts/assemble-package.sh compiles the plugin backend for each # architecture it packages. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.100.0 with: targets: aarch64-apple-darwin, x86_64-apple-darwin + - name: Test the native macOS backend + run: cargo test --workspace --locked + - name: Build the native backend for run integration + run: cargo build --locked -p lithe-java-backend + - name: Execute current main and an individual JUnit method + run: node scripts/run/actions.mjs target/debug/lithe-java-backend # Downloads are named by their SHA-256 and verified again before use. - name: Restore verified third-party downloads uses: actions/cache@v4 @@ -137,7 +150,7 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.100.0 - uses: Swatinem/rust-cache@v2 - uses: actions/setup-node@v4 with: @@ -231,9 +244,7 @@ jobs: with: go-version-file: .artifacts/host/desktop/go.mod cache: false - - uses: dtolnay/rust-toolchain@master - with: - toolchain: 1.100.0 + - uses: dtolnay/rust-toolchain@1.100.0 - uses: actions/setup-node@v4 with: node-version: 22 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 605b30d..3aa8036 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,7 +24,7 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.100.0 with: components: rustfmt, clippy - uses: actions/setup-node@v4 @@ -52,7 +52,7 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.100.0 with: targets: x86_64-pc-windows-msvc - uses: Swatinem/rust-cache@v2 @@ -80,7 +80,7 @@ jobs: persist-credentials: false # scripts/assemble-package.sh compiles the plugin backend for each # architecture it packages. - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.100.0 with: targets: aarch64-apple-darwin, x86_64-apple-darwin - uses: actions/setup-node@v4 @@ -170,7 +170,7 @@ jobs: - uses: actions/checkout@v4 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.100.0 - uses: Swatinem/rust-cache@v2 - uses: actions/setup-node@v4 with: diff --git a/Cargo.toml b/Cargo.toml index 5b813ad..3c1eff6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ resolver = "2" [workspace.package] version = "0.1.0" edition = "2021" +rust-version = "1.100" license = "Apache-2.0" publish = false diff --git a/README.md b/README.md index 4e53196..a6267b0 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,14 @@ Spring/MyBatis 等既有能力不属于本轮 Maven 验收范围。 该 commit 的 SDK README/日志指南写有 `sdk-rust-v0.4.0` 发布标签,但远端当时没有这个标签或资产, 因此依赖固定到同一 Core commit,不把未发布标签当作可下载输入。 +## 当前文件与单个函数/测试运行 + +JDT 语义识别当前文件中的 `main`、JUnit 类和方法,提供 Run/Debug 入口;混合 main/test 类的类级入口优先显示测试动作。 + +点击前重新读取文档、校验路径和版本,保存成功后才启动;rerun 会重新验证当前声明。工作区相对路径统一使用 `/`,拒绝绝对路径、盘符、反斜杠、`.`、`..` 与控制字符。Linux 包的 ELF 可执行权限检查须在 Linux CI 验证。 + +2026-11-30,Windows 11 x64 的真实运行、精确单测试、陈旧版本、保存失败、rerun 和不安全路径回归通过。截图由固定 Viva 无头宿主生成,覆盖明暗主题、中英文及 before/after/hover,见 [截图目录](docs/assets/current-file-runs/)。macOS 原生窗口仍待 CI/实机复验。后端构建工具链固定 Rust 1.100.0。 + ## 功能 | 功能 | 说明 | @@ -292,7 +300,7 @@ scripts/ # 组装、校验、归档插件包,检查 SD MIGRATION.md # 主仓库路径到本仓库的映射、待宿主接口清单、主仓库删除清单 ``` -Rust 部分需要 Rust 工具链和 Cargo;macOS 打包脚本需要 macOS、Node.js 22、`zsh`、`curl`、`ditto`,不需要 Xcode 或 Swift 工具链。 +Rust 部分需要 Rust 1.100.0 工具链和 Cargo;macOS 打包脚本需要 macOS、Node.js 22、`zsh`、`curl`、`ditto`,不需要 Xcode 或 Swift 工具链。 打包脚本会用 `cargo build --release --locked -p lithe-java-backend --target ` 编译后端,所以还要安装两个 Apple target: `rustup target add aarch64-apple-darwin x86_64-apple-darwin`(`--arch arm64` 用前者,`x86_64` 用后者,`universal` 两个都编译再用 `lipo -create` 合并)。 diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 2f4b4f0..4e77f0b 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -3,6 +3,7 @@ name = "lithe-java-backend" description = "Plugin backend process of the Lithe Java Support plugin." version.workspace = true edition.workspace = true +rust-version.workspace = true license.workspace = true publish.workspace = true diff --git a/backend/src/run.rs b/backend/src/run.rs index a2cfc1d..b2bc64a 100644 --- a/backend/src/run.rs +++ b/backend/src/run.rs @@ -369,7 +369,7 @@ impl Target { _ => return Err(failure(RUN_INVALID_PARAMS, "The action names no kind.")), }; let path = text("path") - .filter(|path| !path.is_empty()) + .filter(|path| safe_document_path(path)) .ok_or_else(|| failure(RUN_INVALID_PARAMS, "The action names no document path."))?; let label = text("label") .filter(|label| !label.is_empty()) @@ -386,6 +386,17 @@ impl Target { } } +fn safe_document_path(path: &str) -> bool { + !path.is_empty() + && !path.contains(['\\', ':']) + && !path.chars().any(char::is_control) + && path.split('/').all(|part| !matches!(part, "" | "." | "..")) +} + +fn invalid_target() -> FunctionError { + FunctionError::internal("java.run.invalidTarget") +} + impl RunSession { pub fn new(handle: BackendHandle, settings: Arc) -> Self { Self { @@ -680,7 +691,7 @@ pub fn collect_actions_function( let path = params .pointer("/document/path") .and_then(Value::as_str) - .filter(|path| !path.is_empty()) + .filter(|path| safe_document_path(path)) .ok_or_else(|| failure(RUN_INVALID_PARAMS, "The document has no path."))?; let root = workspace_root(context.host(), reference)?; let uri = file_uri(&root.join(path))?; @@ -730,7 +741,7 @@ pub fn collect_actions_function( .iter() .take(MAX_ACTIONS) .enumerate() - .map(|(index, marker)| action(index, marker, path)) + .map(|(index, marker)| action(index, marker, path, !methods.is_empty())) .collect(); Ok(json!({"actions": actions})) } @@ -751,11 +762,16 @@ fn test_item_input(item: &CollectedTestItem) -> TestItemInput { /// One gutter action: `Run` with a `Debug` alternative, on the first column /// of the declaration line (one-based, half-open). -fn action(index: usize, marker: &JavaRunMarker, path: &str) -> Value { +fn action(index: usize, marker: &JavaRunMarker, path: &str, has_main: bool) -> Value { let line = marker.line + 1; let (kind, icon) = match marker.kind { JavaRunMarkerKind::Main => (TargetKind::Main, "run"), - JavaRunMarkerKind::TestClass | JavaRunMarkerKind::TestMethod => (TargetKind::Test, "test"), + // The toolbar selects the first Run-lane action in source order. A + // mixed main/test class must keep main as its current-file entry. + JavaRunMarkerKind::TestClass => { + (TargetKind::Test, if has_main { "test" } else { "run-all" }) + } + JavaRunMarkerKind::TestMethod => (TargetKind::Test, "test"), }; let target = |debug: bool| Target { debug, @@ -770,7 +786,7 @@ fn action(index: usize, marker: &JavaRunMarker, path: &str) -> Value { "id": format!("a{index}"), "range": { "start": {"line": line, "column": 1}, - "end": {"line": line, "column": 2}, + "end": {"line": line, "column": 1}, }, "title": format!("Run '{}'", marker.label), "icon": icon, @@ -790,11 +806,42 @@ pub fn run_action_function( params: Value, context: &Context, ) -> Result { + context.check_cancelled()?; let data = params .get("data") .filter(|data| data.is_object()) .ok_or_else(|| failure(RUN_INVALID_PARAMS, "The click carries no action data."))?; - start(session, &Target::from_value(data)?, context) + let target = Target::from_value(data)?; + let reference = workspace_context(context)?; + let host = context.host(); + let snapshot = host + .documents() + .get_snapshot(reference, json!({"documentID": params["documentID"]}))?; + if snapshot["document"]["path"] != target.path + || snapshot["document"]["version"] != params["expectedVersion"] + { + return Err(invalid_target()); + } + let actions = collect_actions_function(session, snapshot, context)?; + let valid = actions["actions"].as_array().is_some_and(|actions| { + actions.iter().any(|action| { + action["invoke"]["params"] == *data + || action["alternatives"].as_array().is_some_and(|choices| { + choices + .iter() + .any(|choice| choice["invoke"]["params"] == *data) + }) + }) + }); + if !valid { + return Err(invalid_target()); + } + host.request( + "lithe/host/documents/save", + json!({"context": reference.to_value(), + "documentID": params["documentID"], "expectedVersion": params["expectedVersion"]}), + )?; + start(session, &target, context) } /// Runs a rerun: the host passes the start's `rerun.data` as the params. @@ -803,7 +850,22 @@ pub fn rerun_function( params: Value, context: &Context, ) -> Result { - start(session, &Target::from_value(¶ms)?, context) + let reference = workspace_context(context)?; + let documents = context.host().documents().list(reference)?; + let document = documents["documents"] + .as_array() + .into_iter() + .flatten() + .find(|document| document["path"] == params["path"]) + .ok_or_else(invalid_target)?; + run_action_function( + session, + json!({ + "documentID": document["documentID"], + "expectedVersion": document["version"], "data": params + }), + context, + ) } /// Prepares the process of a target and asks the host to start it. @@ -1078,15 +1140,7 @@ fn test_process( LAUNCH_REQUEST_TIMEOUT_MILLISECONDS, ) .map_err(language_server_failed)?; - let items: Vec = match found { - Value::Null => Vec::new(), - value => serde_json::from_value(value).map_err(|_| { - failure( - RUN_LANGUAGE_SERVER_FAILED, - "The test items answered an unexpected shape.", - ) - })?, - }; + let items = launch_test_items(&found)?; let plan = jdt_test_items::plan_debug_launch(&items, &file_name, target.test_identifier.as_deref()) .map_err(|error| failure(RUN_NO_TESTS, error.message))?; @@ -1115,7 +1169,7 @@ fn test_process( testng_runner.as_deref(), ) .map_err(|error| failure(RUN_LANGUAGE_SERVER_FAILED, error.message))?; - let working_directory = relative_working_directory(root, &debug_target.working_directory); + let working_directory = relative_working_directory(root, &debug_target.working_directory)?; let listener = ResultListener::start( session.handle.host(), reference.clone(), @@ -1133,6 +1187,29 @@ fn test_process( )) } +/// JDT's wire ranges and string-valued levels must pass through the same +/// normalizer as gutter discovery before the typed launch planner reads them. +fn launch_test_items(found: &Value) -> Result, FunctionError> { + let normalized = normalize_java_test_items(found).ok_or_else(|| { + failure( + RUN_LANGUAGE_SERVER_FAILED, + "The test items answered an unexpected shape.", + ) + })?; + serde_json::from_value(serde_json::to_value(normalized.items).map_err(|_| { + failure( + RUN_LANGUAGE_SERVER_FAILED, + "The test items could not be normalized.", + ) + })?) + .map_err(|_| { + failure( + RUN_LANGUAGE_SERVER_FAILED, + "The test items could not be normalized.", + ) + }) +} + /// Turns the typed launch parameters the domain produces into `java` /// arguments: VM arguments, module path, classpath, main class, program /// arguments. @@ -1158,15 +1235,29 @@ fn testng_runner_path() -> Option { } /// Maps the absolute working directory JDT LS answers to the -/// workspace-relative form `run/start` accepts; a directory outside the -/// first folder falls back to the folder itself. -fn relative_working_directory(root: &Path, working_directory: &str) -> String { - let directory = Path::new(working_directory); - match directory.strip_prefix(root) { - Ok(relative) if relative.as_os_str().is_empty() => ".".to_owned(), - Ok(relative) => relative.to_string_lossy().into_owned(), - Err(_) => ".".to_owned(), - } +/// workspace-relative form `run/start` accepts. Resolve both paths before +/// comparing them, including Windows drive casing, verbatim paths and links. +fn relative_working_directory( + root: &Path, + working_directory: &str, +) -> Result { + let root = dunce::canonicalize(root).map_err(|_| invalid_target())?; + let directory = dunce::canonicalize(working_directory).map_err(|_| invalid_target())?; + if !directory.is_dir() { + return Err(invalid_target()); + } + let relative = directory.strip_prefix(root).map_err(|_| invalid_target())?; + if relative.as_os_str().is_empty() { + return Ok(".".to_owned()); + } + let relative = relative + .to_str() + .ok_or_else(invalid_target)? + .replace('\\', "/"); + if !safe_document_path(&relative) { + return Err(invalid_target()); + } + Ok(relative) } /// Counts the results the Eclipse JUnit runner streams to the result port @@ -1445,6 +1536,13 @@ fn workspace_context(context: &Context) -> Result<&WorkspaceContext, FunctionErr /// The local path of the workspace's first folder. fn workspace_root(host: &Host, reference: &WorkspaceContext) -> Result { let context = host.workspace().get_context(reference)?; + if context["authority"]["kind"] != "local" + || context["folders"] + .as_array() + .is_none_or(|folders| folders.len() != 1) + { + return Err(invalid_target()); + } context .pointer("/folders/0/path") .and_then(Value::as_str) @@ -1732,6 +1830,26 @@ mod tests { assert!(require_successful_build(&Value::Null).is_err()); } + #[test] + fn test_launch_uses_the_same_jdt_wire_normalization_as_discovery() { + let raw = json!([{ + "id": "class", "label": "RunSpec", "fullName": "demo.RunSpec", + "projectName": "RunActions", "testKind": "0", "testLevel": "5", + "children": [{ + "id": "method", "label": "selected()", "fullName": "demo.RunSpec#selected()", + "projectName": "RunActions", "testKind": "0", "testLevel": "6", + "jdtHandler": "=RunActions/src{timer=setTimeout(()=>reject(Error('Process cleanup timed out')),5000);})]);}finally{clearTimeout(timer);} } } diff --git a/scripts/run/actions.mjs b/scripts/run/actions.mjs new file mode 100644 index 0000000..1d35efc --- /dev/null +++ b/scripts/run/actions.mjs @@ -0,0 +1,92 @@ +// Real JDT LS -> plugin backend -> Java/JUnit. Host services are scripted; +// semantic targets, classpaths and runner arguments come from upstream JDT. +import assert from 'node:assert/strict'; +import {spawnSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {existsSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,rmSync,statSync,writeFileSync} from 'node:fs'; +import {dirname,join,resolve} from 'node:path'; +import {fileURLToPath,pathToFileURL} from 'node:url'; +import {performance} from 'node:perf_hooks'; +import {Client} from '../package/lsp-client.mjs'; +import {prepareRunPackage} from './prepare.mjs'; +import {preparedRuntimes} from '../package/jdtls-test-inputs.mjs'; + +const repository=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); +const backendPath=resolve(process.argv[2]??join(repository,'target/debug',process.platform==='win32'?'lithe-java-backend.exe':'lithe-java-backend')); +const prepared=process.env.LITHE_RUN_INPUTS?JSON.parse(readFileSync(process.env.LITHE_RUN_INPUTS)):prepareRunPackage(backendPath); +const {pkg,home,java,jdk}=prepared; +const stage=join(repository,'.artifacts/run'); +const root=mkdtempSync(join(stage,'project with spaces 中文 ')); +// Eclipse refuses a project that contains its own language-server workspace. +const runtime=mkdtempSync(join(stage,'runtime-')); +const manifest=JSON.parse(readFileSync(join(pkg,'plugin.json'))); +const reference={contextID:'run-test',generation:1}; +const folders=[{rootID:'root',name:'Run actions',path:root,uri:pathToFileURL(root).href}]; +const workspace={...reference,context:reference,authority:{kind:'local'},folders}; +const relative='src/demo/RunSpec.java'; +const source='package demo;\nimport org.junit.Test;\nimport static org.junit.Assert.*;\npublic class RunSpec {\n public static void main(String[] args) { System.out.println("MAIN_OK"); }\n\n @Test public void selected() { System.out.println("SELECTED_OK"); assertEquals(4, 2 + 2); }\n\n @Test public void sibling() { fail("SIBLING_MUST_NOT_RUN"); }\n}\n'; +mkdirSync(join(root,'src/demo'),{recursive:true});writeFileSync(join(root,relative),source); +// JUnit is a dependency of the Eclipse project, outside the plugin package. +writeFileSync(join(root,'.project'),'RunActionsorg.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature'); +writeFileSync(join(root,'.classpath'),''); +let backend,server,configuration={},operation=0,saveFailure=false; +let snapshot={document:{documentID:'document',version:1,path:relative},text:source}; +const launches=[],events=[],results=[],summaries=[]; +const inventory=directory=>{const items=[];function visit(path,label){if(statSync(path).isDirectory())for(const name of readdirSync(path).sort())visit(join(path,name),`${label}/${name}`);else items.push([label,createHash('sha256').update(readFileSync(path)).digest('hex')]);}visit(directory,'');return items;}; +const baseline=inventory(pkg),jdtBaseline=inventory(home); +const platform={os:{win32:'windows',darwin:'macos'}[process.platform]??process.platform,arch:process.arch==='arm64'?'arm64':'x86_64'}; +function invoke(functionID,params){return backend.request('lithe/function/invoke',{functionID,context:reference,operationID:`run-${++operation}`,params},150000);} +function click(action,version=snapshot.document.version){return invoke('java.runAction',{documentID:'document',expectedVersion:version,actionID:action.id,data:action.invoke.params});} +async function check(name,body){const start=performance.now();await body();results.push({name,milliseconds:Math.round(performance.now()-start)});console.log(`PASS ${name}`);} +function execute(plan){assert.deepEqual(plan.process.executable,{kind:'tool',tool:'java'});assert.equal(plan.temporaryFiles,undefined,'Fixture should not need a classpath JAR');const run=spawnSync(java,plan.process.arguments,{cwd:join(root,plan.process.workingDirectory),encoding:'utf8',timeout:60000,maxBuffer:4*1024*1024,windowsHide:true});backend.notify('lithe/host/run/didExit',{runID:`run-${launches.length}`,exitCode:run.status});assert.ifError(run.error);assert.equal(run.status,0,run.stdout+run.stderr);return run.stdout+run.stderr;} +try{ + backend=new Client(join(pkg,manifest.backend.launch.path),[],{windowsHide:true,hostRequests:{ + 'lithe/host/getCapabilities':()=>({services:{editor:{methods:['lithe/host/editor/registerActions']},run:{methods:['lithe/host/run/start']}}}), + 'lithe/host/workspace/listContexts':()=>({contexts:[workspace]}), + 'lithe/host/workspace/getContext':()=>workspace, + 'lithe/host/workspace/getFolders':()=>({folders}), + 'lithe/host/functions/providers':()=>({providers:[]}), + 'lithe/host/editor/registerActions':()=>({subscriptionID:`actions-${++operation}`}), + 'lithe/host/subscriptions/dispose':()=>({}), + 'lithe/host/languageServer/request':async p=>({value:await server.request(p.method,p.params,p.timeoutMilliseconds??60000)}), + 'lithe/host/languageServer/notify':p=>{if(p.method==='workspace/didChangeConfiguration')configuration=p.params.settings;server?.notify(p.method,p.params);return {};}, + 'lithe/host/documents/getSnapshot':()=>snapshot, + 'lithe/host/documents/list':()=>({documents:[snapshot.document]}), + 'lithe/host/documents/save':()=>{events.push('save');if(saveFailure)throw Error('Test save refused');writeFileSync(join(root,relative),snapshot.text);return {document:snapshot.document};}, + 'lithe/host/run/start':p=>{events.push('start');launches.push(p);return {runID:`run-${launches.length}`};}, + 'lithe/host/window/showInformation':p=>{summaries.push(p);return {};}, + 'lithe/host/window/showWarning':p=>{summaries.push(p);return {};}, + }}); + await backend.request('initialize',{capabilities:{experimental:{litheFunctions:{versions:[0]},litheLogging:{versions:[0]}}}});backend.notify('initialized',{}); + const inputs={home,java,jdkHome:jdk,tools:{'jdtls-runtime':{executable:java,home:jdk,version:'25.0.5'},java:{executable:java,home:jdk,version:'25.0.5'}}}; + const params={serverID:'java',platform,settings:{logLevel:'WARNING'},tools:inputs.tools}; + params.runtimes=await preparedRuntimes(backend,manifest,platform,inputs,`runtime-${++operation}`); + for(const [key,name] of Object.entries({stateDirectory:'state',workspaceStateDirectory:'workspace-state',logDirectory:'logs',temporaryDirectory:'tmp'})){params[key]=join(runtime,name);mkdirSync(params[key],{recursive:true});} + const launch=await invoke('java.resolveLaunch',params);configuration=launch.workspaceConfiguration; + server=new Client(java,launch.arguments,{windowsHide:true,env:{...process.env,...launch.environment},hostRequests:{'workspace/configuration':p=>p.items.map(item=>item.section?item.section.split('.').reduce((value,key)=>value?.[key],configuration)??null:configuration)}}); + await server.request('initialize',{processId:null,rootUri:pathToFileURL(root).href,workspaceFolders:[{uri:pathToFileURL(root).href,name:'Run actions'}],capabilities:{workspace:{configuration:true,workspaceFolders:true},textDocument:{publishDiagnostics:{}}},initializationOptions:launch.initializationOptions},120000);server.notify('initialized',{}); + backend.notify('lithe/host/languageServer/didChangeState',{context:reference,serverID:'java',generation:1,state:'running'}); + const uri=pathToFileURL(join(root,relative)).href; + server.notify('textDocument/didOpen',{textDocument:{uri,languageId:'java',version:1,text:source}}); + const deadline=performance.now()+90000;let actions=[]; + while(performance.now()a.title.includes('selected')))break;await new Promise(resolve=>setTimeout(resolve,200));} + const main=actions.find(a=>a.icon==='run'),selected=actions.find(a=>a.title.includes('selected')); + assert.ok(main,JSON.stringify(actions));assert.ok(selected,JSON.stringify(actions)); + await check('current file runs the main class found by JDT',async()=>{events.length=0;await click(main);assert.deepEqual(events,['save','start']);assert.match(execute(launches.at(-1)),/MAIN_OK/);}); + await check('single JUnit method excludes a failing sibling',async()=>{await click(selected);const output=execute(launches.at(-1));assert.match(output,/SELECTED_OK/);assert.doesNotMatch(output,/SIBLING_MUST_NOT_RUN/);}); + await check('stale version never saves or starts',async()=>{events.length=0;await assert.rejects(click(selected,0));assert.deepEqual(events,[]);}); + await check('save failure blocks execution',async()=>{events.length=0;saveFailure=true;try{await assert.rejects(click(selected));assert.deepEqual(events,['save']);}finally{saveFailure=false;}}); + await check('rerun revalidates the open document',async()=>{events.length=0;await invoke('java.rerun',selected.invoke.params);assert.deepEqual(events,['save','start']);execute(launches.at(-1));}); + await check('removed declaration never launches',async()=>{snapshot={...snapshot,document:{...snapshot.document,version:2},text:source.replace('selected()', 'renamed()')};server.notify('textDocument/didChange',{textDocument:{uri,version:2},contentChanges:[{text:snapshot.text}]});events.length=0;await assert.rejects(click(selected));assert.deepEqual(events,[]);}); + await check('unsafe paths are rejected',async()=>{for(const path of ['../RunSpec.java','C:/RunSpec.java','a\\RunSpec.java','/RunSpec.java'])await assert.rejects(invoke('java.collectActions',{document:{path},text:source}));}); + assert.deepEqual(inventory(pkg),baseline,'Installed package changed');assert.deepEqual(inventory(home),jdtBaseline,'JDT LS files changed'); + writeFileSync(join(stage,'evidence.json'),JSON.stringify({platform:process.platform,architecture:process.arch,results,fixtures:[{path:relative,text:source,actions}],commands:launches.map(p=>p.process)},null,2)); +}catch(error){ + const log=join(runtime,'workspace-state/data/.metadata/.log'); + if(existsSync(log))writeFileSync(join(stage,'last-failure.log'),readFileSync(log)); + throw error; +}finally{ + try{ + for(const client of [server,backend]){if(!client)continue;try{await client.request('shutdown',null,5000);client.notify('exit',null);}catch{}try{await client.close();}catch(error){console.error('Client cleanup failed:',error.message);process.exitCode=1;}} + }finally{rmSync(root,{recursive:true,force:true});rmSync(runtime,{recursive:true,force:true});rmSync(pkg,{recursive:true,force:true});} +} diff --git a/scripts/run/host.json b/scripts/run/host.json new file mode 100644 index 0000000..eda372d --- /dev/null +++ b/scripts/run/host.json @@ -0,0 +1,5 @@ +{ + "repository": "https://github.com/1lck/Lithe-IDEA", + "revision": "4191c1553486247026c767ccd52b5cd9e8f38115", + "coreRevision": "d426f018065c950754140295e857bc71b870139f" +} diff --git a/scripts/run/prepare.mjs b/scripts/run/prepare.mjs new file mode 100644 index 0000000..784dfd5 --- /dev/null +++ b/scripts/run/prepare.mjs @@ -0,0 +1,82 @@ +// Integration-test inputs only. Verify the same upstream pins as the release +// preparation script; keep all downloads and generated files in this checkout. +import assert from 'node:assert/strict'; +import {execFileSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {cpSync,existsSync,mkdirSync,mkdtempSync,readFileSync,renameSync,rmSync,writeFileSync} from 'node:fs'; +import {basename,dirname,join,resolve} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {prepareTestJDK} from '../package/prepare-test-jdk.mjs'; +import {buildProjectModelBundle} from '../package/project-model-bundle.mjs'; + +const root=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); +const stage=join(root,'.artifacts/run'); +const pins=JSON.parse(readFileSync(join(root,'third_party/jdtls/manifest.json'))); +const hash=path=>createHash('sha256').update(readFileSync(path)).digest('hex'); +const tar=process.platform==='win32'?join(process.env.SystemRoot,'System32/tar.exe'):'tar'; +function tool(command,args){return execFileSync(command,args,{stdio:['ignore','pipe','inherit'],timeout:180000,windowsHide:true});} +function download(url,sha){ + const path=join(stage,'downloads',`${sha}-${basename(new URL(url).pathname)}`); + mkdirSync(dirname(path),{recursive:true}); + if(existsSync(path)&&hash(path)===sha)return path; + const partial=`${path}.${process.pid}.partial`; + try{ + tool('curl',['--fail','--silent','--show-error','--location','--proto','=https','--proto-redir','=https','--connect-timeout','20','--max-time','160','--output',partial,url]); + assert.equal(hash(partial),sha,`Checksum: ${url}`);renameSync(partial,path);return path; + }finally{rmSync(partial,{force:true});} +} +export function prepareRunPackage(backend){ + mkdirSync(stage,{recursive:true}); + const home=join(stage,`jdtls-${pins.archiveSHA256}`); + if(!existsSync(join(home,'manifest.json'))){ + const work=mkdtempSync(join(stage,'jdtls-stage-')); + try{ + tool(tar,['-xf',download(pins.archiveURL,pins.archiveSHA256),'-C',work]); + const copy=(url,sha,path)=>{mkdirSync(dirname(path),{recursive:true});cpSync(download(url,sha),path);}; + copy(pins.licenseURL,pins.licenseSHA256,join(work,'LICENSE-EPL-2.0.txt')); + copy(pins.lombokURL,pins.lombokSHA256,join(work,'lombok/lombok.jar')); + copy(pins.lombokLicenseURL,pins.lombokLicenseSHA256,join(work,'lombok/LICENSE-MIT.txt')); + const unpack=mkdtempSync(join(stage,'vsix-stage-')); + try{ + tool(tar,['-xf',download(pins.javaDebugArchiveURL,pins.javaDebugArchiveSHA256),'-C',unpack]); + const name=`com.microsoft.java.debug.plugin-${pins.javaDebugServerVersion}.jar`; + mkdirSync(join(work,'java-debug'));cpSync(join(unpack,'extension/server',name),join(work,'java-debug',name)); + assert.equal(hash(join(work,'java-debug',name)),pins.javaDebugPluginSHA256); + copy(pins.javaDebugLicenseURL,pins.javaDebugLicenseSHA256,join(work,'java-debug/LICENSE-EPL-1.0.txt')); + }finally{rmSync(unpack,{recursive:true,force:true});} + const tests=mkdtempSync(join(stage,'vsix-stage-')); + try{ + tool(tar,['-xf',download(pins.javaTestArchiveURL,pins.javaTestArchiveSHA256),'-C',tests]); + const manifest=JSON.parse(readFileSync(join(tests,'extension/package.json'))),bundles=[]; + mkdirSync(join(work,'java-test/extensions'),{recursive:true});mkdirSync(join(work,'java-test/runner')); + for(const entry of manifest.contributes.javaExtensions){ + const name=basename(entry);if(existsSync(join(work,'plugins',name)))continue; + cpSync(join(tests,'extension',entry),join(work,'java-test/extensions',name));bundles.push(name); + } + writeFileSync(join(work,'java-test/extensions.txt'),`${bundles.join('\n')}\n`); + const runner='com.microsoft.java.test.runner-jar-with-dependencies.jar'; + cpSync(join(tests,'extension/server',runner),join(work,'java-test/runner',runner)); + assert.equal(hash(join(work,'java-test/runner',runner)),pins.javaTestRunnerSHA256); + assert.equal(hash(join(work,'java-test/extensions',`com.microsoft.java.test.plugin-${pins.javaTestPluginVersion}.jar`)),pins.javaTestPluginSHA256); + copy(pins.javaTestLicenseURL,pins.javaTestLicenseSHA256,join(work,'java-test/LICENSE-MIT.txt')); + }finally{rmSync(tests,{recursive:true,force:true});} + writeFileSync(join(work,'manifest.json'),JSON.stringify(pins)); + tool(process.execPath,[join(root,'scripts/package/jdtls-runtime-profile.mjs'),work]); + renameSync(work,home); + }finally{rmSync(work,{recursive:true,force:true});} + } + tool(process.execPath,[join(root,'scripts/package/jdtls-runtime-profile.mjs'),home]); + const java=prepareTestJDK(),jdk=dirname(dirname(java)); + const pkg=mkdtempSync(join(stage,'package-')); + try{ + const manifest=JSON.parse(readFileSync(join(root,'io.github.lithe-idea.java-support/plugin.json'))); + manifest.backend.launch.path=`bin/lithe-java-backend${process.platform==='win32'?'.exe':''}`; + mkdirSync(join(pkg,'bin'));cpSync(backend,join(pkg,manifest.backend.launch.path)); + writeFileSync(join(pkg,'plugin.json'),JSON.stringify(manifest)); + for(const name of ['lombok','java-debug','java-test','manifest.json'])cpSync(join(home,name),join(pkg,'jdtls-extensions',name),{recursive:true}); + process.env.LITHE_JAVAC=join(jdk,'bin',process.platform==='win32'?'javac.exe':'javac'); + process.env.LITHE_JAR=join(jdk,'bin',process.platform==='win32'?'jar.exe':'jar'); + buildProjectModelBundle(home,join(pkg,'jdtls-extensions')); + return {pkg,home,java,jdk}; + }catch(error){rmSync(pkg,{recursive:true,force:true});throw error;} +} diff --git a/scripts/run/process.mjs b/scripts/run/process.mjs new file mode 100644 index 0000000..d3ae40f --- /dev/null +++ b/scripts/run/process.mjs @@ -0,0 +1,37 @@ +// Integration-test tools run in owned process trees with bounded output and cleanup. +import {spawn,execFile} from 'node:child_process'; +const LIMIT=2*1024*1024; +export function runTool(tool,args,{cwd,env=process.env,timeout=120000}={}) { + let command=tool,parameters=args,verbatim=false; + if(process.platform==='win32'&&/\.(cmd|bat)$/i.test(tool)) { + const quote=value=>{if(/["%\r\n]/.test(value))throw Error('Unsupported batch test argument');return `"${value}"`;}; + command=process.env.ComSpec??'cmd.exe';parameters=['/d','/v:off','/s','/c',`"${[tool,...args].map(quote).join(' ')}"`];verbatim=true; + } + return new Promise((resolve,reject)=>{ + const child=spawn(command,parameters,{cwd,env,detached:process.platform!=='win32',windowsHide:true,windowsVerbatimArguments:verbatim,stdio:['ignore','pipe','pipe']}); + let output=Buffer.alloc(0),errorOutput=Buffer.alloc(0),failure,done=false,stopping=false,cleanup; + const kill=()=>{ + if(!child.pid)return; + if(process.platform==='win32') { + if(child.exitCode!==null)return; + execFile('taskkill.exe',['/PID',String(child.pid),'/T','/F'],{timeout:5000,windowsHide:true},error=>{if(error&&child.exitCode===null)failure??=error;}); + } else {try{process.kill(-child.pid,'SIGKILL');}catch(error){if(error.code!=='ESRCH')failure??=error;}} + }; + const finish=()=>{ + if(done)return;done=true;clearTimeout(timer);clearTimeout(cleanup); + process.off('SIGINT',interrupt);process.off('SIGTERM',interrupt); + if(failure)reject(failure);else if(child.exitCode!==0)reject(Error(`Tool failed (${child.exitCode}): ${errorOutput.toString()}\n${output.toString()}`));else resolve(output); + }; + const stop=error=>{ + failure??=error;if(stopping)return;stopping=true;kill(); + cleanup=setTimeout(()=>{kill();child.stdout.destroy();child.stderr.destroy();child.unref();failure=Error('Tool cleanup timed out',{cause:failure});finish();},6000); + }; + const interrupt=()=>stop(Error('Tool interrupted')); + const timer=setTimeout(()=>stop(Error('Tool timed out')),timeout); + process.once('SIGINT',interrupt);process.once('SIGTERM',interrupt); + child.stdout.on('data',bytes=>{if(output.length+bytes.length>LIMIT)stop(Error('Tool output exceeds limit'));else output=Buffer.concat([output,bytes]);}); + child.stderr.on('data',bytes=>{if(errorOutput.length+bytes.length>LIMIT)stop(Error('Tool error output exceeds limit'));else errorOutput=Buffer.concat([errorOutput,bytes]);}); + child.once('error',error=>stop(error)); + child.once('close',()=>{kill();finish();}); + }); +} diff --git a/scripts/run/visual.mjs b/scripts/run/visual.mjs new file mode 100644 index 0000000..1c8e070 --- /dev/null +++ b/scripts/run/visual.mjs @@ -0,0 +1,42 @@ +// Render actual backend presentation fields in the pinned Viva workbench. +// This overlay remains in the plugin checkout; the host is never edited. +import assert from 'node:assert/strict'; +import {readFileSync,writeFileSync,mkdirSync,existsSync} from 'node:fs'; +import {resolve,join,dirname,delimiter} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {runTool} from './process.mjs'; +const root=resolve(dirname(fileURLToPath(import.meta.url)),'../..'); +if(!process.argv[2])throw Error('Usage: node scripts/run/visual.mjs '); +const host=resolve(process.argv[2]); +const bashCandidates=process.platform==='win32' + ? [process.env.LITHE_TEST_BASH,join(process.env.ProgramFiles??'C:\\Program Files','Git','usr','bin','bash.exe'),join(process.env['ProgramFiles(x86)']??'C:\\Program Files (x86)','Git','usr','bin','bash.exe'),'bash.exe'].filter(Boolean) + : [process.env.LITHE_TEST_BASH??'bash']; +const bash=bashCandidates.find(candidate=>candidate==='bash.exe'||candidate==='bash'||existsSync(candidate)); +if(!bash)throw Error('Git Bash is required on Windows; set LITHE_TEST_BASH to bash.exe'); +const visualEnv={...process.env}; +if(process.platform==='win32'&&existsSync(bash)) { + const bashDirectory=dirname(resolve(bash)); + const pathKey=Object.keys(visualEnv).find(key=>key.toLowerCase()==='path')??'PATH'; + visualEnv[pathKey]=[bashDirectory,visualEnv[pathKey]].filter(Boolean).join(delimiter); +} +const pin=JSON.parse(readFileSync(join(root,'scripts/run/host.json'))); +const revision=(await runTool('git',['-C',host,'rev-parse','HEAD'])).toString().trim(); +assert.equal(revision,pin.revision,'Use the pinned host for reproducible images'); +const stage=join(root,'.artifacts/run');mkdirSync(stage,{recursive:true}); +const evidence=JSON.parse(readFileSync(join(stage,'evidence.json'))); +const fixtures=evidence.fixtures.map(fixture=>({Path:fixture.path,Text:fixture.text,Actions:fixture.actions.map(action=>({ + ID:action.id,Title:action.title,Icon:action.icon, + Range:{StartLine:action.range.start.line,StartColumn:action.range.start.column,EndLine:action.range.end.line,EndColumn:action.range.end.column}, + Alternatives:(action.alternatives??[]).map(choice=>({ID:choice.id,Title:choice.title,Icon:choice.icon})) +}))})); +const projection=join(stage,'projection.json');writeFileSync(projection,JSON.stringify(fixtures)); +const overlay=join(stage,'visual-overlay.json'); +writeFileSync(overlay,JSON.stringify({Replace:{[join(host,'desktop/internal/workbench/plugin_run_actions_visual_test.go')]:join(root,'e2e/host/desktop/internal/workbench/plugin_run_actions_visual_test.go')}})); +const output=join(root,'docs/assets/current-file-runs');mkdirSync(output,{recursive:true}); +const args=['scripts/desktop/desktop-go.sh','test','-json','-overlay',overlay,'-tags','vivahead lithevisual','./internal/workbench','-run','^TestPluginRunActionsVisual$','-count=1','-timeout=120s']; +const log=await runTool(bash,args,{cwd:host,timeout:600000,env:{...visualEnv,LITHE_RUN_PROJECTION:projection,LITHE_RUN_VISUAL_OUTPUT:output}}); +writeFileSync(join(stage,'visual-tests.jsonl'),log); +const timings=log.toString().split('\n').filter(Boolean).map(line=>JSON.parse(line)).filter(event=>event.Action==='pass'&&event.Test).map(event=>({test:event.Test,seconds:event.Elapsed})); +assert.ok(timings.length>1,'No screenshot scenarios ran'); +writeFileSync(join(stage,'visual-timing.json'),JSON.stringify({host:pin,platform:process.platform,architecture:process.arch,size:[1440,900],timings},null,2)); +console.log(`PASS ${timings.length-1} Viva screenshot scenarios (${process.platform}/${process.arch}); output: docs/assets/current-file-runs`);