Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🔧 The ultimate Zig library for seamless command line argument parsing.

License

NotificationsYou must be signed in to change notification settings

prajwalch/yazap

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

testpages-build-deployment

Yazap

Note

This branch targets themaster branch of zig.Seesupported versions table.

The ultimatezig library for seamless command-line parsing.Effortlessly handles options, subcommands, and custom arguments with ease.

Inspired byclap-rs andandrewrk/ziglang: src-self-hosted/arg.zig

Supported versions table

yazapZig
mainmaster
0.6.30.14.0
0.5.10.12.0,0.12.1 and0.13.0
<=0.5.0Not supported to any

Key Features:

  • Options (short and long):

    • Providing values with=, space, or no space (-f=value,-f value,-fvalue).
    • Supports delimiter-separated values with= or without space (-f=v1,v2,v3,-fv1:v2:v3).
    • Chaining multiple short boolean options (-abc).
    • Providing values and delimiter-separated values for multiple chained options using= (-abc=val,-abc=v1,v2,v3).
    • Specifying an option multiple times (-a 1 -a 2 -a 3).
  • Positional arguments:

    • Supports positional arguments alongside options for more flexible command-line inputs. For example:
      • command <positional_arg>
      • command <arg1> <arg2> <arg3>
  • Nested subcommands:

    • Organize commands with nested subcommands for a structured command-line interface. For example:
      • command subcommand
      • command subcommand subsubcommand
  • Automatic help handling and generation

  • Custom Argument definition:

    • Define customArgument types for specific application requirements.

Limitations:

  • Does not support delimiter-separated values using space (-f v1,v2,v3).
  • Does not support providing value and delimiter-separated values for multiplechained options using space (-abc value, -abc v1,v2,v3).

Installing

  1. Run the following command:
zig fetch --save git+https://github.com/prajwalch/yazap
  1. Add the following tobuild.zig:
constyazap=b.dependency("yazap", .{});exe.root_module.addImport("yazap",yazap.module("yazap"));

Documentation

For detailed and comprehensive documentation, please visitthis link.

Warning

The documentation site is currently broken, in the meantime check out the source code.

Usage

Initializing Yazap

To begin usingyazap, the first step is to create an instance ofApp by callingApp.init(allocator, "Your app name", "optional description"). This functioninternally creates a root command for your application.

varapp=App.init(allocator,"myls","My custom ls");deferapp.deinit();

Obtaining the Root Command

TheApp itself does not provideany methods for adding arguments to your command. Its main purpose is toinitialize the library, to invoke the parser with necessary arguments, and todeinitilize the library.

To add arguments and subcommands, acquire the root command by callingApp.rootCommand().This gives you access to the core command of your application by returning a pointer to it.

varmyls=app.rootCommand();

Adding Arguments

Once you have obtained the root command, you can proceed to add arguments andsubcommands using the methods available in theCommand. For a complete listof available methods, refer to theCommand APIdocumentation.

trymyls.addArg(Arg.positional("FILE",null,null));trymyls.addArg(Arg.booleanOption("all",'a',"Don't ignore the hidden directories"));trymyls.addArg(Arg.booleanOption("recursive",'R',"List subdirectories recursively"));trymyls.addArg(Arg.booleanOption("one-line",'1',null));trymyls.addArg(Arg.booleanOption("size",'s',null));trymyls.addArg(Arg.booleanOption("version",null,null));trymyls.addArg(Arg.singleValueOption("ignore",'I',null));trymyls.addArg(Arg.singleValueOption("hide",null,null));trymyls.addArg(Arg.singleValueOptionWithValidValues("color",'C',"Colorize the output",    &[_][]constu8{"always","auto","never" }));

Alternatively, you can add multiple arguments in a single function call usingCommand.addArgs():

trymyls.addArgs(&[_]Arg {Arg.positional("FILE",null,null),Arg.booleanOption("all",'a',"Don't ignore the hidden directories"),Arg.booleanOption("recursive",'R',"List subdirectories recursively"),Arg.booleanOption("one-line",'1',null),Arg.booleanOption("size",'s',null),Arg.booleanOption("version",null,null),Arg.singleValueOption("ignore",'I',null),Arg.singleValueOption("hide",null,null),Arg.singleValueOptionWithValidValues("color",'C',"Colorize the output",        &[_][]constu8{"always","auto","never" }    ),});

Note that for any option that accepts value, you can set its value placeholder to display in thehelp message. If you don't set the placeholder, the option name will be displayed by default.

varignore_opt=Arg.singleValueOption("ignore",'I',null);ignore_opt.setValuePlaceholder("PATTERN");varhide_opt=Arg.singleValueOption("hide",null,null);hide_opt.setValuesPlaceholder("PATTERN");varcolor_opt=Arg.singleValueOptionWithValidValues("color",'C',"Colorize the output",    &[_][]constu8{"always","auto","never" });color_opt.setValuePlaceholder("WHEN");trymyls.addArgs(&[_]Arg{ignore_opt,hide_opt,color_opt });

Adding Subcommands

To create a subcommand, useApp.createCommand("name", "optional description") thenyou can add its own arguments and subcommands just like the root command. After youfinish adding arguments, add it as a root subcommand by callingCommand.addSubcommand().

varupdate_cmd=app.createCommand("update","Update the app or check for new updates");tryupdate_cmd.addArg(Arg.booleanOption("check-only",null,"Only check for new update"));tryupdate_cmd.addArg(Arg.singleValueOptionWithValidValues("branch",'b',"Branch to update",    &[_][]constu8{"stable","nightly","beta" }));trymyls.addSubcommand(update_cmd);

Parsing Arguments

Once you have finished adding all the arguments and subcommands, callApp.parseProcess()to start parsing the arguments given to the current process. This function internally utilizesstd.process.argsAllocto obtain the raw arguments. Alternatively, you can useApp.parseFrom() and pass your own rawarguments, which can be useful during testing. Both functions returnsArgMatches.

constmatches=tryapp.parseProcess();if (matches.containsArg("version")) {log.info("v0.1.0", .{});return;}if (matches.getSingleValue("FILE"))|f| {log.info("List contents of {f}");return;}if (matches.subcommandMatches("update"))|update_cmd_matches| {if (update_cmd_matches.containsArg("check-only")) {std.log.info("Check and report new update", .{});return;    }if (update_cmd_matches.getSingleValue("branch"))|branch| {std.log.info("Branch to update: {s}", .{branch});return;    }return;}if (matches.containsArg("all")) {log.info("show all", .{});return;}if (matches.containsArg("recursive")) {log.info("show recursive", .{});return;}if (matches.getSingleValue("ignore"))|pattern| {log.info("ignore pattern = {s}", .{pattern});return;}if (matches.containsArg("color")) {constwhen=matches.getSingleValue("color").?;log.info("color={s}", .{when});return;}

Handling Help

-h and--h flag is globally available to all the commands and subcommands andhandled automatically when they are passed to command line. However, if you need tomanually display the help message there are currently two ways to do it.

1. By invokingApp.displayHelp() andApp.displaySubcommandHelp().

App.displayHelp() displays the help message for the root command andother handApp.displaySubcommandHelp() displays the help message for theactive subcommand.

For e.x.: ifgh auth login were passed thenApp.displayHelp() would display thehelp forgh andApp.displaySubcommandHelp() display the help forlogin.

Example:

if (!matches.containsArgs()) {tryapp.displayHelp();return;}if (matches.subcommandMatches("update"))|update_cmd_matches| {if (!update_cmd_matches.containsArgs()) {tryapp.displaySubcommandHelp();return;    }}

2. By setting.help_on_empty_args property to the command.

The.help_on_empty_args property which when set to a command, it instructsthe handler to display the help message for that particular command when argumentsare not provided. It behaves exactly like the code shown at the example above.

Example:

varapp=App.init(allocator,"myls","My custom ls");deferapp.deinit();varmyls=app.rootCommand();myls.setProperty(.help_on_empty_args);varupdate_cmd=app.createCommand("update","Update the app or check for new updates");update_cmd.setProperty(.help_on_empty_args);trymyls.addSubcommand(update_cmd);constmatches=trymyls.parseProcess();// --snip--

Putting it All Together

conststd=@import("std");constyazap=@import("yazap");constallocator=std.heap.page_allocator;constlog=std.log;constApp=yazap.App;constArg=yazap.Arg;pubfnmain()anyerror!void {varapp=App.init(allocator,"myls","My custom ls");deferapp.deinit();varmyls=app.rootCommand();myls.setProperty(.help_on_empty_args);trymyls.addArgs(&[_]Arg {Arg.positional("FILE",null,null),Arg.booleanOption("all",'a',"Don't ignore the hidden directories"),Arg.booleanOption("recursive",'R',"List subdirectories recursively"),Arg.booleanOption("one-line",'1',null),Arg.booleanOption("size",'s',null),Arg.booleanOption("version",null,null),    });varignore_opt=Arg.singleValueOption("ignore",'I',null);ignore_opt.setValuePlaceholder("PATTERN");varhide_opt=Arg.singleValueOption("hide",null,null);hide_opt.setValuesPlaceholder("PATTERN");varcolor_opt=Arg.singleValueOptionWithValidValues("color",'C',"Colorize the output",        &[_][]constu8{"always","auto","never" }    );color_opt.setValuePlaceholder("WHEN");trymyls.addArgs(&[_]Arg{ignore_opt,hide_opt,color_opt });// Update subcommand.varupdate_cmd=app.createCommand("update","Update the app or check for new updates");update_cmd.setProperty(.help_on_empty_args);tryupdate_cmd.addArg(Arg.booleanOption("check-only",null,"Only check for new update"));tryupdate_cmd.addArg(Arg.singleValueOptionWithValidValues("branch",'b',"Branch to update",        &[_][]constu8{"stable","nightly","beta" }    ));trymyls.addSubcommand(update_cmd);// Get the parse result.constmatches=tryapp.parseProcess();if (matches.containsArg("version")) {log.info("v0.1.0", .{});return;    }if (matches.getSingleValue("FILE"))|f| {log.info("List contents of {f}");return;    }if (matches.subcommandMatches("update"))|update_cmd_matches| {if (update_cmd_matches.containsArg("check-only")) {std.log.info("Check and report new update", .{});return;        }if (update_cmd_matches.getSingleValue("branch"))|branch| {std.log.info("Branch to update: {s}", .{branch});return;        }return;    }if (matches.containsArg("all")) {log.info("show all", .{});return;    }if (matches.containsArg("recursive")) {log.info("show recursive", .{});return;    }if (matches.getSingleValue("ignore"))|pattern| {log.info("ignore pattern = {s}", .{pattern});return;    }if (matches.containsArg("color")) {constwhen=matches.getSingleValue("color").?;log.info("color={s}", .{when});return;    }}

Alternate Parsers

About

🔧 The ultimate Zig library for seamless command line argument parsing.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors13

Languages


[8]ページ先頭

©2009-2025 Movatter.jp