# Zig でフラグをパースする


published: 2026-03-21

かんたんなコードを書いた。
自分用。

Zig らしいコードになっているか不明。


## バージョン

Zig v0.15.2


## コード

### `src/cli.zig`

```zig
const std = @import("std");

pub const Flag = struct {
    name: []const u8,
    alias: ?[]const u8 = null,
    description: []const u8,
    isBoolFlag: bool = false,
    isValueFlag: bool = false,
    is: bool = false,
    value: ?[]const u8 = null,
};

pub const ParseErr = struct {
    name: []const u8 = "",
    arg: []const u8 = "",
};

pub const CLI = struct {
    arena: std.heap.ArenaAllocator,
    name: []const u8,
    description: []const u8,
    usage: []const u8 = "",
    flags: std.ArrayList(*Flag),
    positionals: std.ArrayList([]const u8),

    pub fn init(allocator: std.mem.Allocator, name: []const u8, description: []const u8) CLI {
        return .{
            .arena = std.heap.ArenaAllocator.init(allocator),
            .name = name,
            .description = description,
            .flags = .{},
            .positionals = .{},
        };
    }

    pub fn deinit(self: *CLI) void {
        const allocator = self.arena.allocator();
        self.flags.deinit(allocator);
        self.positionals.deinit(allocator);
        self.arena.deinit();
    }

    pub fn flagBool(self: *CLI, name: []const u8, description: []const u8) !*Flag {
        const allocator = self.arena.allocator();
        const flag = try allocator.create(Flag);
        flag.* = .{
            .name = name,
            .description = description,
            .isBoolFlag = true,
        };
        try self.flags.append(allocator, flag);
        return flag;
    }

    pub fn flagValue(self: *CLI, name: []const u8, description: []const u8) !*Flag {
        const allocator = self.arena.allocator();
        const flag = try allocator.create(Flag);
        flag.* = .{
            .name = name,
            .description = description,
            .isValueFlag = true,
        };
        try self.flags.append(allocator, flag);
        return flag;
    }

    pub fn parse(self: *CLI, argv: [][:0]u8) ?ParseErr {
        const allocator = self.arena.allocator();
        var i: usize = 1;

        while (i < argv.len) : (i += 1) {
            const arg = argv[i];

            if (!std.mem.startsWith(u8, arg, "-")) {
                self.positionals.append(allocator, arg) catch {
                    return ParseErr{ .arg = arg, .name = "internal error" };
                };
                continue;
            }
            const flag = self.lookupFlag(arg) catch {
                return ParseErr{ .arg = arg, .name = "flag not found" };
            };
            if (flag.isBoolFlag) {
                flag.is = true;
                continue;
            }
            if (flag.isValueFlag) {
                if (i + 1 >= argv.len) {
                    return ParseErr{ .arg = arg, .name = "missing flag value" };
                }
                i += 1;
                flag.value = argv[i];
                flag.is = true;
            }
        }
        return null;
    }

    fn lookupFlag(self: *CLI, name: []const u8) !*Flag {
        for (self.flags.items) |flag| {
            if (std.mem.eql(u8, flag.name, name)) {
                return flag;
            }
            if (flag.alias != null and std.mem.eql(u8, flag.alias.?, name)) {
                return flag;
            }
        }
        return error.FlagNotFound;
    }

    pub fn generateHelpText(self: *CLI) ![]u8 {
        const allocator = self.arena.allocator();
        var buf: std.ArrayList(u8) = .{};
        const writer = buf.writer(allocator);

        try writer.print("{s}\n", .{self.name});
        try writer.print("{s}\n", .{self.description});
        try writer.print("\n", .{});
        try writer.print("Usage:\n", .{});
        try writer.print("  {s}\n", .{self.usage});

        if (self.flags.items.len > 0) {
            try writer.print("\n", .{});
            try writer.print("Flags:\n", .{});
            for (self.flags.items) |flag| {
                if (flag.alias != null) {
                    try writer.print("  {s}, {s}\t{s}\n", .{ flag.alias.?, flag.name, flag.description });
                } else {
                    try writer.print("  {s}\t{s}\n", .{ flag.name, flag.description });
                }
            }
        }
        return buf.toOwnedSlice(allocator);
    }
};

```

### `src/main.zig`

```zig
const std = @import("std");
const CLI = @import("cli.zig").CLI;

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    const args = try std.process.argsAlloc(allocator);
    defer std.process.argsFree(allocator, args);

    var cli = CLI.init(allocator, "sampleapp", "very sample app");
    defer cli.deinit();
    cli.usage = "sampleapp <text>";

    const helpFlag = try cli.flagBool("--help", "show help");
    const versionFlag = try cli.flagBool("--version", "show version");
    versionFlag.alias = "-v";

    const err = cli.parse(args);
    if (err != null) {
        std.debug.print("error: {s}: {s}\n", .{ err.?.name, err.?.arg });
        return;
    }
    if (helpFlag.is) {
        const helpText = try cli.generateHelpText();
        std.debug.print("{s}\n", .{helpText});
        return;
    }
    if (versionFlag.is) {
        std.debug.print("v0.0.1\n", .{});
        return;
    }
    if (cli.positionals.items.len > 1) {
        std.debug.print("error: too many positional arguments.\n", .{});
        return;
    }
    if (cli.positionals.items.len == 0) {
        std.debug.print("error: missing positional arguments.\n", .{});
        return;
    }
    const text = cli.positionals.items[0];
    std.debug.print("ok\n", .{});
    std.debug.print("text: {s}\n", .{text});
}

```

### `.gitignore`

```gitignore
.zig-cache
zig-out

```

### `build.zig`

```zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "sampleapp",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
            .imports = &.{},
        }),
    });
    b.installArtifact(exe);

    const run_step = b.step("run", "Run the app");
    const run_cmd = b.addRunArtifact(exe);
    run_step.dependOn(&run_cmd.step);
    run_cmd.step.dependOn(b.getInstallStep());
    if (b.args) |args| {
        run_cmd.addArgs(args);
    }
}

```

### `build.zig.zon`

```zon
.{
    .name = .sampleapp,
    .version = "0.0.0",
    .fingerprint = 0xb4305fdf1eb80bed,
    .minimum_zig_version = "0.15.2",
    .dependencies = .{},
    .paths = .{
        "build.zig",
        "build.zig.zon",
        "src",
    },
}

```

### `LICENSE`

```LICENSE
MIT License

Copyright (c) 2026 nua

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

```

### memos

ここでフラグを定義


mark: `src/main.zig:16`

フラグをパース


mark: `src/main.zig:20`

ヘルプテキストを表示


mark: `src/main.zig:27`

実行するとこんな感じ


![result.png](https://lab.enuesaa.dev/prototype/zig-parse-flags/result.png)

ヘルプテキスト


![helptext.png](https://lab.enuesaa.dev/prototype/zig-parse-flags/helptext.png)

