summaryrefslogtreecommitdiff
path: root/src/cli/action.zig
blob: 41173a9f1f163b6bf03d69968937083384ca7ade (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
const std = @import("std");
const Allocator = std.mem.Allocator;

pub const DetectError = error{
    /// Multiple actions were detected. You can specify at most one
    /// action on the CLI otherwise the behavior desired is ambiguous.
    MultipleActions,

    /// An unknown action was specified.
    InvalidAction,
};

/// Detect the action from CLI args.
pub fn detectArgs(comptime E: type, alloc: Allocator) !?E {
    var iter = try std.process.argsWithAllocator(alloc);
    defer iter.deinit();
    return try detectIter(E, &iter);
}

/// Detect the action from any iterator. Each iterator value should yield
/// a CLI argument such as "--foo".
///
/// The comptime type E must be an enum with the available actions.
/// If the type E has a decl `detectSpecialCase`, then it will be called
/// for each argument to allow handling of special cases. The function
/// signature for `detectSpecialCase` should be:
///
///   fn detectSpecialCase(arg: []const u8) ?SpecialCase(E)
///
pub fn detectIter(
    comptime E: type,
    iter: anytype,
) DetectError!?E {
    var fallback: ?E = null;
    var pending: ?E = null;
    while (iter.next()) |arg| {
        // Allow handling of special cases.
        if (@hasDecl(E, "detectSpecialCase")) special: {
            const special = E.detectSpecialCase(arg) orelse break :special;
            switch (special) {
                .action => |a| return a,
                .fallback => |a| fallback = a,
                .abort_if_no_action => if (pending == null) return null,
            }
        }

        // Commands must start with "+"
        if (arg.len == 0 or arg[0] != '+') continue;
        if (pending != null) return DetectError.MultipleActions;
        pending = std.meta.stringToEnum(E, arg[1..]) orelse
            return DetectError.InvalidAction;
    }

    // If we have an action, we always return that action, even if we've
    // seen "--help" or "-h" because the action may have its own help text.
    if (pending != null) return pending;

    // If we have no action but we have a fallback, then we return that.
    if (fallback) |a| return a;

    return null;
}

/// The action enum E can implement the decl `detectSpecialCase` to
/// return this enum in order to perform various special case actions.
pub fn SpecialCase(comptime E: type) type {
    return union(enum) {
        /// Immediately return this action.
        action: E,

        /// Return this action if no other action is found.
        fallback: E,

        /// If there is no pending action (we haven't seen an action yet)
        /// then we should return no action. This is kind of weird but is
        /// a special case to allow "-e" in Ghostty.
        abort_if_no_action,
    };
}

test "detect direct match" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const Enum = enum { foo, bar, baz };

    var iter = try std.process.ArgIteratorGeneral(.{}).init(
        alloc,
        "+foo",
    );
    defer iter.deinit();
    const result = try detectIter(Enum, &iter);
    try testing.expectEqual(Enum.foo, result.?);
}

test "detect invalid match" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const Enum = enum { foo, bar, baz };

    var iter = try std.process.ArgIteratorGeneral(.{}).init(
        alloc,
        "+invalid",
    );
    defer iter.deinit();
    try testing.expectError(
        DetectError.InvalidAction,
        detectIter(Enum, &iter),
    );
}

test "detect multiple actions" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const Enum = enum { foo, bar, baz };

    var iter = try std.process.ArgIteratorGeneral(.{}).init(
        alloc,
        "+foo +bar",
    );
    defer iter.deinit();
    try testing.expectError(
        DetectError.MultipleActions,
        detectIter(Enum, &iter),
    );
}

test "detect no match" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const Enum = enum { foo, bar, baz };

    var iter = try std.process.ArgIteratorGeneral(.{}).init(
        alloc,
        "--some-flag",
    );
    defer iter.deinit();
    const result = try detectIter(Enum, &iter);
    try testing.expect(result == null);
}

test "detect special case action" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const Enum = enum {
        foo,
        bar,

        fn detectSpecialCase(arg: []const u8) ?SpecialCase(@This()) {
            return if (std.mem.eql(u8, arg, "--special"))
                .{ .action = .foo }
            else
                null;
        }
    };

    {
        var iter = try std.process.ArgIteratorGeneral(.{}).init(
            alloc,
            "--special +bar",
        );
        defer iter.deinit();
        const result = try detectIter(Enum, &iter);
        try testing.expectEqual(Enum.foo, result.?);
    }

    {
        var iter = try std.process.ArgIteratorGeneral(.{}).init(
            alloc,
            "+bar --special",
        );
        defer iter.deinit();
        const result = try detectIter(Enum, &iter);
        try testing.expectEqual(Enum.foo, result.?);
    }

    {
        var iter = try std.process.ArgIteratorGeneral(.{}).init(
            alloc,
            "+bar",
        );
        defer iter.deinit();
        const result = try detectIter(Enum, &iter);
        try testing.expectEqual(Enum.bar, result.?);
    }
}

test "detect special case fallback" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const Enum = enum {
        foo,
        bar,

        fn detectSpecialCase(arg: []const u8) ?SpecialCase(@This()) {
            return if (std.mem.eql(u8, arg, "--special"))
                .{ .fallback = .foo }
            else
                null;
        }
    };

    {
        var iter = try std.process.ArgIteratorGeneral(.{}).init(
            alloc,
            "--special",
        );
        defer iter.deinit();
        const result = try detectIter(Enum, &iter);
        try testing.expectEqual(Enum.foo, result.?);
    }

    {
        var iter = try std.process.ArgIteratorGeneral(.{}).init(
            alloc,
            "+bar --special",
        );
        defer iter.deinit();
        const result = try detectIter(Enum, &iter);
        try testing.expectEqual(Enum.bar, result.?);
    }

    {
        var iter = try std.process.ArgIteratorGeneral(.{}).init(
            alloc,
            "--special +bar",
        );
        defer iter.deinit();
        const result = try detectIter(Enum, &iter);
        try testing.expectEqual(Enum.bar, result.?);
    }
}

test "detect special case abort_if_no_action" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const Enum = enum {
        foo,
        bar,

        fn detectSpecialCase(arg: []const u8) ?SpecialCase(@This()) {
            return if (std.mem.eql(u8, arg, "-e"))
                .abort_if_no_action
            else
                null;
        }
    };

    {
        var iter = try std.process.ArgIteratorGeneral(.{}).init(
            alloc,
            "-e",
        );
        defer iter.deinit();
        const result = try detectIter(Enum, &iter);
        try testing.expect(result == null);
    }

    {
        var iter = try std.process.ArgIteratorGeneral(.{}).init(
            alloc,
            "+foo -e",
        );
        defer iter.deinit();
        const result = try detectIter(Enum, &iter);
        try testing.expectEqual(Enum.foo, result.?);
    }

    {
        var iter = try std.process.ArgIteratorGeneral(.{}).init(
            alloc,
            "-e +bar",
        );
        defer iter.deinit();
        const result = try detectIter(Enum, &iter);
        try testing.expect(result == null);
    }
}