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

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


The following commit(s) were added to refs/heads/master by this push:
     new 24557385 Add a ParserContext that callers pass to parsers
24557385 is described below

commit 24557385948ff153a8f1f1e43b3ac91b8846993e
Author: Sylwester Lachiewicz <[email protected]>
AuthorDate: Fri Nov 13 21:00:20 2026 +0000

    Add a ParserContext that callers pass to parsers
    
    Parsers get the document location, output name, properties and options
    as an argument instead of injecting Maven components
    (apache/maven-doxia-sitetools#736). The context is the first parameter so
    that parse(source, sink, null) calls stay unambiguous.
---
 .../java/org/apache/maven/doxia/parser/Parser.java |  21 ++
 .../apache/maven/doxia/parser/ParserContext.java   | 325 +++++++++++++++++++++
 .../maven/doxia/parser/ParserContextTest.java      | 182 ++++++++++++
 3 files changed, 528 insertions(+)

diff --git a/doxia-core/src/main/java/org/apache/maven/doxia/parser/Parser.java 
b/doxia-core/src/main/java/org/apache/maven/doxia/parser/Parser.java
index 09e47753..aa596b9c 100644
--- a/doxia-core/src/main/java/org/apache/maven/doxia/parser/Parser.java
+++ b/doxia-core/src/main/java/org/apache/maven/doxia/parser/Parser.java
@@ -65,6 +65,27 @@ public interface Parser {
      */
     void parse(Reader source, Sink sink, String reference) throws 
ParseException;
 
+    /**
+     * Parses the given source model and emits Doxia events into the given 
sink, for a caller that knows more
+     * about the document than its reference: its location, where the result 
goes, properties and parser options.
+     * <p>
+     * The default implementation only passes on the reference from the 
context. A parser that needs more
+     * overrides this method and reads the context instead of asking its 
environment, for example a
+     * dependency injection container, for that information.
+     * <p>
+     * The context is the first parameter, so that existing calls passing 
{@code null} as reference
+     * to {@link #parse(Reader, Sink, String)} stay unambiguous.
+     *
+     * @param context not null information about the document and its 
surroundings.
+     * @param source not null reader that provides the source document.
+     * @param sink A sink that consumes the Doxia events.
+     * @throws org.apache.maven.doxia.parser.ParseException if the model could 
not be parsed.
+     * @since 2.3.0
+     */
+    default void parse(ParserContext context, Reader source, Sink sink) throws 
ParseException {
+        parse(source, sink, context.getReference());
+    }
+
     /**
      * The parser type value could be {@link #UNKNOWN_TYPE}, {@link #TXT_TYPE} 
or
      * {@link #XML_TYPE}.
diff --git 
a/doxia-core/src/main/java/org/apache/maven/doxia/parser/ParserContext.java 
b/doxia-core/src/main/java/org/apache/maven/doxia/parser/ParserContext.java
new file mode 100644
index 00000000..0897db8e
--- /dev/null
+++ b/doxia-core/src/main/java/org/apache/maven/doxia/parser/ParserContext.java
@@ -0,0 +1,325 @@
+/*
+ * 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.doxia.parser;
+
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+
+/**
+ * What the caller of a {@link Parser} knows about the document being parsed 
and its surroundings:
+ * where the source comes from, where the result goes, and the properties and 
options that apply.
+ * <p>
+ * A context is immutable and belongs to one call of {@link 
Parser#parse(ParserContext, java.io.Reader,
+ * org.apache.maven.doxia.sink.Sink)}. Parsers are usually shared between 
documents and threads,
+ * so a parser must not keep a context beyond that call.
+ * <p>
+ * Everything except the encodings and the locale is optional, because not 
every caller renders files of a site.
+ *
+ * @since 2.3.0
+ */
+public final class ParserContext {
+
+    private final String reference;
+
+    private final Path sourceFile;
+
+    private final Path sourceDirectory;
+
+    private final Path rootDirectory;
+
+    private final String outputName;
+
+    private final Path outputDirectory;
+
+    private final Locale locale;
+
+    private final Charset inputEncoding;
+
+    private final Charset outputEncoding;
+
+    private final Map<String, String> properties;
+
+    private final Map<String, String> options;
+
+    private ParserContext(Builder builder) {
+        this.reference = builder.reference;
+        this.sourceFile = builder.sourceFile;
+        this.sourceDirectory = builder.sourceDirectory;
+        this.rootDirectory = builder.rootDirectory;
+        this.outputName = builder.outputName;
+        this.outputDirectory = builder.outputDirectory;
+        this.locale = builder.locale;
+        this.inputEncoding = builder.inputEncoding;
+        this.outputEncoding = builder.outputEncoding;
+        this.properties = Collections.unmodifiableMap(new 
LinkedHashMap<>(builder.properties));
+        this.options = Collections.unmodifiableMap(new 
LinkedHashMap<>(builder.options));
+    }
+
+    /**
+     * @return a builder for a context without any information, UTF-8 
encodings and the root locale
+     */
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    /**
+     * @return a builder that starts with the content of this context, for a 
parser that hands a modified
+     * context to another parser
+     */
+    public Builder toBuilder() {
+        Builder builder = new Builder();
+        builder.reference = reference;
+        builder.sourceFile = sourceFile;
+        builder.sourceDirectory = sourceDirectory;
+        builder.rootDirectory = rootDirectory;
+        builder.outputName = outputName;
+        builder.outputDirectory = outputDirectory;
+        builder.locale = locale;
+        builder.inputEncoding = inputEncoding;
+        builder.outputEncoding = outputEncoding;
+        builder.properties = properties;
+        builder.options = options;
+        return builder;
+    }
+
+    /**
+     * @return the string identifying the source, as passed to
+     * {@link Parser#parse(java.io.Reader, org.apache.maven.doxia.sink.Sink, 
String)}, may be {@code null}
+     */
+    public String getReference() {
+        return reference;
+    }
+
+    /**
+     * @return the absolute path of the document being parsed, empty if the 
source is not a file
+     */
+    public Optional<Path> getSourceFile() {
+        return Optional.ofNullable(sourceFile);
+    }
+
+    /**
+     * @return the directory the document's path is relative to, for a Maven 
site the directory of the
+     * document's format, such as {@code src/site/markdown}
+     */
+    public Optional<Path> getSourceDirectory() {
+        return Optional.ofNullable(sourceDirectory);
+    }
+
+    /**
+     * @return the root directory of what is being rendered, for a Maven site 
the project base directory
+     */
+    public Optional<Path> getRootDirectory() {
+        return Optional.ofNullable(rootDirectory);
+    }
+
+    /**
+     * @return the name of the rendered document relative to the output root, 
with {@code /} as separator,
+     * for example {@code guide/index.html}
+     */
+    public Optional<String> getOutputName() {
+        return Optional.ofNullable(outputName);
+    }
+
+    /**
+     * @return the directory {@link #getOutputName()} is relative to, empty if 
the result is not written to a file
+     */
+    public Optional<Path> getOutputDirectory() {
+        return Optional.ofNullable(outputDirectory);
+    }
+
+    /**
+     * @return the locale the document is rendered for, {@link Locale#ROOT} if 
unknown
+     */
+    public Locale getLocale() {
+        return locale;
+    }
+
+    /**
+     * @return the encoding of the source, UTF-8 by default
+     */
+    public Charset getInputEncoding() {
+        return inputEncoding;
+    }
+
+    /**
+     * @return the encoding of the rendered document, UTF-8 by default
+     */
+    public Charset getOutputEncoding() {
+        return outputEncoding;
+    }
+
+    /**
+     * @return the properties of what is being rendered, for a Maven site the 
project properties; unmodifiable
+     */
+    public Map<String, String> getProperties() {
+        return properties;
+    }
+
+    /**
+     * @return the options the caller has for the parser that receives this 
context; unmodifiable
+     */
+    public Map<String, String> getOptions() {
+        return options;
+    }
+
+    /**
+     * Builds a {@link ParserContext}.
+     *
+     * @since 2.3.0
+     */
+    public static final class Builder {
+
+        private String reference;
+
+        private Path sourceFile;
+
+        private Path sourceDirectory;
+
+        private Path rootDirectory;
+
+        private String outputName;
+
+        private Path outputDirectory;
+
+        private Locale locale = Locale.ROOT;
+
+        private Charset inputEncoding = StandardCharsets.UTF_8;
+
+        private Charset outputEncoding = StandardCharsets.UTF_8;
+
+        private Map<String, String> properties = Collections.emptyMap();
+
+        private Map<String, String> options = Collections.emptyMap();
+
+        private Builder() {}
+
+        /**
+         * @param reference the string identifying the source, may be {@code 
null}
+         * @return this builder
+         */
+        public Builder reference(String reference) {
+            this.reference = reference;
+            return this;
+        }
+
+        /**
+         * @param sourceFile the absolute path of the document, may be {@code 
null}
+         * @return this builder
+         */
+        public Builder sourceFile(Path sourceFile) {
+            this.sourceFile = sourceFile;
+            return this;
+        }
+
+        /**
+         * @param sourceDirectory the directory the document's path is 
relative to, may be {@code null}
+         * @return this builder
+         */
+        public Builder sourceDirectory(Path sourceDirectory) {
+            this.sourceDirectory = sourceDirectory;
+            return this;
+        }
+
+        /**
+         * @param rootDirectory the root directory of what is being rendered, 
may be {@code null}
+         * @return this builder
+         */
+        public Builder rootDirectory(Path rootDirectory) {
+            this.rootDirectory = rootDirectory;
+            return this;
+        }
+
+        /**
+         * @param outputName the name of the rendered document relative to the 
output root, may be {@code null}
+         * @return this builder
+         */
+        public Builder outputName(String outputName) {
+            this.outputName = outputName;
+            return this;
+        }
+
+        /**
+         * @param outputDirectory the directory the output name is relative 
to, may be {@code null}
+         * @return this builder
+         */
+        public Builder outputDirectory(Path outputDirectory) {
+            this.outputDirectory = outputDirectory;
+            return this;
+        }
+
+        /**
+         * @param locale the locale the document is rendered for, not {@code 
null}
+         * @return this builder
+         */
+        public Builder locale(Locale locale) {
+            this.locale = Objects.requireNonNull(locale, "locale");
+            return this;
+        }
+
+        /**
+         * @param inputEncoding the encoding of the source, not {@code null}
+         * @return this builder
+         */
+        public Builder inputEncoding(Charset inputEncoding) {
+            this.inputEncoding = Objects.requireNonNull(inputEncoding, 
"inputEncoding");
+            return this;
+        }
+
+        /**
+         * @param outputEncoding the encoding of the rendered document, not 
{@code null}
+         * @return this builder
+         */
+        public Builder outputEncoding(Charset outputEncoding) {
+            this.outputEncoding = Objects.requireNonNull(outputEncoding, 
"outputEncoding");
+            return this;
+        }
+
+        /**
+         * @param properties the properties of what is being rendered, copied 
when the context is built, not {@code null}
+         * @return this builder
+         */
+        public Builder properties(Map<String, String> properties) {
+            this.properties = Objects.requireNonNull(properties, "properties");
+            return this;
+        }
+
+        /**
+         * @param options the options for the parser, copied when the context 
is built, not {@code null}
+         * @return this builder
+         */
+        public Builder options(Map<String, String> options) {
+            this.options = Objects.requireNonNull(options, "options");
+            return this;
+        }
+
+        /**
+         * @return a new context with the content of this builder
+         */
+        public ParserContext build() {
+            return new ParserContext(this);
+        }
+    }
+}
diff --git 
a/doxia-core/src/test/java/org/apache/maven/doxia/parser/ParserContextTest.java 
b/doxia-core/src/test/java/org/apache/maven/doxia/parser/ParserContextTest.java
new file mode 100644
index 00000000..42c7db25
--- /dev/null
+++ 
b/doxia-core/src/test/java/org/apache/maven/doxia/parser/ParserContextTest.java
@@ -0,0 +1,182 @@
+/*
+ * 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.doxia.parser;
+
+import java.io.Reader;
+import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.maven.doxia.sink.Sink;
+import org.apache.maven.doxia.sink.impl.SinkEventTestingSink;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class ParserContextTest {
+
+    @Test
+    void emptyContextHasDefaults() {
+        ParserContext context = ParserContext.builder().build();
+
+        assertNull(context.getReference());
+        assertFalse(context.getSourceFile().isPresent());
+        assertFalse(context.getSourceDirectory().isPresent());
+        assertFalse(context.getRootDirectory().isPresent());
+        assertFalse(context.getOutputName().isPresent());
+        assertFalse(context.getOutputDirectory().isPresent());
+        assertEquals(Locale.ROOT, context.getLocale());
+        assertEquals(StandardCharsets.UTF_8, context.getInputEncoding());
+        assertEquals(StandardCharsets.UTF_8, context.getOutputEncoding());
+        assertTrue(context.getProperties().isEmpty());
+        assertTrue(context.getOptions().isEmpty());
+    }
+
+    @Test
+    void contextKeepsWhatTheBuilderWasGiven() {
+        Path root = Paths.get("project").toAbsolutePath();
+        Path sourceDirectory = root.resolve("src/site/markdown");
+        Path sourceFile = sourceDirectory.resolve("guide/index.md");
+        Path outputDirectory = root.resolve("target/site");
+
+        ParserContext context = ParserContext.builder()
+                .reference("guide/index.md")
+                .sourceFile(sourceFile)
+                .sourceDirectory(sourceDirectory)
+                .rootDirectory(root)
+                .outputName("guide/index.html")
+                .outputDirectory(outputDirectory)
+                .locale(Locale.FRENCH)
+                .inputEncoding(StandardCharsets.ISO_8859_1)
+                .outputEncoding(StandardCharsets.US_ASCII)
+                .build();
+
+        assertEquals("guide/index.md", context.getReference());
+        assertEquals(sourceFile, context.getSourceFile().get());
+        assertEquals(sourceDirectory, context.getSourceDirectory().get());
+        assertEquals(root, context.getRootDirectory().get());
+        assertEquals("guide/index.html", context.getOutputName().get());
+        assertEquals(outputDirectory, context.getOutputDirectory().get());
+        assertEquals(Locale.FRENCH, context.getLocale());
+        assertEquals(StandardCharsets.ISO_8859_1, context.getInputEncoding());
+        assertEquals(StandardCharsets.US_ASCII, context.getOutputEncoding());
+    }
+
+    @Test
+    void mapsAreCopiedAndUnmodifiable() {
+        Map<String, String> properties = new HashMap<>();
+        properties.put("project.version", "1.0");
+        Map<String, String> options = new HashMap<>();
+        options.put("attributes.toc", "left");
+
+        ParserContext context =
+                
ParserContext.builder().properties(properties).options(options).build();
+        properties.put("later", "ignored");
+        options.clear();
+
+        assertEquals(1, context.getProperties().size());
+        assertEquals("1.0", context.getProperties().get("project.version"));
+        assertEquals("left", context.getOptions().get("attributes.toc"));
+        assertThrows(
+                UnsupportedOperationException.class,
+                () -> context.getProperties().put("a", "b"));
+        assertThrows(
+                UnsupportedOperationException.class, () -> 
context.getOptions().put("a", "b"));
+    }
+
+    @Test
+    void builderRejectsNullWhereTheContextGuaranteesAValue() {
+        ParserContext.Builder builder = ParserContext.builder();
+
+        assertThrows(NullPointerException.class, () -> builder.locale(null));
+        assertThrows(NullPointerException.class, () -> 
builder.inputEncoding(null));
+        assertThrows(NullPointerException.class, () -> 
builder.outputEncoding(null));
+        assertThrows(NullPointerException.class, () -> 
builder.properties(null));
+        assertThrows(NullPointerException.class, () -> builder.options(null));
+    }
+
+    @Test
+    void toBuilderCopiesTheContext() {
+        Map<String, String> options = new HashMap<>();
+        options.put("attributes.toc", "left");
+        ParserContext context = ParserContext.builder()
+                .reference("guide/index.md")
+                .outputName("guide/index.html")
+                .locale(Locale.FRENCH)
+                .options(options)
+                .build();
+
+        ParserContext copy = 
context.toBuilder().reference("guide/index.md.vm").build();
+
+        assertEquals("guide/index.md.vm", copy.getReference());
+        assertEquals("guide/index.html", copy.getOutputName().get());
+        assertEquals(Locale.FRENCH, copy.getLocale());
+        assertEquals(options, copy.getOptions());
+        assertEquals("guide/index.md", context.getReference());
+    }
+
+    @Test
+    void parserWithoutContextSupportReceivesTheReference() throws 
ParseException {
+        AtomicReference<String> seen = new AtomicReference<>();
+        Parser parser = new AbstractTextParser() {
+            @Override
+            public void parse(Reader source, Sink sink, String reference) {
+                seen.set(reference);
+            }
+        };
+
+        parser.parse(
+                ParserContext.builder().reference("index.md").build(),
+                new StringReader(""),
+                new SinkEventTestingSink());
+
+        assertEquals("index.md", seen.get());
+    }
+
+    @Test
+    void parserWithContextSupportReceivesTheContext() throws ParseException {
+        AtomicReference<ParserContext> seen = new AtomicReference<>();
+        Parser parser = new AbstractTextParser() {
+            @Override
+            public void parse(Reader source, Sink sink, String reference) {
+                throw new IllegalStateException("the context-aware method must 
be called");
+            }
+
+            @Override
+            public void parse(ParserContext context, Reader source, Sink sink) 
{
+                seen.set(context);
+            }
+        };
+        ParserContext context = 
ParserContext.builder().reference("index.md").build();
+
+        parser.parse(context, new StringReader(""), new 
SinkEventTestingSink());
+
+        assertSame(context, seen.get());
+    }
+}

Reply via email to