Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

Cocona

> 开发工具
Open source

Micro-framework for .NET console application. Cocona makes it easy and fast to build console applications on .NET.

3.5K stars0 likes1 views
WebsiteGitHub

About

Micro-framework for .NET console application. Cocona makes it easy and fast to build console applications on .NET.

Micro-framework for .NET Core console application. Cocona makes it easy and fast to build console applications on .NET.

⏱ Create a console application with Cocona in seconds.

csharp
CoconaApp.Run((string? name, bool hey) =>
    Console.WriteLine($"{(hey ? "Hey" :"Hello")} {(name ?? "Guest")}!"));

Feature

  • Make it easy to build console applications on .NET.
    • ASP.NET Core-like Minimal API
    • public method as a command
    • Provides ASP.NET Core MVC-like development experience to console application development.
  • ✨ Command-line option semantics like UNIX tools standard. (getopt/getopt_long like options)
    • Your app can handle both -rf / and -r -f / :-)
    • Support single command and multiple commands style
      • myapp --foo --bar -n arg0 "arg1" (e.g. dir, cp, ls ...)
      • myapp server -m "Hello world!" (e.g. dotnet, git, kubectl ...)
  • ❓ Built-in help documentation support.
    • You want to see a help message; you type -h or --help.
    • Built-in similar commands suggestion
    • Shell command-line completion support for bash and zsh
  • Highly modulable/customizable CLI framework.
    • Cocona built on top of Microsoft.Extensions.* framework. Cocona natively supports Logging, DI, Configuration and ConsoleLifetime.
    • Don't you need Microsoft.Extensions.*? then you can use a lightweight version of Cocona (named Cocona.Lite).

You can find sample code for various features.

Table of contents

  • Installing
  • Requirements
  • Getting Started
  • Command-line handling basics
    • Command
    • Options
    • Arguments
    • Sub-commands
    • Option-like commands
  • Cocona in action
    • Parameter set
    • Exit code
    • Validation
    • Shutdown event handling
    • Command filter
    • Dependency Injection
    • Configuration
    • Logging
    • Shell command-line completion
  • Performance & Cocona.Lite
  • Advanced
    • Localization
    • Hide command from help
    • Help customization
    • CommandMethodForwardedTo attribute
    • IgnoreUnknownOptions attribute
    • GenericHost integration
  • Related projects
  • License

Installing

Install NuGet package from NuGet.org

bash
$ dotnet add package Cocona

# A lightweight version is also available if you prefer less dependency.
$ dotnet add package Cocona.Lite

Requirements

  • .NET 6 (Required to use Minimal API)
  • .NET 5
  • .NET Standard 2.0, 2.1

Getting Started

csharp
using Cocona;
CoconaApp.Run((string name) =>
{
    Console.WriteLine($"Hello {name}");
})
Class-based style (for .NET Standard / .NET 5)
csharp
using Cocona;
class Program
{
    static void Main(string[] args)
    {
        // Cocona parses command-line and executes a command.
        CoconaApp.Run<Program>(args);
    }

    // public method as a command ™
    public void Hello(string name)
    {
        Console.WriteLine($"Hello {name}");
    }
}

Try to run!

bash
$ dotnet run
Usage: ConsoleAppSample [--name <String>]

Options:
  --name <String>    (Required)
  -h, --help         Show help message
  --version          Show version

$ dotnet run -- --name Cocona
Hello Cocona

Extra: Publish the application as a single-file executable

If your application runs on .NET Core 3.0 or later, you can publish the app as a single-file executable. (see. What's new in .NET Core 3.0)

bash
PS> dotnet publish -r win-x64 -p:PublishSingleFile=true
PS> app.exe --name Cocona

$ dotnet publish -r linux-x64 -p:PublishSingleFile=true
$ ./app --name Cocona

Command-line handling basics

Command

Minimal API style

If your application has a single command, you can easily define and run it with CoconaApp.Run.

csharp
CoconaApp.Run((string name, int age) => { ... });

This is equivalent to the following code using the Minimal API Builder.

csharp
var builder = CoconaApp.CreateBuilder();
var app = builder.Build();

app.AddCommand((string name, int age) => { ... });

app.Run();

If you want your application to have more than one command, you can add named commands. See Sub commands for details.

csharp
var app = CoconaApp.Create(); // is a shorthand for `CoconaApp.CreateBuilder().Build()`

app.AddCommand("list", () => { ... });
app.AddCommand("add", () => { ... });
app.AddCommand("delete", () => { ... });

app.Run();

You can add (classic) Class-based style commands with the AddCommands<T> method.

csharp
app.AddCommands<MyCommand>();

Public method as a command (Class-based style)

By default, Cocona treats public methods as commands.

If an application has one public method, Cocona calls it on startup. If there are more than one, they are treated as sub-commands. (see also Sub commands)

csharp
// Treats a method name as a command name. (Below method is named `command`)
public void Command() { ... }

// Specify a command name using CommandAttribute.
[Command("commandname")]
public void Command() { ... }

// Cocona will ignore this method.
[Ignore]
public void Ignored() { ... }

If you want to specify a method as a command manually, set false to TreatPublicMethodsAsCommands option at startup. All command methods require CommandAttribute.

csharp
CoconaApp.Run<Program>(args, options =>
{
    // If the option value is `false`, All command methods require `CommandAttribute`.
    options.TreatPublicMethodsAsCommands = false;
});

Options

Cocona exposes method parameters as command-line options (also known as flags).

csharp
// This command accepts `--name <string>` and `--hey` options.
app.AddCommand((string name, bool hey) => { ... });
Class-based style (for .NET Standard / .NET 5)
csharp
// This command accepts `--name <string>` and `--hey` options.
public void Hello(string name, bool hey) { ... }

If the parameter of a method is defined as nullable, Cocona will treat them as non-mandatory option for a command. (That is, the parameters are treated as required option by default excepts boolean). If a parameter is boolean, it's assumed that false default value is specified.

csharp
// `--name` is non-mandatory option.
// If the user runs the application without this option, the parameter will be `null`.
app.AddCommand((string? name) => { ... });
Optional with default value (Class-based style)

If method parameters are optional argument, Cocona treats those as optional command options. (That is, the parameters are treated as required option by default excepts boolean). If a parameter is boolean, it's assumed that false default value is specified.

csharp
// `--name "default user"` is specified implicity.
public void Hello(string name = "default user") { ... }

Do you want to use short-name option -f instead of --force? You can specify short-name to an option using OptionAttribute.

csharp
// The command accepts `-f` or `--force` option.
// Cocona's command-line parser accepts getopt-like styles. See below.
// $ remove --force --recursive
// $ remove -r -f
// $ remove -rf
app.AddCommand(([Option('f')]bool force, [Option('r')]bool recursive) => { ... });
Class-based style (for .NET Standard / .NET 5))
csharp
// The command accepts `-f` or `--force` option.
// Cocona's command-line parser accepts getopt-like styles. See below.
// $ remove --force --recursive
// $ remove -r -f
// $ remove -rf
public void Remove([Option('f')]bool force, [Option('r')]bool recursive) { ... }

If a parameter is T[] or IEnumerable<T>, a command accepts one or more options by the same name.

csharp
// $ compile -I../path/to/foo.h -I/usr/include/bar.h -I/usr/include/baz.h nantoka.c
// include = new [] { "../path/to/foo.h", "/usr/include/bar.h", "/usr/include/baz.h" };
app.AddCommand(([Option('I')]string[] include, [Argument]string file) => { ... });
Class-based style (for .NET Standard / .NET 5))
csharp
// $ compile -I../path/to/foo.h -I/usr/include/bar.h -I/usr/include/baz.h nantoka.c
// include = new [] { "../path/to/foo.h", "/usr/include/bar.h", "/usr/include/baz.h" };
public void Compile([Option('I')]string[] include, [Argument]string file) { ... }

You can also specify a description for options that appear in the help.

csharp
app.AddCommand((
    [Option(Description = "Description of the option")] int value,
    [Argument(Description = "Description of the argument")]string arg
) => { ... });
Class-based style (for .NET Standard / .NET 5))
csharp
public void HasDescription([Option(Description = "Description of the option")] int value, [Argument(Description = "Description of the argument")]string arg) { ... }
Usage: CoconaSample.InAction.CommandOptions has-description [--value <Int32>] [--help] arg

Arguments:
  0: arg    Description of the argument (Required)

Options:
  --value <Int32>    Description of the option (Required)
  -h, --help         Show help message
  • See also: CoconaSample.InAction.CommandOptions

Arguments

Command-line arguments are defined as method parameters as same as options.

csharp
// ./app alice karen
app.AddCommand(([Argument]string from, [Argument]string to) => { ... });
Class-based style (for .NET Standard / .NET 5)
csharp
// ./app alice karen
public void Hello([Argument]string from, [Argument]string to) { ... }

You can define a parameter as T[]. It allows defining cp-like command which accepts many file paths and one destination path (cp file1 file2 file3 dest).

csharp
// ./copy file1 file2 file3 dest
app.AddCommand(([Argument]string[] src, [Argument]string dest) => { ... });
Class-based style (for .NET Standard / .NET 5)
csharp
// ./copy file1 file2 file3 dest
public void Copy([Argument]string[] src, [Argument]string dest) { ... }
  • See also: CoconaSample.InAction.ManyArguments

Sub-commands

You can add multiple commands with names and expose them as sub-commands. You can implement an application that has sub-commands similar to dotnet, git, kubectl etc...

csharp
var app = CoconaApp.Create();
app.AddCommand("hello", ([Argument]string name) => Console.WriteLine($"Hello {name}!"))
    .WithDescription("Say hello");
app.AddCommand("bye", ([Argument]string name) => Console.WriteLine($"Goodbye {name}!"))
    .WithDescription("Say goodbye");
app.Run();
Class-based style (for .NET Standard / .NET 5)

If a command type has more than one public method or [Command], those commands are exposed as sub-commands. You can implement an application that has sub-commands similar to dotnet, git, `kubect

Issues· 73 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#clicommand-lineconsolecsharp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具