• Stars
    star
    131
  • Rank 266,111 (Top 6 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created almost 5 years ago
  • Updated 13 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

POSIX-compliant command-line UI (CLI) parser and Hierarchical-configuration operations

cmdr

Go GitHub go.mod Go version GitHub tag (latest SemVer) GoDoc FOSSA Status go.dev Go Report Card codecov Mentioned in Awesome Go

Unstable v2: Working in progress, the main API might be stable till v2.1.0

cmdr is a POSIX-compliant, command-line argument parser library with Golang.

Since v2, our license moved to Apache 2.0.

ee99d078e2f7

See the image frames at #1.

Motivation

There are many dirty codes in the cmdr.v1 which cannot be refactored as well. It prompted we reimplment a new one as v2.

The passing winter, we did rewrite the cmdr.v2 to keep it clean and absorbed in parsing and dispatching. Some abilities were removed and relayouted to new modules. That's why the Option Store has been split as a standalone module hedzr/store1. A faster and colorful slog-like logger has been implemented freshly as hedzr/logg2. hedzr/evendeep3 provides a deep fully-functional object copy tool. It helps to deep copy some internal objects easily. It is also ready for you. hedzr/is4 is an environment detecting framework with many out-of-the-box detectors, such as is.InTesting and is.InDebugging.

Anyway, the whole supply chain painted:

graph BT
  hzis(hedzr/is)-->hzlogg(hedzr/logg/slog)
  hzis-->hzdiff(hedzr/evendeep)
  hzlogg-->hzdiff
  hzerrors(gopkg.in/hedzr/errors.v3)-->hzdiff
  hzerrors-->hzstore(hedzr/store)
  hzis-->hzstore(hedzr/store)
  hzlogg-->hzstore(hedzr/store)
  hzdiff-->hzstore(hedzr/store)
  hzlogg-->cmdr(hedzr/cmdr/v2)
  hzis-->cmdr
  hzlogg-->cmdr
  hzdiff-->cmdr
  hzstore-->cmdr

  1. The .netCore version Cmdr.Core is available now.
  2. A cxx version cmdr-cxx was released (Happy Spring Festival 2021).

Features

v2 is in earlier state but the baseline is stable:

  • Basic command-line arguments parser like POSIX getopt and go stdlib flag.

    • Short flag, single character or a string here to support golang CLI style

      • Compact flags if possible. Also the sticking value will be parsed. For example: -c1b23zv = -c 1 -b 23 -z -v
      • Hit info: -v -v -v = -v (hitCount == 3, hitTitle == 'v')
      • Optimized for slice: -a 1,2,3 -a 4 -a 5,6 => []int{1,2,3,4,5,6}
      • Value can be sticked or not. Valid forms: -c1, -c 1, -c=1 and quoted: -c"1", -c'1', -c="1", -c='1', etc.
      • ...
    • Long flags and aliases

    • Eventual subcommands: an OnAction handler can be attached.

    • Eventual subcommands and flags: PreActions, PostAction, OnMatching, OnMatched, ...,

    • Auto bind to environment variables, For instance: command line HELP=1 app = app --help.

    • Builtin commands and flags:

      • --help, -h
      • --version, -V
      • --verbose. -v
      • ...
    • Help Screen: auto generate and print

    • Smart suggestions when wrong cmd or flag parsed. Jaro-winkler distance is used.

  • Loosely parse subcmds and flags:

    • Subcommands and flags can be input in any order
    • Lookup a flag along with subcommands tree for resolving the duplicated flags
  • Can integrate with hedzr/store1

    • High-performance in-memory KV store for hierarchical data.
    • Extract data to user-spec type with auto-converting
    • Loadable external sources: environ, config files, consul, etcd, etc..
      • extensible codecs and providers for loading from data sources
  • Three kinds of config files are searched and loaded via loaders.NewConfigFileLoader():

    • Primary: main config, shipped with installable package.
    • Secondary: 2ndry config. Wrapped by reseller(s).
    • Alternative: user's local config, writeable. The runtime changeset will be written back to this file while app stopping.
  • TODO

    • Shell autocompletion
    • ...

More minor details need to be evaluated and reimplemented if it's still meaningful in v2.

History

v2 is staying in earlier state:

  • Latest: v2.0.3

    • split loaders as a standalone repo
    • split examples and tests to standalone
    • update deps
    • fix bugs
  • Full list: CHANGELOG

Guide

A simple cli-app can be:

package main

import (
	logz "github.com/hedzr/logg/slog"

	"github.com/hedzr/cmdr/v2"
	"github.com/hedzr/cmdr/v2/cli"
	"github.com/hedzr/cmdr/v2/loaders"
	"github.com/hedzr/cmdr/v2/pkg/dir"
	"github.com/hedzr/store"
)

func main() {
	app := prepareApp()

	// // simple run the parser of app and trigger the matched command's action
	// _ = app.Run(
	// 	cmdr.WithForceDefaultAction(false), // true for debug in developing time
	// )

	if err := app.Run(
		cmdr.WithStore(store.New()),
		cmdr.WithExternalLoaders(
			loaders.NewConfigFileLoader(),
			loaders.NewEnvVarLoader(),
		),
		cmdr.WithForceDefaultAction(true), // true for debug in developing time
	); err != nil {
		logz.Error("Application Error:", "err", err)
	}
}

func prepareApp() (app cli.App) {
	app = cmdr.New().
		Info("demo-app", "0.3.1").
		Author("hedzr")
	app.AddFlg(func(b cli.FlagBuilder) {
		b.Titles("no-default").
			Description("disable force default action").
			OnMatched(func(f *cli.Flag, position int, hitState *cli.MatchState) (err error) {
				app.Store().Set("app.force-default-action", false)
				return
			})
	})
	app.AddCmd(func(b cli.CommandBuilder) {
		b.Titles("jump").
			Description("jump command").
			Examples(`jump example`).
			Deprecated(`jump is a demo command`).
			Hidden(false)

		b.AddCmd(func(b cli.CommandBuilder) {
			b.Titles("to").
				Description("to command").
				Examples(``).
				Deprecated(`v0.1.1`).
				Hidden(false).
				OnAction(func(cmd *cli.Command, args []string) (err error) {
					app.Store().Set("app.demo.working", dir.GetCurrentDir())
					println()
					println(dir.GetCurrentDir())
					println()
					println(app.Store().Dump())
					return // handling command action here
				})
			b.AddFlg(func(b cli.FlagBuilder) {
				b.Default(false).
					Titles("full", "f").
					Description("full command").
					Build()
			})
		})
	})

	app.AddFlg(func(b cli.FlagBuilder) {
		b.Titles("dry-run", "n").
			Default(false).
			Description("run all but without committing")
	})

	app.Flg("wet-run", "w").
		Default(false).
		Description("run all but with committing").
		Build() // no matter even if you're adding the duplicated one.
	return
}

Thanks to JODL

Thanks to JetBrains for donating product licenses to help develop cmdr
jetbrains goland

License

Since v2, our license moved to Apache 2.0.

The v1 keeps under MIT itself.

FOSSA Status

Footnotes

  1. hedzr/store is a high-performance configure management library ↩ ↩2

  2. hedzr/logg provides a slog like and colorful logging library ↩

  3. hedzr/evendeep offers a customizable deepcopy tool to you. There are also deepequal, deepdiff tools in it. ↩

  4. hedzr/is is a basic environ detectors library ↩

More Repositories

1

android-file-chooser

a lightweight file/folder chooser or picker
Java
284
star
2

mirror-list

list of Chinese mainland mirrors
147
star
3

go-ringbuf

Lock-free MPMC Ring Buffer (Generic) for SMP, in golang. Some posts in chinese:
Go
63
star
4

docker-compose-file-format

Translation of docker-compose file format, ηΌ–ζŽ’θ―­ζ³•θ―‘ζ–‡ v3.8
26
star
5

cmdr-cxx

cmdr cxx version, a C++17 header-only command-line parser with hierarchical config data manager here
C++
17
star
6

consul-tags

A CLI tool to Update, add, remove the service tags at consul store.
Go
12
star
7

fsm-cxx

a finite state machine within c++17
C++
12
star
8

lb

concurrent load balancers, go lib,
Go
12
star
9

bash.sh

main entry template of your first bash script file
Shell
11
star
10

pxe-server-and-focal

files for [build-pxe-server-and-autoinstall-ubuntu-server]
Shell
10
star
11

awesome-tool

a command-line tool to retrieve the stars of all repos in an awesome-list
Go
10
star
12

progressbar

A task-based terminal progress bar in golang, with a python rich-like progressbar. Integrated more styles.
Go
8
star
13

ini-op

small command-line tool to read/write inifile. it's used by my `git-submodule-rm` script
Go
7
star
14

bgo

make go building easier: an efficient and extensible tool for go apps
Go
6
star
15

Cmdr.Core

Useful POSIX command line arguments parser for .Net. Hierarchical-configuration Store for app.
C#
5
star
16

errors

Nestable/wrappable golang errors library.
Go
5
star
17

evendeep

Per-field copying deeply, and comparing deeply abilities: deepcopy, deepdiff and more...
Go
5
star
18

design-patterns-cxx

exercises about design patterns, in c++17
C++
5
star
19

store

extensible, high-performance configuration management library, optimized for hierarchical data
Go
4
star
20

logex

an enhanced over logrus/zap. `logex` attaches the caller info to the logging output.
Go
4
star
21

Mdx.Core

loading mdx/mdd (MDict) file format with dotnetcore, legacy codes
C#
4
star
22

meijue-ui

an android kotlin extension library
Kotlin
4
star
23

undo-cxx

a c++17 undo/redo subsystem (linear or restricted non-linear)
CMake
4
star
24

ticker-cxx

c++17 timing and trigger abilities
C++
4
star
25

go-faker

faked records generator. A CLI app for generating the faked records such as names, addresses, and phone numbers.
Go
4
star
26

hio

Enhanced Http Client for Dart/Flutter.
Dart
3
star
27

bash-framework

minimal starting of bash programming
Shell
3
star
28

hedzr.github.io

main gh io pages and sites
HTML
3
star
29

rate

rate limit library in golang
Go
3
star
30

go-socketlib

A simple, fast approach to implement your communication protocol.
Go
3
star
31

log

Minimal logging interface without other dependencies, basics common codes: dir,exec,detects,pheripheral,...
Go
2
star
32

cmdr-http2

a http2 server with `cmdr` full daemon supports and graceful shutdown.
Go
2
star
33

pools

golang connection pool, task pool, and jobs scheduler, ...
Go
2
star
34

hicc

hi, cc! hicc is a c++ template class library to provide some basic data structures and algorithms
C++
2
star
35

zag-common

Java
2
star
36

zag-servers

prototype of microservice system / ζœεŠ‘ζ²»η†ε’Œη°εΊ¦ε‘εΈƒη³»η»Ÿη ”ε‘εŽŸεž‹
Java
2
star
37

ansible-k8s

maintain k8s ha cluster via ansible
Jinja
2
star
38

cmdr-addons

helpers for go `cmdr`
Go
2
star
39

study-cmake

the demo project for cmake-hello posts
CMake
2
star
40

zsh-extras

personal terminal initial files
Shell
2
star
41

cmdr-docs

documentation for hedzr/cmdr (SIP)
Shell
2
star
42

docker-basics

basic docker images of mine
Makefile
1
star
43

sql-xx-core-demo

part of mysql 5.x sql parser
C++
1
star
44

kvl

simple golang kvstore abstract layer
Go
1
star
45

sphinx-study

a notebook for studying sphinx documenter
JavaScript
1
star
46

cmdr-examples

The example apps for go `cmdr` project
Go
1
star
47

rules

1
star
48

deb-build-tutor

stuffs about building a deb file
Shell
1
star
49

list.dos

list, a DOS text file browser by Vernon D. Buerg
Assembly
1
star
50

kcxt

kotlin context-awareness library for android libraries or applications
Kotlin
1
star
51

bsd3-1

1
star
52

sphinx-builder

extending official sphinx docker image with usesful plugins
Dockerfile
1
star
53

is

go lib to provide a set of minimal environ container and detectors
Go
1
star
54

logg

colored logger with log/slog like api
Go
1
star