You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@logging.apache.org by GitBox <gi...@apache.org> on 2022/11/23 23:15:29 UTC

[GitHub] [logging-log4j2] ppkarwasz commented on a diff in pull request #1145: LOG4J2-3628 Replace maven-changes-plugin with a custom changelog implementation.

ppkarwasz commented on code in PR #1145:
URL: https://github.com/apache/logging-log4j2/pull/1145#discussion_r1030925236


##########
log4j-internal-util/src/main/java/org/apache/logging/log4j/internal/util/XmlReader.java:
##########
@@ -0,0 +1,120 @@
+/*
+ * 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.logging.log4j.internal.util;
+
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * A SAX2-based XML reader.
+ */
+public final class XmlReader {
+
+    private XmlReader() {}
+
+    public static Element readXmlFileRootElement(final Path path, final String rootElementName) {
+        try (final InputStream inputStream = new FileInputStream(path.toFile())) {
+            final Document document = readXml(inputStream);
+            final Element rootElement = document.getDocumentElement();
+            if (!rootElementName.equals(rootElement.getNodeName())) {
+                final String message = String.format(
+                        "was expecting root element to be called `%s`, found: `%s`",
+                        rootElementName, rootElement.getNodeName());
+                throw new IllegalArgumentException(message);
+            }
+            return rootElement;
+        } catch (final Exception error) {
+            final String message = String.format(
+                    "XML read failure for file `%s` and root element `%s`", path, rootElementName);
+            throw new RuntimeException(message, error);
+        }
+    }
+
+    private static Document readXml(final InputStream inputStream) throws Exception {
+        final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
+        final SAXParser parser = parserFactory.newSAXParser();
+        final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+        final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
+        final Document document = documentBuilder.newDocument();

Review Comment:
   I know that this is for internal usage only, but it doesn't hurt to disable DTDs entirely: https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html



##########
log4j-internal-util/pom.xml:
##########
@@ -0,0 +1,164 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <parent>
+    <artifactId>log4j</artifactId>
+    <groupId>org.apache.logging.log4j</groupId>
+    <version>2.19.1-SNAPSHOT</version>
+  </parent>
+
+  <modelVersion>4.0.0</modelVersion>
+
+  <artifactId>log4j-internal-util</artifactId>
+  <name>Apache Log4j internal utilities</name>
+  <description>Internal Log4j utilities for project's build infrastructure.</description>
+
+  <properties>
+    <log4jParentDir>${basedir}/..</log4jParentDir>  <!-- required for `spotless-maven-plugin` inherited configuration -->
+    <maven.doap.skip>true</maven.doap.skip>
+  </properties>
+
+  <build>
+    <finalName>log4j-internal-util</finalName>
+    <plugins>
+
+      <!-- Disable ITs: -->
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-failsafe-plugin</artifactId>
+        <executions>
+          <execution>
+            <goals>
+              <goal>integration-test</goal>
+              <goal>verify</goal>
+            </goals>
+          </execution>
+        </executions>

Review Comment:
   If the tests are disabled, this is not needed.



##########
log4j-internal-util/src/main/java/org/apache/logging/log4j/internal/util/changelog/exporter/AsciiDocExporter.java:
##########
@@ -0,0 +1,424 @@
+/*
+ * 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.logging.log4j.internal.util.changelog.exporter;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.FileTime;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.apache.logging.log4j.internal.util.AsciiDocUtils;
+import org.apache.logging.log4j.internal.util.changelog.ChangelogEntry;
+import org.apache.logging.log4j.internal.util.changelog.ChangelogFiles;
+import org.apache.logging.log4j.internal.util.changelog.ChangelogRelease;
+
+public final class AsciiDocExporter {
+
+    private static final String TARGET_RELATIVE_DIRECTORY = "src/site/asciidoc/changelog";
+
+    private static final Comparator<Path> FILE_MODIFICATION_TIME_COMPARATOR = Comparator.comparing(path -> {
+        try {
+            final FileTime fileTime = Files.getLastModifiedTime(path);
+            return fileTime.toMillis();
+        } catch (final IOException error) {
+            final String message = String.format("failed reading the last-modified time: `%s`", path);
+            throw new UncheckedIOException(message, error);
+        }
+    });
+
+    private static final String AUTO_GENERATION_WARNING_ASCIIDOC = "////\n" +
+            "*DO NOT EDIT THIS FILE!!*\n" +
+            "This file is automatically generated from the release changelog directory!\n" +
+            "////\n";
+
+    private AsciiDocExporter() {}
+
+    public static void main(final String[] mainArgs) {
+
+        // Read arguments.
+        final AsciiDocExporterArgs args = AsciiDocExporterArgs.fromMainArgs(mainArgs);
+
+        // Find release directories.
+        final Path changelogDirectory = ChangelogFiles.changelogDirectory(args.projectRootDirectory);
+        final List<Path> releaseDirectories = findAdjacentFiles(changelogDirectory)
+                .filter(file -> file.toFile().isDirectory())
+                .sorted()
+                .collect(Collectors.toList());
+        final int releaseDirectoryCount = releaseDirectories.size();
+
+        // Read the release information files.
+        final List<ChangelogRelease> changelogReleases = releaseDirectories
+                .stream()
+                .map(releaseDirectory -> {
+                    final Path releaseXmlFile = ChangelogFiles.releaseXmlFile(releaseDirectory);
+                    return ChangelogRelease.readFromXmlFile(releaseXmlFile);
+                })
+                .collect(Collectors.toList());
+
+        // Export releases.
+        if (releaseDirectoryCount > 0) {
+
+            // Export each release directory.
+            for (int releaseIndex = 0; releaseIndex < releaseDirectories.size(); releaseIndex++) {
+                final Path releaseDirectory = releaseDirectories.get(releaseIndex);
+                final ChangelogRelease changelogRelease = changelogReleases.get(releaseIndex);
+                try {
+                    exportRelease(args.projectRootDirectory, releaseDirectory, changelogRelease);
+                } catch (final Exception error) {
+                    final String message =
+                            String.format("failed exporting release from directory `%s`", releaseDirectory);
+                    throw new RuntimeException(message, error);
+                }
+            }
+
+            // Report the operation.
+            if (releaseDirectoryCount == 1) {
+                System.out.format("exported a single release directory: `%s`%n", releaseDirectories.get(0));
+            } else {
+                System.out.format(
+                        "exported %d release directories: ..., `%s`%n",
+                        releaseDirectories.size(),
+                        releaseDirectories.get(releaseDirectoryCount - 1));
+            }
+
+        }
+
+        // Export unreleased.
+        exportUnreleased(args.projectRootDirectory);
+
+        // Export the release index.
+        exportReleaseIndex(args.projectRootDirectory, changelogReleases);
+
+    }
+
+    /**
+     * Finds files non-recursively in the given directory.
+     * <p>
+     * Given directory itself and hidden files are filtered out.
+     * </p>
+     */
+    @SuppressWarnings("RedundantIfStatement")
+    private static Stream<Path> findAdjacentFiles(final Path directory) {
+        try {
+            return Files
+                    .walk(directory, 1)
+                    .filter(path -> {
+
+                        // Skip the directory itself.
+                        if (path.equals(directory)) {
+                            return false;
+                        }
+
+                        // Skip hidden files.
+                        boolean hiddenFile = path.getFileName().toString().startsWith(".");
+                        if (hiddenFile) {
+                            return false;
+                        }
+
+                        // Accept the rest.
+                        return true;
+
+                    });
+        } catch (final IOException error) {
+            final String message = String.format("failed walking directory: `%s`", directory);
+            throw new UncheckedIOException(message, error);
+        }
+    }
+
+    private static void exportRelease(
+            final Path projectRootDirectory,
+            final Path releaseDirectory,
+            final ChangelogRelease changelogRelease) {
+        final String introAsciiDoc = readIntroAsciiDoc(releaseDirectory);
+        final List<ChangelogEntry> changelogEntries = readChangelogEntries(releaseDirectory);
+        try {
+            exportRelease(projectRootDirectory, changelogRelease, introAsciiDoc, changelogEntries);
+        } catch (final IOException error) {
+            final String message = String.format("failed exporting release from directory `%s`", releaseDirectory);
+            throw new UncheckedIOException(message, error);
+        }
+    }
+
+    private static String readIntroAsciiDoc(final Path releaseDirectory) {
+
+        // Determine the file to be read.
+        final Path introAsciiDocFile = ChangelogFiles.introAsciiDocFile(releaseDirectory);
+        if (!Files.exists(introAsciiDocFile)) {
+            return "";
+        }
+
+        // Read the file.
+        final List<String> introAsciiDocLines;
+        try {
+            introAsciiDocLines = Files.readAllLines(introAsciiDocFile, StandardCharsets.UTF_8);
+        } catch (final IOException error) {
+            final String message = String.format("failed reading intro AsciiDoc file: `%s`", introAsciiDocFile);
+            throw new UncheckedIOException(message, error);
+        }
+
+        // Erase comment blocks.
+        final boolean[] inCommentBlock = {false};
+        return introAsciiDocLines
+                .stream()
+                .filter(line -> {
+                    final boolean commentBlock = "////".equals(line);
+                    if (commentBlock) {
+                        inCommentBlock[0] = !inCommentBlock[0];
+                        return false;
+                    }
+                    return !inCommentBlock[0];
+                })
+                .collect(Collectors.joining("\n"))
+                + "\n";
+
+    }
+
+    private static List<ChangelogEntry> readChangelogEntries(final Path releaseDirectory) {
+        return findAdjacentFiles(releaseDirectory)
+                .sorted(FILE_MODIFICATION_TIME_COMPARATOR)

Review Comment:
   Are we sure that `git clone` sets the correct modification time?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscribe@logging.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org