From cb29cf5a28e8da08c537520f9f07b3d6862fa974 Mon Sep 17 00:00:00 2001 From: Bartosz Popiela Date: Wed, 11 Nov 2026 03:13:53 +0100 Subject: [PATCH] feat(vscode): separate runtime Kamelets directory from editor catalog Validate camel.localKameletDir for JBang run/export, await validation in runtime and deploy callers, and keep Karavan.kameletsPath editor-only. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- karavan-vscode/README.md | 17 ++ karavan-vscode/package.json | 10 +- karavan-vscode/src/exec.ts | 19 +- karavan-vscode/src/jbang.ts | 25 +-- karavan-vscode/src/utils.ts | 15 ++ karavan-vscode/test/runtime-kamelets.test.cjs | 169 ++++++++++++++++++ 6 files changed, 235 insertions(+), 20 deletions(-) create mode 100644 karavan-vscode/test/runtime-kamelets.test.cjs diff --git a/karavan-vscode/README.md b/karavan-vscode/README.md index 9ac6efb9d41..d57b163f4cf 100644 --- a/karavan-vscode/README.md +++ b/karavan-vscode/README.md @@ -68,6 +68,23 @@ Build-in catalogues: The **Camel version** extension setting controls the version passed to Camel JBang. Leave it empty to omit `-Dcamel.jbang.version` and let Camel JBang select its default version. +## Runtime Kamelets directory + +Set **Camel: Local Kamelet Dir** (`camel.localKameletDir`) to pass +`--local-kamelet-dir` to Camel JBang run/export (including runtime run and deploy): + +```json +{ + "camel.localKameletDir": "C:\\camel\\runtime-kamelets" +} +``` + +This must be an existing local directory, not a YAML file or URL. Leave it empty +to omit the JBang option. It does not affect the editor's Kamelet catalog. +`Karavan.kameletsPath` is now editor-only and is never passed to Camel JBang. +If you previously used `Karavan.kameletsPath` for runtime Kamelets, also set +`camel.localKameletDir` to that directory. + ## Run integration locally * Run in UI: click `Run` button diff --git a/karavan-vscode/package.json b/karavan-vscode/package.json index ce902f98e29..6db1863cd5b 100644 --- a/karavan-vscode/package.json +++ b/karavan-vscode/package.json @@ -111,10 +111,17 @@ "scope": "machine", "order": 60 }, + "camel.localKameletDir": { + "type": "string", + "default": "", + "description": "Local Kamelet directory for Camel JBang run/export (--local-kamelet-dir). Does not affect the editor catalog.", + "scope": "machine", + "order": 64 + }, "Karavan.kameletsPath": { "type": "string", "default": "", - "description": "Custom Kamelets Path", + "description": "Custom Kamelets directory for the editor only. Does not affect Camel JBang run/export.", "scope": "machine", "order": 65 }, @@ -677,6 +684,7 @@ "lint": "eslint src webview", "lint:fix": "eslint --fix src webview", "test": "node ./out/test/runTest.js", + "test:runtime-kamelets": "node --test test/runtime-kamelets.test.cjs", "open-in-browser": "vscode-test-web --extensionDevelopmentPath=. ../karavan-demo/hello-world/" }, "dependencies": { diff --git a/karavan-vscode/src/exec.ts b/karavan-vscode/src/exec.ts index 3dda92a47fd..fce20bfe391 100644 --- a/karavan-vscode/src/exec.ts +++ b/karavan-vscode/src/exec.ts @@ -45,14 +45,17 @@ export function execTerminalCommand(terminalId: string, command: string, env?: { } export async function runWithRuntime(fullPath: string, run?: boolean) { - const runtime = await utils.getRuntime(); - let command = jbang.createExportCommand(fullPath, runtime); - if (run) { + try { const runtime = await utils.getRuntime(); - const mvn = runtime === 'quarkus' ? "quarkus:dev" : (runtime === 'spring-boot' ? "spring-boot:run" : "camel:run"); - command = command.concat(" && mvn clean compile ").concat(mvn).concat(" -f ").concat(fullPath); + let command = await jbang.createExportCommand(fullPath, runtime); + if (run) { + const mvn = runtime === 'quarkus' ? "quarkus:dev" : (runtime === 'spring-boot' ? "spring-boot:run" : "camel:run"); + command = command.concat(" && mvn clean compile ").concat(mvn).concat(" -f ").concat(fullPath); + } + execTerminalCommand("runtime-run", command); + } catch (err) { + window.showErrorMessage(`Karavan: failed to export project: ${err instanceof Error ? err.message : String(err)}`); } - execTerminalCommand("runtime-run", command); } export function camelDeploy(directory: string) { @@ -61,7 +64,7 @@ export function camelDeploy(directory: string) { utils.getTarget(), utils.getExportFolder(), execCommand("oc project -q"), // get namespace - ]).then(val => { + ]).then(async val => { const runtime = val[0] || ''; const target = val[1] || ''; const exportFolder = val[2] || ''; @@ -72,7 +75,7 @@ export function camelDeploy(directory: string) { window.showErrorMessage("Namespace not set \n" + val[3].error); } const deployCommand: string = workspace.getConfiguration().get("Karavan.".concat(runtime.replaceAll("-", "")).concat(utils.capitalize(target)).concat("Deploy")) || ''; - const command = jbang.createExportCommand(directory, runtime).concat(" && ").concat(deployCommand).concat(" -f ").concat(exportFolder); + const command = (await jbang.createExportCommand(directory, runtime)).concat(" && ").concat(deployCommand).concat(" -f ").concat(exportFolder); execTerminalCommand("deploy", command, env); }).catch((reason: any) => { window.showErrorMessage("Error: \n" + reason.message); diff --git a/karavan-vscode/src/jbang.ts b/karavan-vscode/src/jbang.ts index 6148626dab1..c424ef9108d 100644 --- a/karavan-vscode/src/jbang.ts +++ b/karavan-vscode/src/jbang.ts @@ -50,22 +50,26 @@ function prepareCommand(command: string): string { return "jbang" + versionOption + " camel@apache/camel " + command; } -export function camelJbangRun() { +export async function camelJbangRun() { const maxMessages: number = workspace.getConfiguration().get("camel.maxMessages") || -1; - const kameletsPath: string | undefined = workspace.getConfiguration().get("Karavan.kameletsPath"); const dev: boolean = workspace.getConfiguration().get("camel.dev") || false; - const cmd = "run * " - + (maxMessages > -1 ? " --max-messages=" + maxMessages : "") - + (kameletsPath && kameletsPath.trim().length > 0 ? " --local-kamelet-dir=" + kameletsPath : ""); - const command = prepareCommand(cmd) + (dev === true ? " --dev" : ""); - exec.execTerminalCommand("jbang-run", command); + try { + const kameletsPath = await utils.getLocalKameletsDirectory(); + const cmd = "run * " + + (maxMessages > -1 ? " --max-messages=" + maxMessages : "") + + (kameletsPath ? ` --local-kamelet-dir="${kameletsPath}"` : ""); + const command = prepareCommand(cmd) + (dev === true ? " --dev" : ""); + exec.execTerminalCommand("jbang-run", command); + } catch (err) { + window.showErrorMessage(`Karavan: failed to run project: ${err instanceof Error ? err.message : String(err)}`); + } } -export function createExportCommand(fullPath: string, runtime: string) { - const kameletsPath: string | undefined = workspace.getConfiguration().get("Karavan.kameletsPath"); +export async function createExportCommand(fullPath: string, runtime: string) { + const kameletsPath = await utils.getLocalKameletsDirectory(); const cmd = "export --fresh " + (fullPath ? " --directory=" + fullPath : '') - + (kameletsPath && kameletsPath.trim().length > 0 ? " --local-kamelet-dir=" + kameletsPath : ""); + + (kameletsPath ? ` --local-kamelet-dir="${kameletsPath}"` : ""); return prepareCommand(cmd); } @@ -84,4 +88,3 @@ function executeJbangCommand(rootPath: string, command: string, callback: (code: window.showErrorMessage("JBang not found!"); } } - diff --git a/karavan-vscode/src/utils.ts b/karavan-vscode/src/utils.ts index 527d6fff78b..81b638e16cc 100644 --- a/karavan-vscode/src/utils.ts +++ b/karavan-vscode/src/utils.ts @@ -75,6 +75,21 @@ export async function readKamelets(context: ExtensionContext) { return yamls; } +export async function getLocalKameletsDirectory(): Promise { + const source = workspace.getConfiguration().get("camel.localKameletDir")?.trim(); + if (!source) { + return undefined; + } + if (/^https?:\/\//i.test(source)) { + throw new Error("camel.localKameletDir must point to a local directory, not a URL"); + } + const fileStat = await stat(path.resolve(source)); + if (!(fileStat.type & FileType.Directory)) { + throw new Error("camel.localKameletDir must point to a directory, not a file"); + } + return source; +} + async function readBuildInKamelets(context: ExtensionContext) { const kameletsPath = path.join(context.extensionPath, 'metadata', "kamelets.yaml"); try { diff --git a/karavan-vscode/test/runtime-kamelets.test.cjs b/karavan-vscode/test/runtime-kamelets.test.cjs new file mode 100644 index 00000000000..e8faa793867 --- /dev/null +++ b/karavan-vscode/test/runtime-kamelets.test.cjs @@ -0,0 +1,169 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const assert = require("node:assert/strict"); +const {readFileSync} = require("node:fs"); +const Module = require("node:module"); +const path = require("node:path"); +const {beforeEach, test} = require("node:test"); +const ts = require("typescript"); +const yaml = require("js-yaml"); + +let settings; +let directories; +let files; +let errors; +let commands; +const context = {extensionPath: path.resolve("extension")}; +const builtinPath = path.join(context.extensionPath, "metadata", "kamelets.yaml"); +const kamelet = "kind: Kamelet\nmetadata:\n name: builtin\n"; +const vscode = { + FileType: {File: 1, Directory: 2}, + Uri: {file: fullPath => ({fsPath: fullPath})}, + ThemeIcon: class {}, + workspace: { + getConfiguration: () => ({get: key => settings[key]}), + fs: { + stat: async uri => { + if (directories.has(uri.fsPath)) return {type: 2}; + if (files.has(uri.fsPath)) return {type: 1}; + throw new Error("File not found"); + }, + readFile: async uri => Buffer.from(files.get(uri.fsPath)), + }, + }, + window: { + showErrorMessage: message => errors.push(message), + createTerminal: () => ({show() {}, dispose() {}, sendText: command => commands.push(command)}), + }, +}; + +// Exercise the command builders and callers without launching VS Code or terminals. +function loadSource(filename, mocks) { + const fullPath = path.join(__dirname, "..", "src", filename); + const loaded = new Module(fullPath, module); + loaded.filename = fullPath; + loaded.paths = module.paths; + loaded.require = request => { + if (request in mocks) return mocks[request]; + if (request.startsWith("@karavan-core/")) return {}; + return require(request); + }; + loaded._compile(ts.transpileModule(readFileSync(fullPath, "utf8"), { + compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true}, + }).outputText, fullPath); + return loaded.exports; +} + +const utils = loadSource("utils.ts", {vscode}); +const jbang = loadSource("jbang.ts", { + vscode, + "./utils": utils, + "./exec": {execTerminalCommand: (_id, command) => commands.push(command)}, + shelljs: {}, +}); +const exec = loadSource("exec.ts", { + vscode, + "./utils": { + ...utils, + getRuntime: async () => "quarkus", + getTarget: async () => "kubernetes", + getExportFolder: async () => ".export", + }, + "./jbang": jbang, + shelljs: {exec: (_command, callback) => callback(0, "namespace", "")}, +}); + +beforeEach(() => { + settings = {}; + directories = new Set(); + files = new Map([[builtinPath, kamelet]]); + errors = []; + commands = []; +}); + +test("editor sources never affect Camel JBang run/export", async () => { + for (const source of [path.resolve("custom"), path.resolve("catalog.yaml"), "http://example.invalid/catalog", "https://example.invalid/catalog", ""]) { + settings["Karavan.kameletsPath"] = source; + const command = await jbang.createExportCommand("export", "camel-main"); + await jbang.camelJbangRun(); + for (const actual of [command, commands.at(-1)]) { + assert.equal(actual.includes("--local-kamelet-dir="), false); + } + } + assert.deepEqual(errors, []); +}); + +test("the runtime directory is trimmed, quoted and does not change the editor catalog", async () => { + const directory = path.resolve("runtime kamelets"); + directories.add(directory); + settings["camel.localKameletDir"] = ` ${directory} `; + assert.deepEqual((await utils.readKamelets(context)).map(document => yaml.load(document)), [yaml.load(kamelet)]); + const command = await jbang.createExportCommand("export", "camel-main"); + await jbang.camelJbangRun(); + await exec.runWithRuntime("project", true); + for (const actual of [command, ...commands]) { + assert.ok(actual.includes(`--local-kamelet-dir="${directory}"`)); + } + assert.match(commands.at(-1), /&& mvn clean compile quarkus:dev -f project$/); + assert.deepEqual(errors, []); +}); + +test("unset and whitespace-only runtime settings omit the option", async () => { + for (const value of [undefined, "", " "]) { + settings["camel.localKameletDir"] = value; + assert.equal(await utils.getLocalKameletsDirectory(), undefined); + assert.equal((await jbang.createExportCommand("export", "camel-main")).includes("--local-kamelet-dir"), false); + await jbang.camelJbangRun(); + assert.equal(commands.at(-1).includes("--local-kamelet-dir"), false); + } +}); + +test("files, URLs and missing directories prevent run and export", async () => { + const file = path.resolve("catalog.yaml"); + files.set(file, kamelet); + for (const value of [file, "http://example.invalid/catalog", "https://example.invalid/catalog", path.resolve("missing")]) { + settings["camel.localKameletDir"] = value; + await assert.rejects(jbang.createExportCommand("export", "camel-main"), /must point to a (local )?directory|File not found/); + await jbang.camelJbangRun(); + await exec.runWithRuntime("project"); + } + assert.deepEqual(commands, []); + assert.equal(errors.length, 8); + assert.match(errors[0], /failed to run project/); + assert.match(errors[1], /failed to export project/); +}); + +test("deploy awaits directory validation and reports errors without starting a terminal", async () => { + settings["camel.localKameletDir"] = path.resolve("missing"); + exec.camelDeploy("project"); + await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(commands, []); + assert.match(errors[0], /File not found/); +}); + +test("deploy includes the validated runtime directory and deployment command", async () => { + const directory = path.resolve("runtime kamelets"); + directories.add(directory); + settings["camel.localKameletDir"] = directory; + settings["Karavan.quarkusKubernetesDeploy"] = "mvn clean package"; + exec.camelDeploy("project"); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(commands.length, 1); + assert.ok(commands[0].includes(`--local-kamelet-dir="${directory}"`)); + assert.match(commands[0], /&& mvn clean package -f .export$/); + assert.deepEqual(errors, []); +});