概要
📟 Build ergonomic, high-performance command-line tools (CLI) with zig.
開発ツールできること
- Modular commands & subcommands
- Fast flag parsing (--flag, --flag=value, shorthand -abc)
- Type-safe support for bool, int, string
- Named positional arguments with required, optional, variadic
計測したスター増加
- 24時間
- 0
- 7日間
- 0
- 15日間
- +4
- 1か月
- 履歴を収集中
期間ごとの純増数です。期間は重複しており、日別の値ではありません。未計測の値は空欄です。スター数は注目度の指標であり、品質の保証ではありません。
README.md
オリジナル📟 zli - a blazing-fast CLI framework for Zig.
Build modular, ergonomic, and high-performance CLIs with ease.
Batteries included. ZLI reference docs
🚀 Features
- Modular commands & subcommands
- Fast flag parsing (
--flag,--flag=value, shorthand-abc) - Type-safe support for
bool,int,string - Named positional arguments with
required,optional,variadic - Variadic args can keep parsing flags after the positionals (
passthrough = false) - Repeated flags (
ctx.flagValues) and given-vs-default (ctx.isFlagSet) - Errors on a separate writer (
error_writer), help stays onwriter - The process environment in every command (
ctx.environ_map) - Auto help/version/deprecation handling
- Pretty help output with aligned flags & args
- Your own message at the end of a command's help (
help_footer) - Spinners for a more interactive experience
- Usage hints, context-aware
📦 Installation
zig fetch --save=zli https://github.com/xcaeser/zli/archive/v7.1.0.tar.gz
Add to your build.zig:
const zli_dep = b.dependency("zli", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("zli", zli_dep.module("zli"));
🌱 Single-file Quick Start
Start with one src/main.zig: initialize the root command, add a flag, add a subcommand, then run it.
const std = @import("std");
const Io = std.Io;
const zli = @import("zli");
pub fn main(init: std.process.Init) !void {
const io = init.io;
var wbuf: [1024]u8 = undefined;
var stdout_writer = Io.File.Writer.init(.stdout(), io, &wbuf);
const stdout = &stdout_writer.interface;
defer stdout.flush() catch {};
var rbuf: [1024]u8 = undefined;
var stdin_reader = Io.File.Reader.init(.stdin(), io, &rbuf);
const stdin = &stdin_reader.interface;
const init_options = zli.InitOptions{
.allocator = init.gpa,
.environ_map = init.environ_map,
.io = io,
.writer = stdout,
.reader = stdin,
};
const root = try zli.Command.init(init_options, .{
.name = "hello",
.description = "A tiny zli app",
.version = .{ .major = 0, .minor = 1, .patch = 0, .pre = null, .build = null },
}, showHelp);
try root.addFlag(.{
.name = "verbose",
.shortcut = "v",
.description = "Print more details",
.type = .Bool,
.default_value = .{ .Bool = false },
.persistent = true,
});
const greet = try zli.Command.init(init_options, .{
.name = "greet",
.description = "Greet someone",
}, greetSomeone);
try greet.addPositionalArg(.{
.name = "name",
.description = "Who to greet",
.required = true,
});
try root.addCommand(greet);
var args_iter = init.minimal.args.iterate();
root.runAndExit(&args_iter, .{});
}
fn showHelp(ctx: zli.CommandContext) !void {
try ctx.command.printHelp();
}
fn greetSomeone(ctx: zli.CommandContext) !void {
const verbose = ctx.flag("verbose", bool);
const name = ctx.getArg("name") orelse "friend";
if (verbose) {
try ctx.writer.print("Preparing greeting for {s}\n", .{name});
}
try ctx.writer.print("Hello, {s}!\n", .{name});
}
Run it:
zig build run -- greet Ada
zig build run -- --verbose greet Ada
zig build run -- greet Ada --help
Use runAndExit for normal CLI binaries: it prints errors/help (including error: Name for errors your commands return) and exits with the right process code. run does the same but returns the exit code instead of exiting. Use execute when you want library-friendly behavior for tests, embedding, or custom error handling; it returns errors instead of exiting the process.
🗂 Folder Structure (but you can do what you want)
your-app/
├── build.zig
├── src/
│ ├── main.zig
│ └── cli/
│ ├── root.zig // zli entrypoint
│ ├── run.zig // subcommand 1
│ └── version.zig // subcommand 1
... // subcommand of subcommands, go nuts
- Each command is in its own file
- You explicitly register subcommands
root.zigis the entry point
🧪 Example
Your program
// src/main.zig
const std = @import("std");
const Io = std.Io;
const cli = @import("cli/root.zig");
pub fn main(init: std.process.Init) !void {
const io = init.io;
var wbuf: [1024]u8 = undefined;
var stdout_writer = Io.File.Writer.init(.stdout(), io, &wbuf);
const stdout = &stdout_writer.interface;
defer stdout.flush() catch {};
var rbuf: [1024]u8 = undefined;
var stdin_reader = Io.File.Reader.init(.stdin(), io, &rbuf);
const stdin = &stdin_reader.interface;
const root = try cli.build(.{
.allocator = init.gpa,
.environ_map = init.environ_map,
.io = io,
.writer = stdout,
.reader = stdin,
});
var argsIter = init.minimal.args.iterate();
root.runAndExit(&argsIter, .{}); // Or pass data with: root.runAndExit(&argsIter, .{ .data = &my_data });
}
Root command - entrypoint
// src/cli/root.zig
const std = @import("std");
const zli = @import("zli");
const run = @import("run.zig");
const version = @import("version.zig");
pub fn build(init_options: zli.InitOptions) !*zli.Command {
const root = try zli.Command.init(init_options, .{
.name = "blitz",
.description = "Your dev toolkit CLI",
.version = .{ .major = 0, .minor = 0, .patch = 1, .pre = null, .build = null },
.help_footer = "Docs: https://example.com/blitz",
}, showHelp);
try root.addCommands(&.{
try run.register(init_options),
try version.register(init_options),
});
return root;
}
fn showHelp(ctx: zli.CommandContext) !void {
try ctx.command.printHelp();
}
Run subcommand
// src/cli/run.zig
const std = @import("std");
const zli = @import("zli");
const now_flag = zli.Flag{
.name = "now",
.shortcut = "n",
.description = "Run immediately",
.type = .Bool,
.default_value = .{ .Bool = false },
};
pub fn register(init_options: zli.InitOptions) !*zli.Command {
const cmd = try zli.Command.init(init_options, .{
.name = "run",
.description = "Run your workflow",
}, run);
try cmd.addFlag(now_flag);
try cmd.addPositionalArg(.{
.name = "script",
.description = "Script to execute",
.required = true,
});
try cmd.addPositionalArg(.{
.name = "env",
.description = "Environment name",
.required = false,
});
return cmd;
}
fn run(ctx: zli.CommandContext) !void {
const now = ctx.flag("now", bool); // type-safe flag access
const script = ctx.getArg("script") orelse {
try ctx.writer.print("Missing script arg\n", .{});
return;
};
const env = ctx.getArg("env") orelse "default";
std.debug.print("Running {s} in {s} (now = {})\n", .{ script, env, now });
// You can also get other commands by name:
// if (ctx.root.findCommand("create")) |create_cmd| {
// try create_cmd.printUsageLine();
// }
// if you passed data to your root command, you can access it here:
// const object = ctx.getContextData(type_of_your_data); // can be struct, []const u8, etc., object is a pointer.
}
Version subcommand
// src/cli/version.zig
const std = @import("std");
const zli = @import("zli");
pub fn register(init_options: zli.InitOptions) !*zli.Command {
return zli.Command.init(init_options, .{
.name = "version",
.shortcut = "v",
.description = "Show CLI version",
}, show);
}
fn show(ctx: zli.CommandContext) !void {
try ctx.root.printVersion();
}
Spinners example
Available functions:
spinner.start: spins a message on a new line, replacing any running spinnerspinner.updateStyle: sets the frames and refresh rate (both; an omitted field goes back to its default). Pick frames fromzli.SpinnerStylesor pass your own:.{ .frames = &.{ "+", "x" } }spinner.updateMessage: to update text of a running spinnerspinner.succeed,fail,warn,info,preserve: end the line you started with a ✔, ✖, ⚠, i or dim » mark. They also work without astart, to print a one-off status line.spinner.stoperases the line instead- Recommendation: use
spinner.printinstead of your ownwriter.printto not have non-displayed messages as spinner works on its own thread - When the output is not a terminal (piped, redirected to a file, CI logs), nothing animates: only the finished lines are printed, without colors or escape codes
- Ctrl+C while a spinner runs restores the hidden cursor before the process exits
const std = @import("std");
const zli = @import("zli");
pub fn run(ctx: zli.CommandContext) !void {
const spinner = ctx.spinner;
spinner.updateStyle(.{ .frames = zli.SpinnerStyles.earth, .refresh_rate_ms = 150 }); // many styles available
// Step 1
try spinner.start("Step 1", .{}); // New line
try ctx.io.sleep(.fromSeconds(2), .awake);
try spinner.succeed("Step 1 success", .{}); // end each start with succeed, fail, warn, info or preserve
spinner.updateStyle(.{ .frames = zli.SpinnerStyles.weather, .refresh_rate_ms = 150 }); // many styles available
// Step 2
try spinner.start("Step 2", .{}); // New line
try ctx.io.sleep(.fromSeconds(3), .awake);
spinner.updateStyle(.{ .frames = zli.SpinnerStyles.dots, .refresh_rate_ms = 150 }); // many styles available
try spinner.updateMessage("Step 2: Calculating things...", .{}); // update the text of step 2
const i = work(); // do some work
try spinner.info("Step 2 info: {d}", .{i});
// Step 3
try spinner.start("Step 3", .{});
try ctx.io.sleep(.fromSeconds(2), .awake);
try spinner.warn("Step 3 slower than expected", .{});
// Step 4
try spinner.start("Step 4", .{});
try ctx.io.sleep(.fromSeconds(2), .awake);
try spinner.fail("Step 4 fail", .{});
try spinner.print("Finish\n", .{}); // instead of using ctx.writer or another writer to avoid concurrency issues
}
fn work() u128 {
var i: u128 = 1;
for (0..100000000) |t| {
i = (t + i);
}
return i;
}
✅ Features Checklist
- Commands & subcommands
- Command aliases
- Flags & shorthands
- Type-safe flag values
- Positional args (required, optional, variadic): a variadic command takes every word after its first positional as a positional, flag-like ones included (
app shell ls -la) - Named access:
ctx.getArg("name") - Context data
- Help/version auto handling
- Deprecation notices
- Pretty-aligned help for flags & args
- Clean usage output like Cobra
- Spinners and loading state (very powerful)
- Persistent flags
📚 Documentation
See docs for full usage, examples, and internals.
📝 License
MIT. See LICENSE. Contributions welcome.
関連プロジェクトを探す
読み込み中…