getopt.net-bsd 1.1.0

dotnet add package getopt.net-bsd --version 1.1.0
                    
NuGet\Install-Package getopt.net-bsd -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="getopt.net-bsd" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="getopt.net-bsd" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="getopt.net-bsd" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add getopt.net-bsd --version 1.1.0
                    
#r "nuget: getopt.net-bsd, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package getopt.net-bsd@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=getopt.net-bsd&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=getopt.net-bsd&version=1.1.0
                    
Install as a Cake Tool

getopt.net - A GNU and POSIX getopt port to .net

This repository contains the code for my port of the GNU getopt functionality found on most Unix-like systems.

getopt.net is written entirely in C# and is a "cleanroom port"; although not necessary it made the project that much more fun 😊

getopt.net logo

Build Workflow Test Workflow Nuget Version GitHub all releases Nuget Downloads GitHub CodeQL

Installation

There are several methods of installing and using getopt.net in your project.

  1. Add the repository as a submodule, checkout a tag and include it as a project reference in your solution
  2. Use the NuGet package manager: install-package getopt.net-bsd Note the -bsd ending which shows the license used and not system requirements! getopt.net was already in use šŸ˜•
  3. Use the dotnet command-line tools: dotnet add package getopt.net-bsd

NuGet page

Features

Optional main commands and subcommands

Applications can define a single level of bare main commands. Each command owns a normal getopt option set, so all existing GNU/POSIX, Windows, PowerShell and parameter-file behavior remains available inside the command. Global options are parsed before the command; after a command is selected, only that command's options are active.

var getopt = new GetOpt {
    AppArgs = args,
    Options = new[] {
        new Option("verbose", ArgumentType.None, 'v', "Enable verbose output.")
    },
    ShortOpts = "v",
    Commands = new[] {
        new MainCommand(
            "config",
            "Manage application configuration.",
            "cp",
            new Option("create", ArgumentType.None, 'c', "Create configuration."),
            new Option("purge", ArgumentType.None, 'p', "Purge configuration.")
        )
    }
};

while (getopt.GetNextOpt(out var optionArgument) is var option && option != -1) {
    // getopt.SelectedCommand is "config" while handling --create or --purge.
    // option contains 'c' for: myapp --verbose config --create
}

SelectedCommand is populated as soon as the bare command is consumed. A command is not required, even when Commands is configured, which permits global invocations such as myapp --version.

Command and long-option names remain case-sensitive by default. Set CaseInsensitiveMatching = true to use culture-independent case-insensitive matching; short options always remain case-sensitive.

When IgnoreInvalidOptions is false, an unknown command raises CommandMisspeltException if a plausible spelling correction is available, or CommandNotFoundException otherwise. Both exceptions expose the entered Command and a read-only PossibleCommands list. When invalid options are ignored, an unknown command behaves like other invalid input: GetNextOpt returns GetOpt.InvalidOptChar and places the entered command in optionArgument.

Full support for getopt-like command-line options

Separate options

  • --help
    • -h
  • --config=/path/to/config POSIX separator
    • --config /path/to/config GNU separator
    • -c /path/to/config POSIX separator
    • -c/path/to/config GNU extension

Compound options

  • --console, -C
  • --test, -t
  • --config, -c
  • -Ctc/path/to/config Options with required or optional arguments go last!

Support for options using the Windows convention

NOTE: It is possible to use the Windows argument separator (:) with all conventions.
To enable this, you must set AllowWindowsConventions to true.

Separate options

  • /help
    • /h
  • /config=/path/to/config POSIX separator
    • /config /path/to/config GNU separator
    • /config:/path/to/config Windows separator
    • /c /path/to/config POSIX separator
    • /c/path/to/config GNU extension

Compound options

  • /console, /C
  • /test, /t
  • /config, /c
  • /Ctc/path/to/config Options with required or optional arguments go last!

Support for Powershell-style options

Separate options

  • -help
    • -h
  • -config=/path/to/config POSIX separator
    • -config /path/to/config GNU separator
    • -config:/path/to/config Windows separator
    • -c /path/to/config POSIX separator
    • -c/path/to/config GNU extension

Compound options

  • -console, -C
  • -test, -t
  • -config, -c
  • -Ctc/path/to/config Options with required or optional arguments go last!

Support for paramfiles

Some applications, such as GCC, allow passing of paramfile arguments. A paramfile is a line-separated text file which contains one option (and argument) per line. Each line of the paramfile is parsed as if it were passed to getopt.net directly.

Syntax:

myapp @/path/to/paramfile

The standard getopt shortopt-string format is supported:

: denotes a required argument!

; denotes an optional argument!

If none of the above is present after a character in ShortOpts, then no argument is required.

getopt.ShortOpts = "abC:dE:f:GhIjkLmnop:q:r;";
POSIXly correct behaviour

If getopt.ShortOpts is prefixed by a +, or the environment variable POSIXLY_CORRECT is set, then getopt.net will stop processing more options as soon when the first non-option string is found.

If getopt.ShortOpts is prefixed by a -, then each non-option string will be treated as if it were the argument to an option with the value 1.

Customisation is available with long opts:

getopt.Options = new[] {
    new Option { Name = "help", ArgumentType = ArgumentType.None, Value = 'h' }, // brace-initialiser
    new Option("config", ArgumentType.Required, 'c'), // standard constructor
    new Option("version", ArgumentType.Optional, 'v')
};

Fallback to long opts (if available!)

Most developers will have experienced this at some point when using getopt; you added an option to your long opts, but forgot it in your shortopt string. getopt.net improves this behaviour and will check the Options array to see if the option you've provided is there.

Customisable behaviour

getopt.net can be configured to not throw exceptions if that's your thing. Just set the IgnoreXXX options to true, and getopt.net will ignore bad user input!

If IgnoreInvalidOptions is enabled, entering an unknown option won't throw an exception, but instead a ! will be returned. Non-option arguments do not throw when this setting is disabled; they are returned according to the configured parsing mode. If IgnoreMissingArguments is enabled, forgetting to add a required argument won't thow an exception either! Instead, ? will be returned.

The exceptions do contain more info, however.

Help text generation

getopt.net can generate a help text for you, by simply calling getopt.GenerateHelpText().

When commands are configured, generated help adds [command] [command options] to the usage and a Commands section. Each command's getopt options are indented by one additional four-space tab stop below their main command.

The behaviour of the help text generator can be customised to suit your needs. By default, getopt.net will not output application name, version or copyright information. This must be provided with the HelpTextConfig object.

If no application name is provided, getopt.net will attempt to read the application name from the Assembly.
Should this fail, getopt.net will identify your program as unknown.

The default configuration outputs options and switches using the GNU/POSIX convention and doesn't print the conventions supported by your application.

Here's an example:

var getopt = new GetOpt {
    AppArgs = args,
    Options = new[] {
        new Option("help",      ArgumentType.None,      'h', "Displays this help text."),
        new Option("version",   ArgumentType.None,      'v', "Displays the version of this program."),
        new Option("file",      ArgumentType.Required,  'f', "Reads the file back to stdout. The file is read into a local buffer and then printed out. Also I created this really long description to show that getopt.net can handle long descriptions."),
    },
    ShortOpts = "hvf:t;", // the last option isn't an error!
    AllowParamFiles = true,
    AllowWindowsConventions = true,
    AllowPowershellConventions = true
};

static void PrintHelp(GetOpt getopt) {
    Console.WriteLine(getopt.GenerateHelpText(new HelpTextConfig {
        ApplicationName = "getopt.net reference",
        ApplicationVersion = "v1.0.0",
        FooterText = "This is a reference implementation of getopt.net in C#.",
        OptionConvention = OptionConvention.GnuPosix, // Change me to different conventions
        ShowSupportedConventions = true // I'm false by default, but enabling me shows which conventions your app supports
    }));
}

produces the following output:

getopt.net reference v1.0.0 Ā© 2023 Simon Cahill (contact@simonc.eu)

Usage:
    getopt.net reference [options]

Supported option conventions:
    Windows (/): yes
    Powershell (-): yes
    Gnu/Posix (-, --): yes

Switches:
    -h, --help    Displays this help text.
    -v, --version Displays the version of this program.

Options:
                  Reads the file back to stdout. The file is read into a local buffer and then
                  printed out. Also I created this really long description to show that getopt.net
    -f, --file    can handle long descriptions.

This is a reference implementation of getopt.net in C#.

Usage:

For a more detailled description of using getopt.net, please consult the Wiki.

Basic usage in C♯


using getopt.net;

static void Main(string[] args) {

    var getopt = new GetOpt {
        Options = new[] {
            new Option("help",    ArgumentType.None, 'h'),
            new Option("version", ArgumentType.None, 'v'),
            // or, alternatively
            new Option { Name = "config", ArgumentType = ArgumentType.Required, Value = 'c' }
        },
        ShortOpts = "hvc:",
        AppArgs = args, // REQUIRED
        OnlyShortOpts = false,
        // AllowWindowsConventions = true, // enable this for Windows-style options
        // other options here
    };

    int opt = 0;
    // GetNextOpt may throw exceptions, depending on your settings!
    while ((opt = getopt.GetNextOpt(out var optArg)) != -1) {
        switch (opt) {
            case 'h':
                // print help or something
                break;
            case 'c':
                // do something with optArg
                break;
        }
    }
}

Basic usage in VB.Net

Imports getopt.net

module Program

    Dim _progOptions() As [Option] = {
        New [Option]("help", ArgumentType.None, "h"c),
        New [Option]("version", ArgumentType.None, "v"c),
        New [Option]("file", ArgumentType.Required, "f"c)
    }

    Dim _progShortOptions As String = "hvf:"

    sub Main(args as string())
        Dim getopt = New GetOpt With {
            .AppArgs = args,
            .Options = _progOptions,
            .ShortOpts = _progShortOptions,
            ' .AllowWindowsConventions = true ' enable me for Windows-style options!
        }

        Dim optChar = 0
        Dim optArg As String = Nothing
        Dim fileToRead As String = Nothing

        While optChar <> -1
            optChar = getopt.GetNextOpt(optArg)

            Select Case optChar
                Case Convert.ToInt32("h"c)
                    ' do something
                    Return
                Case Convert.ToInt32("v"c)
                    ' do something else
                    Return
                Case Convert.ToInt32("f"c)
                    ' do something with optArg
            End Select
        End While
    end sub

end module

Bugs and errors

If you encounter a bug, please add a GitHub Issue and/or create a fork of the project and create a pull request.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Framework net46 is compatible.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETFramework 4.6

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 1,478 8/18/2026
1.0.2 127 7/27/2026
1.0.1 892 9/23/2024
1.0.0 272 7/17/2024
0.9.1 373 12/22/2023
0.9.0 287 10/1/2023
0.8.1 406 4/28/2023
0.8.0 351 4/20/2023
0.7.0 350 4/19/2023
0.6.0 382 3/29/2023
0.5.1 599 3/5/2023
0.5.0 482 3/2/2023
0.4.0 542 2/28/2023
0.3.1 441 2/27/2023
0.3.0 426 2/26/2023
0.2.0 457 2/19/2023

# v1.1.0
Version 1.1.0 introduces optional main commands with getopt-style subcommands.

## Changes
- Added optional main commands with command-specific long and short options
- Added selected-command state without changing the existing `GetNextOpt` contract
- Added opt-in culture-independent case-insensitive matching
- Added spelling suggestions and command-specific exceptions
- Added command-aware help generation and tests