Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions karavan-vscode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
10 changes: 9 additions & 1 deletion karavan-vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
},
Expand Down Expand Up @@ -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": {
Expand Down
19 changes: 11 additions & 8 deletions karavan-vscode/src/exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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] || '';
Expand All @@ -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);
Expand Down
25 changes: 14 additions & 11 deletions karavan-vscode/src/jbang.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand All @@ -84,4 +88,3 @@ function executeJbangCommand(rootPath: string, command: string, callback: (code:
window.showErrorMessage("JBang not found!");
}
}

15 changes: 15 additions & 0 deletions karavan-vscode/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,21 @@ export async function readKamelets(context: ExtensionContext) {
return yamls;
}

export async function getLocalKameletsDirectory(): Promise<string | undefined> {
const source = workspace.getConfiguration().get<string>("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 {
Expand Down
169 changes: 169 additions & 0 deletions karavan-vscode/test/runtime-kamelets.test.cjs
Original file line number Diff line number Diff line change
@@ -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, []);
});