From 82952eb1d5abe25e1e24f4fe8630fe3465ba5044 Mon Sep 17 00:00:00 2001 From: HennyNile <11811410@mail.sustech.edu.cn> Date: Sat, 10 Aug 2024 21:59:06 +0000 Subject: [PATCH] Fix: enable parameter values to start with @ --- .../java/com/beust/jcommander/JCommander.java | 38 ++++++++++++++----- .../com/beust/jcommander/JCommanderTest.java | 3 +- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/beust/jcommander/JCommander.java b/src/main/java/com/beust/jcommander/JCommander.java index 067929c3..f459a28c 100644 --- a/src/main/java/com/beust/jcommander/JCommander.java +++ b/src/main/java/com/beust/jcommander/JCommander.java @@ -457,17 +457,11 @@ private String[] expandArgs(String[] originalArgv) { List vResult1 = Lists.newArrayList(); // - // Expand @ + // Expand dynamic args // for (String arg : originalArgv) { - - if (arg.startsWith("@") && options.expandAtSign) { - String fileName = arg.substring(1); - vResult1.addAll(readFile(fileName)); - } else { - List expanded = expandDynamicArg(arg); - vResult1.addAll(expanded); - } + List expanded = expandDynamicArg(arg); + vResult1.addAll(expanded); } // Expand separators @@ -735,6 +729,32 @@ private void parseValues(String[] args, boolean validate) { boolean isDashDash = false; // once we encounter --, everything goes into the main parameter while (i < args.length && !commandParsed) { String arg = args[i]; + + // + // Expand @ + // + if (arg.startsWith("@") && options.expandAtSign) { + String fileName = arg.substring(1); + List fileArgs = readFile(fileName); + + // Create a new array to hold the expanded arguments + String[] newArgs = new String[args.length + fileArgs.size() - 1]; + + // Copy the existing arguments before the '@' argument + System.arraycopy(args, 0, newArgs, 0, i); + + // Copy the arguments from the file + for (int j = 0; j < fileArgs.size(); j++) { + newArgs[i + j] = fileArgs.get(j); + } + + // Copy the remaining arguments after the '@' argument + System.arraycopy(args, i + 1, newArgs, i + fileArgs.size(), args.length - i - 1); + + args = newArgs; + continue; + } + String a = trim(arg); args[i] = a; p("Parsing arg: " + a); diff --git a/src/test/java/com/beust/jcommander/JCommanderTest.java b/src/test/java/com/beust/jcommander/JCommanderTest.java index dbc03d77..4200ac94 100644 --- a/src/test/java/com/beust/jcommander/JCommanderTest.java +++ b/src/test/java/com/beust/jcommander/JCommanderTest.java @@ -1055,8 +1055,7 @@ class Params { Assert.assertEquals(params.username, "@tzellman"); } - @Test(enabled = true, description = "Enable top-level @/ampersand file expansion, which should throw in this case", - expectedExceptions = ParameterException.class) + @Test public void enabledAtSignExpansionTest() { class Params { @Parameter(names = {"-username"})