AdocManifest.java

/*
 * Copyright © 2026 IKE Network (support@ike.network)
 *
 * Licensed 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 network.ike.plugin.adoc;

import org.apache.maven.api.plugin.MojoException;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * A library's manifest: its coordinates and the packages it ships, generated by the build
 * from the pom and the tree and shipped at {@code META-INF/ike/<group>/<artifact>/manifest.yaml}
 * (IKE-Network/ike-issues#1341). The union goal reads it to know what a zip puts in the
 * union and to refuse two libraries that ship one package.
 *
 * <pre>{@code
 * coordinates: network.ike.lab:unlv-topics
 * packages:
 *   - name: network.ike.lab/aip
 *     kind: topics
 *   - name: network.ike.lab/unlv
 *     kind: library
 * registry: META-INF/ike/network.ike.lab/unlv-topics/topic-registry.yaml
 * }</pre>
 *
 * <p>A module of the same reactor has no zip at generate-sources, so its manifest is derived
 * from its source tree with {@link #fromSourceTree}: every directory under the root whose
 * name has a dot is a group, a group directory that holds files directly is one package,
 * and otherwise each directory under it is one. The manifest the doc plugin generates is the
 * one a zip ships; the derived one is for linking the member into the union.
 *
 * @param groupId    the owning group, from {@code coordinates}
 * @param artifactId the artifact, from {@code coordinates}
 * @param packages   the packages shipped, in manifest order
 * @param registry   the registry path relative to the root, or null when the manifest
 *                   names none
 */
public record AdocManifest(String groupId, String artifactId, List<AdocPackage> packages,
                           String registry) {

    /** The manifest's file name inside the library's {@code META-INF} area. */
    public static final String FILE_NAME = "manifest.yaml";

    /**
     * Checks the parts and copies the package list.
     *
     * @param groupId    the group
     * @param artifactId the artifact
     * @param packages   the packages
     * @param registry   the registry path, or null
     */
    public AdocManifest {
        Objects.requireNonNull(groupId, "groupId");
        Objects.requireNonNull(artifactId, "artifactId");
        packages = List.copyOf(packages);
    }

    /**
     * The group and artifact as the manifest writes them, {@code group:artifact}.
     *
     * @return the coordinates without a version
     */
    public String ga() {
        return groupId + ":" + artifactId;
    }

    /**
     * Parses a manifest.
     *
     * @param yaml   the manifest text
     * @param source what the text came from, for the message of a refusal
     * @return the manifest
     * @throws MojoException if the text has no coordinates or no package list
     */
    public static AdocManifest parse(String yaml, String source) {
        Object loaded = new Yaml().load(yaml);
        if (!(loaded instanceof Map<?, ?> map)) {
            throw new MojoException("Not a manifest: " + source);
        }
        Object coordinates = map.get("coordinates");
        if (!(coordinates instanceof String ga) || ga.indexOf(':') < 0) {
            throw new MojoException("The manifest " + source
                    + " has no coordinates: expected 'coordinates: <group>:<artifact>'");
        }
        String[] parts = ga.split(":", 2);
        List<AdocPackage> packages = new ArrayList<>();
        if (map.get("packages") instanceof List<?> list) {
            for (Object item : list) {
                if (item instanceof Map<?, ?> entry && entry.get("name") instanceof String name) {
                    Object kind = entry.get("kind");
                    packages.add(new AdocPackage(stripSlashes(name),
                            kind instanceof String k ? k : AdocPackage.KIND_TOPICS));
                } else if (item instanceof String name) {
                    packages.add(new AdocPackage(stripSlashes(name), AdocPackage.KIND_TOPICS));
                } else {
                    throw new MojoException("The manifest " + source
                            + " has a package entry without a name: " + item);
                }
            }
        } else {
            throw new MojoException("The manifest " + source + " lists no packages");
        }
        Object registry = map.get("registry");
        return new AdocManifest(parts[0].trim(), parts[1].trim(), packages,
                registry instanceof String r ? r : null);
    }

    /**
     * Reads a library's manifest from its zip, at the entry its coordinates name.
     *
     * @param zip         the library's {@code adoc} zip
     * @param coordinates the library's coordinates
     * @return the manifest, or empty when the zip ships none, which marks a legacy library
     * @throws MojoException if the zip cannot be read or the manifest cannot be parsed
     */
    public static Optional<AdocManifest> readFromZip(Path zip, AdocCoordinates coordinates) {
        try (ZipFile file = new ZipFile(zip.toFile())) {
            ZipEntry entry = file.getEntry(coordinates.manifestPath());
            if (entry == null) {
                return Optional.empty();
            }
            try (InputStream in = file.getInputStream(entry)) {
                return Optional.of(parse(new String(in.readAllBytes(), StandardCharsets.UTF_8),
                        zip + "!/" + coordinates.manifestPath()));
            }
        } catch (IOException e) {
            throw new MojoException("Cannot read " + zip + ": " + e.getMessage(), e);
        }
    }

    /**
     * Reads a manifest file from a directory tree, such as the union.
     *
     * @param file the manifest file
     * @return the manifest
     * @throws MojoException if the file cannot be read or parsed
     */
    public static AdocManifest read(Path file) {
        try {
            return parse(Files.readString(file, StandardCharsets.UTF_8), file.toString());
        } catch (IOException e) {
            throw new MojoException("Cannot read " + file + ": " + e.getMessage(), e);
        }
    }

    /**
     * Derives the manifest of a reactor member from its source tree. A directory under the
     * root is a group when its name has a dot and does not start with one. A group
     * directory that holds a file directly is one package, as {@code network.ike.kompendium.anf}
     * is; otherwise each directory under it is a package. A package is of kind
     * {@value AdocPackage#KIND_TOPICS} when any {@code .adoc} file in it declares a
     * {@code :topic-id:}, else {@value AdocPackage#KIND_LIBRARY}. A root without any group
     * directory, the legacy {@code topics/} layout among them, yields no packages.
     *
     * @param coordinates the member's coordinates
     * @param root        the member's AsciiDoc source root
     * @return the derived manifest, with no registry path
     * @throws MojoException if the tree cannot be read
     */
    public static AdocManifest fromSourceTree(AdocCoordinates coordinates, Path root) {
        List<AdocPackage> packages = new ArrayList<>();
        if (Files.isDirectory(root)) {
            for (Path group : children(root)) {
                String name = group.getFileName().toString();
                if (!Files.isDirectory(group) || name.startsWith(".") || name.indexOf('.') < 0) {
                    continue;
                }
                if (children(group).stream().anyMatch(Files::isRegularFile)) {
                    packages.add(new AdocPackage(name, kindOf(group)));
                    continue;
                }
                for (Path domain : children(group)) {
                    if (Files.isDirectory(domain) && !domain.getFileName().toString().startsWith(".")) {
                        packages.add(new AdocPackage(name + "/" + domain.getFileName(), kindOf(domain)));
                    }
                }
            }
        }
        return new AdocManifest(coordinates.groupId(), coordinates.artifactId(), packages, null);
    }

    /**
     * The package this manifest ships that holds a path, the longest one when a group
     * package and a domain package both match.
     *
     * @param path a path relative to the root, with forward slashes
     * @return the owning package, or empty when none ships it
     */
    public Optional<AdocPackage> packageOwning(String path) {
        return packages.stream().filter(p -> p.contains(path))
                .max(Comparator.comparingInt(p -> p.name().length()));
    }

    /**
     * Writes the manifest as YAML, deterministically, so an unchanged manifest rewrites to
     * the same bytes.
     *
     * @return the YAML text
     */
    public String toYaml() {
        StringBuilder out = new StringBuilder();
        out.append("coordinates: ").append(ga()).append('\n');
        out.append("packages:\n");
        for (AdocPackage p : packages) {
            out.append("  - name: ").append(p.name()).append('\n');
            out.append("    kind: ").append(p.kind()).append('\n');
        }
        if (registry != null) {
            out.append("registry: ").append(registry).append('\n');
        }
        return out.toString();
    }

    private static String stripSlashes(String name) {
        String s = name.trim();
        while (s.startsWith("/")) {
            s = s.substring(1);
        }
        while (s.endsWith("/")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }

    private static List<Path> children(Path dir) {
        List<Path> result = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            stream.forEach(result::add);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
        result.sort(Comparator.comparing(p -> p.getFileName().toString()));
        return result;
    }

    private static String kindOf(Path packageDir) {
        try (Stream<Path> files = Files.walk(packageDir)) {
            boolean topics = files.filter(f -> f.toString().endsWith(".adoc") && Files.isRegularFile(f))
                    .anyMatch(AdocManifest::declaresTopicId);
            return topics ? AdocPackage.KIND_TOPICS : AdocPackage.KIND_LIBRARY;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private static boolean declaresTopicId(Path adoc) {
        try (Stream<String> lines = Files.lines(adoc, StandardCharsets.UTF_8)) {
            return lines.anyMatch(line -> line.startsWith(":topic-id:"));
        } catch (IOException | UncheckedIOException e) {
            return false;
        }
    }
}