summaryrefslogtreecommitdiff
path: root/src/main/java/org/zwobble/hobgoblin/compiler/HobgoblinCli.java
blob: 7e2dceed1859756eda2a10059c2563b454534371 (plain)
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
package org.zwobble.hobgoblin.compiler;

import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import org.zwobble.hobgoblin.compiler.errors.SourceError;
import org.zwobble.hobgoblin.compiler.sources.NullSource;
import org.zwobble.hobgoblin.compiler.util.argparse4j.PathArgumentType;

import java.io.IOException;
import java.nio.file.Path;

public class HobgoblinCli {
    public static void main(String[] rawArgs) throws IOException, InterruptedException {
        var args = parseArgs(rawArgs);
        try {
            compile(args);
        } catch (SourceError error) {
            if (!(error.source() instanceof NullSource)) {
                System.err.println(error.source().describe());
            }
            System.err.println(error.getMessage());
            System.exit(2);
        }
    }

    private static void compile(Namespace args) throws IOException, InterruptedException {
        var sourcePath = args.<Path>get("source");

        switch (args.<Command>get("command")) {
            case COMPILE -> {
                HobgoblinCompiler.compile(sourcePath);
            }
        }
    }

    private static Namespace parseArgs(String[] args) {
        var parser = ArgumentParsers.newFor("hobgoblin").build()
            .defaultHelp(true);

        var subparsers = parser.addSubparsers();

        var compileSubParser = subparsers.addParser("compile");
        compileSubParser.setDefault("command", Command.COMPILE);
        compileSubParser
            .addArgument("source")
            .type(new PathArgumentType())
            .required(true);

        try {
            return parser.parseArgs(args);
        } catch (ArgumentParserException e) {
            parser.handleError(e);
            System.exit(1);
            throw new RuntimeException(e);
        }
    }

    private enum Command {
        COMPILE,
    }
}