Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CAMEL-21896: camel-jbang - Allow configuration preset per directory #17593

Merged
merged 3 commits into from
Mar 31, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
package org.apache.camel.dsl.jbang.core.commands;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Expand Down Expand Up @@ -129,8 +131,17 @@ protected Printer printer() {

protected void printConfigurationValues(String header) {
if (spec != null) {
final Properties configProperties = new Properties();
CommandLineHelper.loadProperties(configProperties::putAll);
Properties configProperties = new Properties();
Path userConfigInCurrentDirectory = Path.of(CommandLineHelper.USER_CONFIG);
if (main.isMergeUserConfigurations()) {
CommandLineHelper.loadProperties(configProperties::putAll, false);
if (Files.exists(userConfigInCurrentDirectory)) {
CommandLineHelper.loadProperties(configProperties::putAll, true);
}
} else {
boolean isLocalConfiguration = Files.exists(userConfigInCurrentDirectory);
CommandLineHelper.loadProperties(configProperties::putAll, isLocalConfiguration);
}
List<String> lines = new ArrayList<>();
spec.options().forEach(opt -> {
if (Arrays.stream(opt.names()).anyMatch(name ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
*/
package org.apache.camel.dsl.jbang.core.commands;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import org.apache.camel.catalog.CamelCatalog;
Expand Down Expand Up @@ -72,6 +74,8 @@ public static void run(String... args) {
run(new CamelJBangMain(), args);
}

private static boolean mergeUserConfigurations;

public static void run(CamelJBangMain main, String... args) {
// set pid as system property as logging ${sys:pid} needs to be resolved on windows
try {
Expand Down Expand Up @@ -192,11 +196,34 @@ public static void run(CamelJBangMain main, String... args) {
return new String[] { v };
});

CommandLineHelper.augmentWithUserConfiguration(commandLine, args);
List<String> arguments = new ArrayList<>(args.length);
mergeUserConfigurations = isMergeUserConfigurations(args, mergeUserConfigurations, arguments);
args = arguments.toArray(new String[0]);
CommandLineHelper.augmentWithUserConfiguration(commandLine, mergeUserConfigurations);
int exitCode = commandLine.execute(args);
main.quit(exitCode);
}

/**
* The option --mergeConfigurations is used only during PicoCLI UserConfigDefaultProvider initialization if args
* contains the string --mergeConfigurations, it is removed, this way, it won't mess with PicoCLI @CommandLine.*
*
* @param args
* @param mergeConfigurations
* @param arguments
* @return
*/
private static boolean isMergeUserConfigurations(String[] args, boolean mergeConfigurations, List<String> arguments) {
for (String arg : args) {
if ("--mergeConfigurations".equals(arg)) {
mergeConfigurations = true;
} else {
arguments.add(arg);
}
}
return mergeConfigurations;
}

/**
* Finish this main with given exit code. By default, uses system exit to terminate. Subclasses may want to
* overwrite this exit behavior e.g. during unit tests.
Expand Down Expand Up @@ -244,4 +271,8 @@ public CamelJBangMain withPrinter(Printer out) {
public static CommandLine getCommandLine() {
return commandLine;
}

public boolean isMergeUserConfigurations() {
return mergeUserConfigurations;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ public class ConfigGet extends CamelCommand {
@CommandLine.Parameters(description = "Configuration key", arity = "1")
String key;

@CommandLine.Option(names = { "--local" }, description = "Retrieve configurations from current directory")
boolean local;

public ConfigGet(CamelJBangMain main) {
super(main);
}
Expand All @@ -43,7 +46,7 @@ public Integer doCall() throws Exception {
} else {
printer().println(key + " key not found");
}
});
}, local);

return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
@CommandLine.Command(name = "list", description = "Displays user configuration", sortOptions = false, showDefaultValues = true)
public class ConfigList extends CamelCommand {

@CommandLine.Option(names = { "--local" }, description = "Retrieve configurations from current directory")
boolean local;

public ConfigList(CamelJBangMain main) {
super(main);
}
Expand All @@ -36,7 +39,7 @@ public Integer doCall() throws Exception {
String v = p.getProperty(k);
printer().printf("%s = %s%n", k, v);
}
});
}, local);
return 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,16 @@ public class ConfigSet extends CamelCommand {
@CommandLine.Parameters(description = "Configuration parameter (ex. key=value)", arity = "1")
String configuration;

@CommandLine.Option(names = { "--local" }, description = "Retrieve configurations from current directory")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The wording should be "Store ... to" instead of "Retrieve ... from" here.

boolean local;

public ConfigSet(CamelJBangMain main) {
super(main);
}

@Override
public Integer doCall() throws Exception {
CommandLineHelper.createPropertyFile();
CommandLineHelper.createPropertyFile(local);

if (configuration.split("=").length == 1) {
printer().println("Configuration parameter not in key=value format");
Expand All @@ -46,8 +49,8 @@ public Integer doCall() throws Exception {
String key = StringHelper.before(configuration, "=").trim();
String value = StringHelper.after(configuration, "=").trim();
properties.put(key, value);
CommandLineHelper.storeProperties(properties, printer());
});
CommandLineHelper.storeProperties(properties, printer(), local);
}, local);

return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ public class ConfigUnset extends CamelCommand {
@CommandLine.Parameters(description = "Configuration key", arity = "1")
String key;

@CommandLine.Option(names = { "--local" }, description = "Retrieve configurations from current directory")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Unset" instead of "Retrieve"

boolean local;

public ConfigUnset(CamelJBangMain main) {
super(main);
}
Expand All @@ -36,8 +39,8 @@ public ConfigUnset(CamelJBangMain main) {
public Integer doCall() throws Exception {
CommandLineHelper.loadProperties(properties -> {
properties.remove(key);
CommandLineHelper.storeProperties(properties, printer());
});
CommandLineHelper.storeProperties(properties, printer(), local);
}, local);

return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
showDefaultValues = true)
public class VersionGet extends CamelCommand {

@CommandLine.Option(names = { "--local" }, description = "Retrieve configurations from current directory")
boolean local;

public VersionGet(CamelJBangMain main) {
super(main);
}
Expand Down Expand Up @@ -63,7 +66,7 @@ public Integer doCall() throws Exception {
printer().println(" repos = " + repos);
}
}
});
}, local);

return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,16 @@ public class VersionSet extends CamelCommand {
@CommandLine.Option(names = { "--reset" }, description = "Reset by removing any custom version settings")
boolean reset;

@CommandLine.Option(names = { "--local" }, description = "Retrieve configurations from current directory")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Store ... to" over "Retrieve ... from"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or if we want the same wording for all options, we should consider a more generic wording. Examples:
"Apply configrations to current directoyr", or
"Use local configurations instead of global"?

boolean local;

public VersionSet(CamelJBangMain main) {
super(main);
}

@Override
public Integer doCall() throws Exception {
CommandLineHelper.createPropertyFile();
CommandLineHelper.createPropertyFile(local);

CommandLineHelper.loadProperties(properties -> {
if (reset) {
Expand All @@ -67,8 +70,8 @@ public Integer doCall() throws Exception {
properties.put("runtime", runtime.runtime());
}
}
CommandLineHelper.storeProperties(properties, printer());
});
CommandLineHelper.storeProperties(properties, printer(), local);
}, local);

return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
import java.util.function.Consumer;

Expand All @@ -41,22 +44,47 @@ private CommandLineHelper() {
super();
}

public static void augmentWithUserConfiguration(CommandLine commandLine, String... args) {
File file = getUserPropertyFile();
public static void augmentWithUserConfiguration(CommandLine commandLine, boolean mergeConfigurations) {
File file = getUserConfigurationFile();
if (file.isFile() && file.exists()) {
commandLine.setDefaultValueProvider(new CamelUserConfigDefaultValueProvider(file));
Properties properties = new Properties();
try {
if (mergeConfigurations) {
properties.load(new FileReader(getUserPropertyFile(false)));
}

properties.load(new FileReader(file));
} catch (IOException e) {
commandLine.setDefaultValueProvider(new CamelUserConfigDefaultValueProvider(file));
}

commandLine.setDefaultValueProvider(new CamelUserConfigDefaultValueProvider(properties));
}
}

public static void createPropertyFile() throws IOException {
File file = getUserPropertyFile();
private static File getUserConfigurationFile() {
File file;
if (Files.exists(Path.of(USER_CONFIG))) {
file = new File(USER_CONFIG);
} else {
file = getUserPropertyFile(false);
}
return file;
}

public static void createPropertyFile(boolean local) throws IOException {
File file = getUserPropertyFile(local);
if (!file.exists()) {
file.createNewFile();
}
}

public static void loadProperties(Consumer<Properties> consumer) {
File file = getUserPropertyFile();
loadProperties(consumer, false);
}

public static void loadProperties(Consumer<Properties> consumer, boolean local) {
File file = getUserPropertyFile(local);
if (file.isFile() && file.exists()) {
FileInputStream fis = null;
try {
Expand All @@ -72,8 +100,8 @@ public static void loadProperties(Consumer<Properties> consumer) {
}
}

public static void storeProperties(Properties properties, Printer printer) {
File file = getUserPropertyFile();
public static void storeProperties(Properties properties, Printer printer, boolean local) {
File file = getUserPropertyFile(local);
if (file.isFile() && file.exists()) {
try (FileOutputStream fos = new FileOutputStream(file)) {
properties.store(fos, null);
Expand All @@ -85,8 +113,18 @@ public static void storeProperties(Properties properties, Printer printer) {
}
}

private static File getUserPropertyFile() {
return new File(homeDir, USER_CONFIG);
/**
* Get the config file in current directory (local = true) or the default one
*
* @param local
* @return
*/
private static File getUserPropertyFile(boolean local) {
if (local) {
return new File(USER_CONFIG);
} else {
return new File(homeDir, USER_CONFIG);
}
}

/**
Expand Down Expand Up @@ -131,6 +169,10 @@ private static class CamelUserConfigDefaultValueProvider extends CommandLine.Pro
public CamelUserConfigDefaultValueProvider(File file) {
super(file);
}

public CamelUserConfigDefaultValueProvider(Properties properties) {
super(properties);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,19 @@ private UserConfigHelper() {
}

public static void createUserConfig(String content) throws IOException {
CommandLineHelper.useHomeDir("target");
Path userConfigDir = Paths.get("target");
if (!userConfigDir.toFile().exists()) {
userConfigDir.toFile().mkdirs();
createUserConfig(content, false);
}

public static void createUserConfig(String content, boolean local) throws IOException {
Path userConfigDir;
if (!local) {
CommandLineHelper.useHomeDir("target");
userConfigDir = Paths.get("target");
if (!userConfigDir.toFile().exists()) {
userConfigDir.toFile().mkdirs();
}
} else {
userConfigDir = Paths.get(".");
}

Files.writeString(userConfigDir.resolve(CommandLineHelper.USER_CONFIG), content,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* 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.
*/
package org.apache.camel.dsl.jbang.core.commands.config;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.apache.camel.dsl.jbang.core.commands.CamelCommandBaseTest;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
import org.junit.jupiter.api.AfterEach;

public class BaseConfigTest extends CamelCommandBaseTest {

@AfterEach
void removeLocalConfigFile() throws IOException {
Files.deleteIfExists(Paths.get(CommandLineHelper.USER_CONFIG));
}
}
Loading
Loading