This is an automated email from the ASF dual-hosted git repository.

gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven.git


The following commit(s) were added to refs/heads/master by this push:
     new 6098b8e40e fix(cli): preserve quoted empty arguments in settings and 
JVM configuration
6098b8e40e is described below

commit 6098b8e40e32149c7359e0b850cfc71e5b79b6a8
Author: Amar Ghugare <[email protected]>
AuthorDate: Thu Nov 19 18:07:09 2026 +0530

    fix(cli): preserve quoted empty arguments in settings and JVM configuration
    
    fix(cli): preserve quoted empty arguments in settings and JVM configuration
    
    - Track whether a token has started independently of its length so that
      `""` and `''` produce an empty argument token instead of being silently
      dropped; inline `<options>`/`<alias>` and structured `<arg/>` forms now
      produce identical argument lists
    - Generalise the backslash escape rules: outside quotes backslashes are
      literal; inside double-quoted strings only `\"` and `\\` are recognised
      as escapes, all other backslashes stay literal; unquoted
      backslash-space sequences no longer combine words into one argument
      (migration: use `"-Dfoo=hello world"` instead of `-Dfoo=hello\ world`)
    - Preserve unquoted Windows paths including `-javaagent:D:\a\...` and
      UNC paths without modification
    - Throw `IllegalArgumentException` with a clear message on unclosed
      single or double quotes, caught in `main()` and reported as a
      configuration error so Maven exits cleanly instead of launching with
      wrong options
    - Keep the standalone `JvmConfigParser` algorithm in sync with the
      settings `ArgumentTokenizer`; remove unused CLI wrapper
    - Expand project-directory placeholders after tokenisation so substituted
      spaces and Windows backslashes remain literal
    - Backported to `maven-4.0.x` (#14076): same empty-argument and
      unclosed-quote fixes; backslash-escape semantics change is intentionally
      excluded (unquoted backslashes continue to act as escapes on 4.0.x with
      a deprecation warning to migrate before 4.2.0)
---
 apache-maven/pom.xml                               |   5 +
 .../src/assembly/maven/bin/JvmConfigParser.java    |  67 ++++++++------
 .../src/test/java/JvmConfigParserTest.java         |  90 ++++++++++++++++++
 .../maven/cling/invoker/mvn/ArgumentTokenizer.java |  59 ------------
 .../cling/invoker/mvn/ArgumentTokenizerTest.java   |   8 +-
 .../cling/invoker/mvn/MavenInvokerAliasTest.java   |   1 +
 .../maven/settings/v4/ArgumentTokenizer.java       |  35 ++++---
 .../maven/settings/v4/ArgumentTokenizerTest.java   | 103 +++++++++++++++++++++
 .../maven/settings/v4/SettingsStaxReaderTest.java  |  77 +++++++++++++++
 9 files changed, 342 insertions(+), 103 deletions(-)

diff --git a/apache-maven/pom.xml b/apache-maven/pom.xml
index f9a7291975..4dbe388366 100644
--- a/apache-maven/pom.xml
+++ b/apache-maven/pom.xml
@@ -33,6 +33,11 @@ under the License.
   <description>The Apache Maven distribution, source and binary, in zip and 
tar.gz formats.</description>
 
   <dependencies>
+    <dependency>
+      <groupId>org.junit.jupiter</groupId>
+      <artifactId>junit-jupiter</artifactId>
+      <scope>test</scope>
+    </dependency>
     <dependency>
       <groupId>org.apache.maven</groupId>
       <artifactId>maven-cli</artifactId>
diff --git a/apache-maven/src/assembly/maven/bin/JvmConfigParser.java 
b/apache-maven/src/assembly/maven/bin/JvmConfigParser.java
index 93b8011568..1c2a877250 100644
--- a/apache-maven/src/assembly/maven/bin/JvmConfigParser.java
+++ b/apache-maven/src/assembly/maven/bin/JvmConfigParser.java
@@ -77,10 +77,10 @@ public static void main(String[] args) {
                 System.out.print(result);
                 System.out.flush();
             }
-        } catch (IOException e) {
+        } catch (IOException | IllegalArgumentException e) {
             // If jvm.config exists but can't be read, this is a configuration 
error
             // Print clear error and exit with error code to prevent Maven 
from running
-            System.err.println("ERROR: Failed to read .mvn/jvm.config: " + 
e.getMessage());
+            System.err.println("ERROR: Failed to process .mvn/jvm.config: " + 
e.getMessage());
             System.err.println("Please check file permissions and syntax.");
             System.err.flush();
             System.exit(1);
@@ -95,36 +95,29 @@ static String parseJvmConfig(Path jvmConfigPath, String 
mavenProjectBasedir) thr
         StringBuilder result = new StringBuilder();
 
         for (String line : Files.readAllLines(jvmConfigPath, 
StandardCharsets.UTF_8)) {
-            line = processLine(line, mavenProjectBasedir);
+            line = processLine(line);
             if (line.isEmpty()) {
                 continue;
             }
 
             List<String> parsed = parseArguments(line);
-            appendQuotedArguments(result, parsed);
+            appendQuotedArguments(result, parsed, mavenProjectBasedir);
         }
 
         return result.toString();
     }
 
     /**
-     * Process a single line: remove comments, trim whitespace, and replace 
placeholders.
+     * Process a single line: remove comments and trim whitespace.
      */
-    private static String processLine(String line, String mavenProjectBasedir) 
{
+    private static String processLine(String line) {
         // Remove comments
         int commentIndex = line.indexOf('#');
         if (commentIndex >= 0) {
             line = line.substring(0, commentIndex);
         }
 
-        // Trim whitespace
-        line = line.trim();
-
-        // Replace MAVEN_PROJECTBASEDIR placeholders
-        line = line.replace("${MAVEN_PROJECTBASEDIR}", mavenProjectBasedir);
-        line = line.replace("$MAVEN_PROJECTBASEDIR", mavenProjectBasedir);
-
-        return line;
+        return line.trim();
     }
 
     /**
@@ -135,8 +128,11 @@ private static String processLine(String line, String 
mavenProjectBasedir) {
      * Quoting is always valid in {@code @argfile} format and ensures safe 
parsing
      * by both the Windows and Unix JVM {@code @argfile} consumers.
      */
-    private static void appendQuotedArguments(StringBuilder result, 
List<String> args) {
+    private static void appendQuotedArguments(StringBuilder result, 
List<String> args, String mavenProjectBasedir) {
         for (String arg : args) {
+            // Expand after tokenization so spaces and backslashes in the 
project path remain literal.
+            arg = arg.replace("${MAVEN_PROJECTBASEDIR}", mavenProjectBasedir)
+                    .replace("$MAVEN_PROJECTBASEDIR", mavenProjectBasedir);
             if (result.length() > 0) {
                 result.append(' ');
             }
@@ -150,36 +146,51 @@ private static void appendQuotedArguments(StringBuilder 
result, List<String> arg
     /**
      * Parse a line into individual arguments, respecting quoted strings.
      * Quotes are stripped from the arguments.
+     * Keep this algorithm in sync with 
org.apache.maven.settings.v4.ArgumentTokenizer.tokenize.
      */
-    private static List<String> parseArguments(String line) {
+    private static List<String> parseArguments(String input) {
         List<String> args = new ArrayList<>();
         StringBuilder current = new StringBuilder();
         boolean inDoubleQuotes = false;
         boolean inSingleQuotes = false;
-
-        for (int i = 0; i < line.length(); i++) {
-            char c = line.charAt(i);
-
-            if (c == '"' && !inSingleQuotes) {
+        boolean tokenStarted = false;
+
+        for (int i = 0; i < input.length(); i++) {
+            char c = input.charAt(i);
+
+            if (c == '\\'
+                    && inDoubleQuotes
+                    && i + 1 < input.length()
+                    && (input.charAt(i + 1) == '"' || input.charAt(i + 1) == 
'\\')) {
+                current.append(input.charAt(++i));
+                tokenStarted = true;
+            } else if (c == '"' && !inSingleQuotes) {
                 inDoubleQuotes = !inDoubleQuotes;
+                tokenStarted = true;
             } else if (c == '\'' && !inDoubleQuotes) {
                 inSingleQuotes = !inSingleQuotes;
-            } else if (c == ' ' && !inDoubleQuotes && !inSingleQuotes) {
-                // Space outside quotes - end of argument
-                if (current.length() > 0) {
+                tokenStarted = true;
+            } else if (Character.isWhitespace(c) && !inDoubleQuotes && 
!inSingleQuotes) {
+                if (tokenStarted) {
                     args.add(current.toString());
                     current.setLength(0);
+                    tokenStarted = false;
                 }
             } else {
                 current.append(c);
+                tokenStarted = true;
             }
         }
 
-        // Add last argument
-        if (current.length() > 0) {
+        if (tokenStarted) {
             args.add(current.toString());
         }
 
-        return args;
+        if (inDoubleQuotes || inSingleQuotes) {
+            throw new IllegalArgumentException(
+                    "Unclosed " + (inDoubleQuotes ? "double" : "single") + " 
quote in: " + input);
+        }
+
+        return List.copyOf(args);
     }
-}
\ No newline at end of file
+}
diff --git a/apache-maven/src/test/java/JvmConfigParserTest.java 
b/apache-maven/src/test/java/JvmConfigParserTest.java
new file mode 100644
index 0000000000..40da74cfad
--- /dev/null
+++ b/apache-maven/src/test/java/JvmConfigParserTest.java
@@ -0,0 +1,90 @@
+/*
+ * 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.
+ */
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class JvmConfigParserTest {
+    @TempDir
+    Path tempDir;
+
+    static Stream<Arguments> arguments() {
+        return Stream.of(
+                Arguments.of("first \"\" third", "\"first\" \"\" \"third\""),
+                Arguments.of("'' \"\"", "\"\" \"\""),
+                Arguments.of("first\t\"\"\tthird", "\"first\" \"\" \"third\""),
+                Arguments.of("fi\"\"rst ''third", "\"first\" \"third\""),
+                Arguments.of("-Dname=\"hello world\"", "\"-Dname=hello 
world\""),
+                Arguments.of("hello\\ world", "\"hello\\\\\" \"world\""),
+                Arguments.of("\"a\\\"b\"", "\"a\\\"b\""),
+                Arguments.of(
+                        "-javaagent:D:\\a\\maven\\target\\agent.jar",
+                        
"\"-javaagent:D:\\\\a\\\\maven\\\\target\\\\agent.jar\""),
+                Arguments.of("\"-Dpath=C:\\Program Files\\Maven\"", 
"\"-Dpath=C:\\\\Program Files\\\\Maven\""),
+                Arguments.of(
+                        "-javaagent:\\\\server\\share\\agent.jar",
+                        "\"-javaagent:\\\\\\\\server\\\\share\\\\agent.jar\""),
+                Arguments.of("'-Dpath=C:\\temp\\config'", 
"\"-Dpath=C:\\\\temp\\\\config\""),
+                Arguments.of("  \t  ", ""));
+    }
+
+    @ParameterizedTest
+    @MethodSource("arguments")
+    void tokenizesArguments(String input, String expected) throws Exception {
+        Path config = tempDir.resolve("jvm.config");
+        Files.writeString(config, input);
+        assertEquals(expected, JvmConfigParser.parseJvmConfig(config, 
tempDir.toString()));
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"\"\" '", "'' \""})
+    void rejectsUnclosedQuotes(String input) throws Exception {
+        Path config = tempDir.resolve("jvm.config");
+        Files.writeString(config, input);
+        assertThrows(IllegalArgumentException.class, () -> 
JvmConfigParser.parseJvmConfig(config, tempDir.toString()));
+    }
+
+    @Test
+    void preservesProjectBasedirAfterTokenization() throws Exception {
+        Path config = tempDir.resolve("jvm.config");
+        Files.writeString(config, "'-Dfirst=${MAVEN_PROJECTBASEDIR}/first' 
\"-Dsecond=$MAVEN_PROJECTBASEDIR/second\"");
+        assertEquals(
+                "\"-Dfirst=C:\\\\Program Files\\\\Maven/first\" 
\"-Dsecond=C:\\\\Program Files\\\\Maven/second\"",
+                JvmConfigParser.parseJvmConfig(config, "C:\\Program 
Files\\Maven"));
+    }
+
+    @Test
+    void preservesUnquotedProjectBasedirWithSpaces() throws Exception {
+        Path config = tempDir.resolve("jvm.config");
+        Files.writeString(config, "-Dpath=$MAVEN_PROJECTBASEDIR/settings");
+        assertEquals(
+                "\"-Dpath=C:\\\\Program Files\\\\Maven/settings\"",
+                JvmConfigParser.parseJvmConfig(config, "C:\\Program 
Files\\Maven"));
+    }
+}
diff --git 
a/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/ArgumentTokenizer.java
 
b/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/ArgumentTokenizer.java
deleted file mode 100644
index b832680ce4..0000000000
--- 
a/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvn/ArgumentTokenizer.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.maven.cling.invoker.mvn;
-
-import java.util.List;
-
-/**
- * Quote-aware argument tokenizer for the shorthand form of {@code <options>} 
and {@code <alias>} elements
- * in {@code settings.xml}.
- *
- * <p>The algorithm is identical to {@code JvmConfigParser.parseArguments()} 
(the single-file source launcher
- * used by shell scripts to parse {@code .mvn/jvm.config}):
- * <ul>
- *   <li>Whitespace is the delimiter outside quotes.</li>
- *   <li>{@code "..."} and {@code '...'} are both supported — quotes are 
stripped, content is kept as a
- *       single token.</li>
- *   <li>Outside single-quotes, a backslash ({@code \}) escapes the next 
character literally
- *       (e.g. {@code \"} → {@code "}, {@code \\} → {@code \}, {@code \ } → a 
literal space).
- *       Inside single-quotes, backslash has no special meaning.</li>
- * </ul>
- *
- * <p><strong>Note:</strong> {@code JvmConfigParser.java} is a self-contained 
single-file source launcher
- * invoked directly by shell scripts; it must not share classpath code with 
Maven. This class is an
- * independent re-implementation of the same algorithm for use within Maven's 
Java classpath.
- *
- * @since 4.2.0
- */
-public final class ArgumentTokenizer {
-
-    private ArgumentTokenizer() {
-        // utility class
-    }
-
-    /**
-     * Splits a string into a list of argument tokens using quote-aware 
whitespace splitting.
-     *
-     * @param input the input string to tokenize, must not be {@code null}
-     * @return an unmodifiable list of token strings; empty if the input 
contains only whitespace
-     */
-    public static List<String> tokenize(String input) {
-        return org.apache.maven.settings.v4.ArgumentTokenizer.tokenize(input);
-    }
-}
diff --git 
a/impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/ArgumentTokenizerTest.java
 
b/impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/ArgumentTokenizerTest.java
index ead5a52393..be76d8faea 100644
--- 
a/impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/ArgumentTokenizerTest.java
+++ 
b/impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/ArgumentTokenizerTest.java
@@ -50,13 +50,13 @@ void singleQuotes() {
     }
 
     @Test
-    void backslashEscapeSpace() {
-        assertEquals(List.of("-Dfoo=hello world"), 
ArgumentTokenizer.tokenize("-Dfoo=hello\\ world"));
+    void backslashOutsideQuotesIsLiteral() {
+        assertEquals(List.of("-Dfoo=hello\\", "world"), 
ArgumentTokenizer.tokenize("-Dfoo=hello\\ world"));
     }
 
     @Test
     void backslashEscapeDoubleQuote() {
-        assertEquals(List.of("-Dfoo=say \"hi\""), 
ArgumentTokenizer.tokenize("-Dfoo=say\\ \\\"hi\\\""));
+        assertEquals(List.of("-Dfoo=say \"hi\""), 
ArgumentTokenizer.tokenize("\"-Dfoo=say \\\"hi\\\"\""));
     }
 
     @Test
@@ -73,7 +73,7 @@ void backslashNoSpecialInsideSingleQuotes() {
 
     @Test
     void backslashEscapeBackslash() {
-        assertEquals(List.of("a\\b"), ArgumentTokenizer.tokenize("a\\\\b"));
+        assertEquals(List.of("a\\b"), 
ArgumentTokenizer.tokenize("\"a\\\\b\""));
     }
 
     @Test
diff --git 
a/impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/MavenInvokerAliasTest.java
 
b/impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/MavenInvokerAliasTest.java
index 0824a9ebfb..03061bdf65 100644
--- 
a/impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/MavenInvokerAliasTest.java
+++ 
b/impl/maven-cli/src/test/java/org/apache/maven/cling/invoker/mvn/MavenInvokerAliasTest.java
@@ -24,6 +24,7 @@
 
 import org.apache.maven.api.settings.Alias;
 import org.apache.maven.api.settings.Settings;
+import org.apache.maven.settings.v4.ArgumentTokenizer;
 import org.junit.jupiter.api.Test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
diff --git 
a/impl/maven-support/src/main/java/org/apache/maven/settings/v4/ArgumentTokenizer.java
 
b/impl/maven-support/src/main/java/org/apache/maven/settings/v4/ArgumentTokenizer.java
index eac729d6f9..fc9c70713b 100644
--- 
a/impl/maven-support/src/main/java/org/apache/maven/settings/v4/ArgumentTokenizer.java
+++ 
b/impl/maven-support/src/main/java/org/apache/maven/settings/v4/ArgumentTokenizer.java
@@ -25,20 +25,23 @@
  * Quote-aware argument tokenizer for the shorthand form of {@code <options>} 
and {@code <alias>} elements
  * in {@code settings.xml}.
  *
- * <p>The algorithm is identical to {@code JvmConfigParser.parseArguments()} 
(the single-file source launcher
- * used by shell scripts to parse {@code .mvn/jvm.config}):</p>
+ * <p>Tokenization follows these rules:</p>
  * <ul>
  *   <li>Whitespace is the delimiter outside quotes.</li>
  *   <li>{@code "..."} and {@code '...'} are both supported — quotes are 
stripped, content is kept as a
- *       single token.</li>
- *   <li>Outside single-quotes, a backslash ({@code \}) escapes the next 
character literally
- *       (e.g. {@code \"} → {@code "}, {@code \\} → {@code \}, {@code \ } → a 
literal space).
- *       Inside single-quotes, backslash has no special meaning.</li>
+ *       single token, including an empty argument when the quotes contain no 
text.</li>
+ *   <li>Inside double quotes, a backslash escapes a double quote or another 
backslash.
+ *       Other backslashes are literal, including those in unquoted Windows 
paths.
+ *       Use quotes around arguments containing whitespace.</li>
  * </ul>
  *
+ * <p><strong>Migration note:</strong> If you previously used a 
backslash-space ({@code \\ }) to embed a
+ * space in an argument (e.g. {@code -Dfoo=hello\ world}), replace it with a 
quoted argument:
+ * {@code "-Dfoo=hello world"}. Unquoted backslashes are now always treated as 
literal characters.</p>
+ *
  * <p><strong>Note:</strong> {@code JvmConfigParser.java} is a self-contained 
single-file source launcher
- * invoked directly by shell scripts; it must not share classpath code with 
Maven. This class is an
- * independent re-implementation of the same algorithm for use within Maven's 
Java classpath.</p>
+ * invoked directly by shell scripts; it must not share classpath code with 
Maven. Keep this tokenization
+ * algorithm in sync with its {@code parseArguments} method.</p>
  *
  * @since 4.2.0
  */
@@ -59,28 +62,36 @@ public static List<String> tokenize(String input) {
         StringBuilder current = new StringBuilder();
         boolean inDoubleQuotes = false;
         boolean inSingleQuotes = false;
+        boolean tokenStarted = false;
 
         for (int i = 0; i < input.length(); i++) {
             char c = input.charAt(i);
 
-            if (c == '\\' && !inSingleQuotes && i + 1 < input.length()) {
-                // Backslash escape: outside single-quotes, \X is always a 
literal X.
+            if (c == '\\'
+                    && inDoubleQuotes
+                    && i + 1 < input.length()
+                    && (input.charAt(i + 1) == '"' || input.charAt(i + 1) == 
'\\')) {
                 current.append(input.charAt(++i));
+                tokenStarted = true;
             } else if (c == '"' && !inSingleQuotes) {
                 inDoubleQuotes = !inDoubleQuotes;
+                tokenStarted = true;
             } else if (c == '\'' && !inDoubleQuotes) {
                 inSingleQuotes = !inSingleQuotes;
+                tokenStarted = true;
             } else if (Character.isWhitespace(c) && !inDoubleQuotes && 
!inSingleQuotes) {
-                if (current.length() > 0) {
+                if (tokenStarted) {
                     args.add(current.toString());
                     current.setLength(0);
+                    tokenStarted = false;
                 }
             } else {
                 current.append(c);
+                tokenStarted = true;
             }
         }
 
-        if (current.length() > 0) {
+        if (tokenStarted) {
             args.add(current.toString());
         }
 
diff --git 
a/impl/maven-support/src/test/java/org/apache/maven/settings/v4/ArgumentTokenizerTest.java
 
b/impl/maven-support/src/test/java/org/apache/maven/settings/v4/ArgumentTokenizerTest.java
new file mode 100644
index 0000000000..7324a38356
--- /dev/null
+++ 
b/impl/maven-support/src/test/java/org/apache/maven/settings/v4/ArgumentTokenizerTest.java
@@ -0,0 +1,103 @@
+/*
+ * 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.maven.settings.v4;
+
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class ArgumentTokenizerTest {
+
+    @Test
+    void doubleQuotedEmptyArgument() {
+        assertEquals(List.of("first", "", "third"), 
ArgumentTokenizer.tokenize("first \"\" third"));
+    }
+
+    @Test
+    void singleQuotedEmptyArgument() {
+        assertEquals(List.of("first", "", "third"), 
ArgumentTokenizer.tokenize("first '' third"));
+    }
+
+    @Test
+    void emptyArgumentsAtBoundaries() {
+        assertEquals(List.of(""), ArgumentTokenizer.tokenize("\"\""));
+        assertEquals(List.of(""), ArgumentTokenizer.tokenize("''"));
+        assertEquals(List.of("", "middle", ""), ArgumentTokenizer.tokenize("  
\"\" middle ''  "));
+    }
+
+    @Test
+    void consecutiveEmptyArguments() {
+        assertEquals(List.of("", "", ""), 
ArgumentTokenizer.tokenize("\"\"\t''\n\"\""));
+        // Adjacent quoted fragments without whitespace belong to the same 
argument.
+        assertEquals(List.of(""), ArgumentTokenizer.tokenize("\"\"''"));
+    }
+
+    @Test
+    void adjacentQuotedFragmentsStayInOneArgument() {
+        assertEquals(List.of("first", "third"), 
ArgumentTokenizer.tokenize("fi\"\"rst ''third"));
+        assertEquals(List.of("firstthird"), 
ArgumentTokenizer.tokenize("\"first\"''third\"\""));
+    }
+
+    @Test
+    void quotedWhitespaceIsPreserved() {
+        assertEquals(List.of(" ", "\t"), ArgumentTokenizer.tokenize("\" \" 
'\t'"));
+    }
+
+    @Test
+    void escapedQuotesAreLiteralArguments() {
+        assertEquals(List.of("\"\"", "''", " "), 
ArgumentTokenizer.tokenize("\"\\\"\\\"\" \"''\" \" \""));
+    }
+
+    @Test
+    void windowsPathsKeepLiteralBackslashes() {
+        assertEquals(
+                List.of("-javaagent:D:\\a\\maven\\target\\agent.jar", 
"-Dpath=C:\\Program Files\\Maven"),
+                ArgumentTokenizer.tokenize(
+                        "-javaagent:D:\\a\\maven\\target\\agent.jar 
\"-Dpath=C:\\Program Files\\Maven\""));
+        assertEquals(
+                List.of("\\\\server\\share\\agent.jar"), 
ArgumentTokenizer.tokenize("\\\\server\\share\\agent.jar"));
+    }
+
+    @Test
+    void unquotedBackslashDoesNotEscapeWhitespace() {
+        assertEquals(List.of("hello\\", "world"), 
ArgumentTokenizer.tokenize("hello\\ world"));
+    }
+
+    @Test
+    void blankInputDoesNotCreateArguments() {
+        assertEquals(List.of(), ArgumentTokenizer.tokenize(""));
+        assertEquals(List.of(), ArgumentTokenizer.tokenize(" \t\r\n "));
+    }
+
+    @Test
+    void unclosedQuotesStillFail() {
+        assertThrows(IllegalArgumentException.class, () -> 
ArgumentTokenizer.tokenize("\"\" '"));
+        assertThrows(IllegalArgumentException.class, () -> 
ArgumentTokenizer.tokenize("'' \""));
+    }
+
+    @Test
+    void resultWithEmptyArgumentIsUnmodifiable() {
+        List<String> arguments = ArgumentTokenizer.tokenize("\"\"");
+        assertEquals(List.of(""), arguments);
+        assertThrows(UnsupportedOperationException.class, () -> 
arguments.add("extra"));
+    }
+}
diff --git 
a/impl/maven-support/src/test/java/org/apache/maven/settings/v4/SettingsStaxReaderTest.java
 
b/impl/maven-support/src/test/java/org/apache/maven/settings/v4/SettingsStaxReaderTest.java
new file mode 100644
index 0000000000..1d72a78bac
--- /dev/null
+++ 
b/impl/maven-support/src/test/java/org/apache/maven/settings/v4/SettingsStaxReaderTest.java
@@ -0,0 +1,77 @@
+/*
+ * 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.maven.settings.v4;
+
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.List;
+
+import org.apache.maven.api.settings.Settings;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class SettingsStaxReaderTest {
+
+    @Test
+    void optionsPreserveQuotedEmptyArgument() throws Exception {
+        Settings settings = parse("<options>--log-file \"\" verify</options>");
+        assertEquals(List.of("--log-file", "", "verify"), settings.getArgs());
+    }
+
+    @Test
+    void aliasPreservesQuotedEmptyArgument() throws Exception {
+        Settings settings = parse("<alias name=\"ci\">--log-file '' 
verify</alias>");
+        assertEquals(
+                List.of("--log-file", "", "verify"),
+                settings.getAliases().get(0).getArgs());
+    }
+
+    @Test
+    void inlineAndStructuredEmptyArgumentsAreEquivalent() throws Exception {
+        Settings inline =
+                parse("<options>--log-file \"\" verify</options>" + "<alias 
name=\"ci\">--log-file '' verify</alias>");
+        Settings structured = 
parse("<options><arg>--log-file</arg><arg/><arg>verify</arg></options>"
+                + "<alias 
name=\"ci\"><arg>--log-file</arg><arg/><arg>verify</arg></alias>");
+
+        assertEquals(structured.getArgs(), inline.getArgs());
+        assertEquals(
+                structured.getAliases().get(0).getArgs(),
+                inline.getAliases().get(0).getArgs());
+    }
+
+    @Test
+    void emptyArgumentsSurviveRoundTrip() throws Exception {
+        Settings original =
+                parse("<options>--log-file \"\" verify</options>" + "<alias 
name=\"ci\">--log-file '' verify</alias>");
+        StringWriter output = new StringWriter();
+        new SettingsStaxWriter().write(output, original);
+        Settings roundTripped = new SettingsStaxReader().read(new 
StringReader(output.toString()), false, null);
+
+        assertEquals(List.of("--log-file", "", "verify"), 
roundTripped.getArgs());
+        assertEquals(
+                List.of("--log-file", "", "verify"),
+                roundTripped.getAliases().get(0).getArgs());
+    }
+
+    private Settings parse(String content) throws Exception {
+        String xml = "<settings 
xmlns=\"http://maven.apache.org/SETTINGS/2.1.0\";>" + content + "</settings>";
+        return new SettingsStaxReader().read(new StringReader(xml), false, 
null);
+    }
+}

Reply via email to