this repo has no description
at main 118 lines 2.3 kB view raw
1package dev.kdl; 2 3import jakarta.annotation.Nonnull; 4 5import java.util.ArrayList; 6import java.util.Collections; 7import java.util.List; 8 9/** 10 * A KDL document. 11 * 12 * @param nodes the nodes in the document 13 */ 14public record KdlDocument(@Nonnull List<KdlNode> nodes) { 15 /** 16 * Creates a new document with the provided nodes. 17 * 18 * @param nodes the nodes in the document 19 */ 20 public KdlDocument(@Nonnull List<KdlNode> nodes) { 21 this.nodes = Collections.unmodifiableList(nodes); 22 } 23 24 /** 25 * Creates a new builder to create a new document from the current one. 26 * 27 * @return a new builder with the nodes of this document 28 */ 29 @Nonnull 30 public Builder mutate() { 31 return new Builder(nodes); 32 } 33 34 /** 35 * @return a new document builder 36 */ 37 @Nonnull 38 public static Builder builder() { 39 return new Builder(); 40 } 41 42 /** 43 * A {@link KdlDocument} builder. 44 */ 45 public static final class Builder { 46 47 private Builder() { 48 this.nodes = new ArrayList<>(); 49 } 50 51 private Builder(List<KdlNode> nodes) { 52 this.nodes = new ArrayList<>(nodes); 53 } 54 55 /** 56 * Adds a node to the document being built. 57 * 58 * @param node a node to add 59 * @return this builder 60 */ 61 @Nonnull 62 public Builder node(@Nonnull KdlNode node) { 63 nodes.add(node); 64 return this; 65 } 66 67 /** 68 * Adds a node to the document being built using a node builder. 69 * 70 * @param node a node builder to add 71 * @return this builder 72 */ 73 @Nonnull 74 public Builder node(@Nonnull KdlNode.Builder node) { 75 nodes.add(node.build()); 76 return this; 77 } 78 79 /** 80 * Adds nodes to the document being built. 81 * 82 * @param nodes nodes to add 83 * @return this builder 84 */ 85 @Nonnull 86 public Builder nodes(@Nonnull KdlNode... nodes) { 87 Collections.addAll(this.nodes, nodes); 88 return this; 89 } 90 91 /** 92 * Adds nodes to the document being built using node builders. 93 * 94 * @param nodes node builders to add 95 * @return this builder 96 */ 97 @Nonnull 98 public Builder nodes(@Nonnull KdlNode.Builder... nodes) { 99 for (var node : nodes) { 100 this.nodes.add(node.build()); 101 } 102 return this; 103 } 104 105 /** 106 * Creates a new document. 107 * 108 * @return a new KDL document 109 */ 110 @Nonnull 111 public KdlDocument build() { 112 return new KdlDocument(nodes); 113 } 114 115 @Nonnull 116 private final List<KdlNode> nodes; 117 } 118}