aboutsummaryrefslogtreecommitdiffstats
path: root/node-admin/src/main/java/com/yahoo/vespa/hosted/node/admin/task/util/template/SectionList.java
blob: 066f6476bcb2359650c868bb77f36e4fba8152df (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.template;

import com.yahoo.vespa.hosted.node.admin.task.util.text.Cursor;
import com.yahoo.vespa.hosted.node.admin.task.util.text.CursorRange;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * A mutable list of sections at the same level that can be used to build a template, e.g. the if-body.
 *
 * @author hakonhall
 */
class SectionList {
    private final Cursor start;
    private final Cursor end;
    private final TemplateBuilder templateBuilder;

    private final List<Section> sections = new ArrayList<>();

    SectionList(Cursor start, TemplateBuilder templateBuilder) {
        this.start = new Cursor(start);
        this.end = new Cursor(start);
        this.templateBuilder = templateBuilder;
    }

    CursorRange range() { return new CursorRange(start, end); }
    TemplateBuilder templateBuilder() { return templateBuilder; }
    List<Section> sections() { return List.copyOf(sections); }

    void appendLiteralSection(Cursor end) {
        CursorRange range = verifyAndUpdateEnd(end);
        var section = new LiteralSection(range);
        templateBuilder.addLiteralSection(section);
        sections.add(section);
    }

    VariableSection appendVariableSection(String name, Cursor nameOffset, Cursor end) {
        CursorRange range = verifyAndUpdateEnd(end);
        var section = new VariableSection(range, name, nameOffset);
        templateBuilder.addVariableSection(section);
        sections.add(section);
        return section;
    }

    void appendIfSection(boolean negated, String name, Cursor nameOffset, Cursor end,
                         SectionList ifSections, Optional<SectionList> elseSections) {
        CursorRange range = verifyAndUpdateEnd(end);
        var section = new IfSection(range, negated, name, nameOffset, ifSections, elseSections);
        templateBuilder.addIfSection(section);
        sections.add(section);
    }

    ListSection appendListSection(String name, Cursor nameOffset, Cursor end, Template body) {
        CursorRange range = verifyAndUpdateEnd(end);
        var section = new ListSection(range, name, nameOffset, body);
        templateBuilder.addListSection(section);
        sections.add(section);
        return section;
    }

    private CursorRange verifyAndUpdateEnd(Cursor newEnd) {
        var range = new CursorRange(this.end, newEnd);
        this.end.set(newEnd);
        return range;
    }
}