summaryrefslogtreecommitdiff
path: root/src/Agent.App/Cli/CommandLine.cs
blob: 3fdac9f1d27d60c165ecf8c75eaf60a649fc39d1 (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
namespace Agent.App.Cli;

public enum AppCommand { Serve, Check }

public sealed record CommandLine(AppCommand Command, string? ConfigPath, string? Language, string? Transport)
{
    public static CommandLine Parse(string[] args)
    {
        bool implicitServe = args.Length == 0 || args[0].StartsWith("--", StringComparison.Ordinal);
        AppCommand command = implicitServe ? AppCommand.Serve : args[0] switch
        {
            "serve" => AppCommand.Serve,
            "check" => AppCommand.Check,
            _ => throw new CommandLineException("Expected 'serve' or 'check'.")
        };

        string? config = null;
        string? language = null;
        string? transport = null;
        for (int i = implicitServe ? 0 : 1; i < args.Length; i++)
        {
            string option = args[i];
            if (i + 1 >= args.Length) throw new CommandLineException($"Missing value for '{option}'.");
            string value = args[++i];
            switch (option)
            {
                case "--config" when config is null: config = value; break;
                case "--lang" when language is null: language = value; break;
                case "--transport" when command == AppCommand.Serve && transport is null && value is "stdio" or "http": transport = value; break;
                case "--transport" when command == AppCommand.Check: throw new CommandLineException("--transport is only valid for serve.");
                case "--transport": throw new CommandLineException("Transport must be stdio or http.");
                default: throw new CommandLineException($"Unknown or duplicate option '{option}'.");
            }
        }
        return new CommandLine(command, config, language, transport);
    }
}

public sealed class CommandLineException(string message) : Exception(message);