Coder Social home page Coder Social logo

joseluisq / cline Goto Github PK

View Code? Open in Web Editor NEW
3.0 3.0 0.0 109 KB

A fast and lightweight CLI package for Go without external dependencies.

Home Page: https://git.io/Cline

License: Apache License 2.0

Makefile 0.66% Go 99.34%
golang golang-package cli command-line-tool

cline's Introduction

CLIne devel codecov Go Report Card PkgGoDev

A fast and lightweight CLI package for Go without external dependencies.

WIP project under active development.

Features

  • No external dependencies more than few Go's stdlib ones.
  • Compact but concise API.
  • Global and command flags support.
  • bool, int, string and []string flag's data types.
  • Flag aliases and default values support.
  • Convenient contexts for function handlers (global and command flags)
  • Context built-in types conversion API for bool, int, string and []string flag values.
  • Convenient API to detect provided (passed) flags only with thier props.
  • Optional environment variable names for flags.
  • Automatic --help (-h) flag for global flags and commands.
  • Automatic --version (-v) flag with relevant info like app version, Go version, build datetime and OS/Arch.

Work in progress

  • POSIX-compliant flags feature is partial. Please see issue #3
  • Subcommands are not supported yet.

Usage

API definition example:

package main

import (
	"fmt"
	"os"

	cli "github.com/joseluisq/cline"
)

// App values passed at compile time for --version flag
// See "Makefile > build"
var (
	version     string = "devel"
	buildTime   string
	buildCommit string
)

func main() {
	app := cli.New()
	app.Name = "enve"
	app.Summary = "Run a program in a modified environment using .env files"
	app.Version = version
	app.BuildTime = buildTime
	app.BuildCommit = buildCommit
	// Global App flags
	app.Flags = []cli.Flag{
		cli.FlagString{
			Name:    "file",
			Summary: "Load environment variables from a file path",
			Value:   ".env",
			Aliases: []string{"f"},
		},
		cli.FlagBool{
			Name:    "verbose",
			Summary: "Enable more verbose info",
			Value:   false,
			Aliases: []string{"V"},
			EnvVar:  "ENV_VERBOSE",
		},
	}
	// App commands
	app.Commands = []cli.Cmd{
		{
			Name:    "info",
			Summary: "Show command information",
			Flags: []cli.Flag{
				cli.FlagInt{
					Name:    "trace",
					Summary: "Enable tracing mode",
					Value:   10,
					Aliases: []string{"t"},
				},
				cli.FlagBool{
					Name:    "detailed",
					Summary: "Enable info details",
					Value:   true,
					Aliases: []string{"d"},
				},
			},
			// Specific command handler for its flags
			Handler: func(ctx *cli.CmdContext) error {
				fmt.Printf("Cmd `%s` executed!\n", ctx.Cmd.Name)
				fmt.Printf("App Flag `file` opted: `%s`\n", ctx.AppContext.Flags.Any("file"))

				trace, err := ctx.Flags.Int("trace")
				if err != nil {
					return err
				}
				i, err := trace.Value()
				if err != nil {
					return err
				}
				fmt.Printf("Cmd Flag `trace` opted: `%d` (%T)\n", i, i)

				detailed, err := ctx.Flags.Bool("detailed")
				if err != nil {
					return err
				}
				d, err := detailed.Value()
				if err != nil {
					return err
				}
				fmt.Printf("Cmd Flag `detailed` opted: `%v` (%T)\n", d, d)

				fmt.Printf("Cmd Tail arguments: %#v\n", ctx.TailArgs)
				return nil
			},
		},
	}
	// App handler for flags
	app.Handler = func(ctx *cli.AppContext) error {
		fmt.Printf("App `%s` executed!\n", ctx.App.Name)
		fmt.Printf("App Tail arguments: %#v\n", ctx.TailArgs)

		if f, err := ctx.Flags.StringSlice("file"); err == nil {
			fmt.Printf("App Flag `file` opted: `%v`\n", f.Value())
		}

		if v, err := ctx.Flags.Bool("verbose"); err == nil {
			b, _ := v.Value()
			fmt.Printf("App Flag `verbose` opted: `%v`\n", b)
		}

		return nil
	}
	if err := app.Run(os.Args); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

Output example:

$ go run examples/main.go -h
# enve 0.0.0
# Run a program in a modified environment using .env files

# USAGE:
#    enve [OPTIONS] COMMAND
#
# OPTIONS:
#       -f --file      Load environment variables from a file path.
#                      Some new line description
#                      Another new line description. [default: .env]
#    -b,-z --int       Int value [default: 5]
#       -V --verbose   Enable more verbose info [default: true] [env: ENV_VERBOSE]
#       -h --help      Prints help information
#       -v --version   Prints version information
#
# COMMANDS:
#    info   Show command information
#
# Run 'enve COMMAND --help' for more information on a command

$ go run examples/main.go -v
# Version:       0.0.0
# Go version:    go1.16.2
# Built:         2021-03-28T20:03:04
# Commit:        1885ad1
# OS/Arch:       linux/amd64

More details on examples/main.go

Contributions

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in current work by you, as defined in the Apache-2.0 license, shall be dual licensed as described below, without any additional terms or conditions.

Feel free to send some Pull request or issue.

License

This work is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0).

© 2020-present Jose Quintana

cline's People

Contributors

joseluisq avatar

Stargazers

frankfanslc avatar  avatar Zhao Xiaohong avatar

Watchers

James Cloos avatar  avatar  avatar

cline's Issues

POSIX-compliant

Cline must be POSIX-compliant according to https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html

  • Arguments are options if they begin with a hyphen delimiter (‘-’).
  • Option names are single alphanumeric characters.
  • Certain options require an argument. For example, the ‘-o’ command of the ld command requires an argument—an output file name.
  • Options typically precede other non-option arguments.
  • The argument ‘--’ terminates all options; any following arguments are treated as non-option arguments, even if they begin with a hyphen.
  • A token consisting of a single hyphen character is interpreted as an ordinary non-option argument. By convention, it is used to specify input from or output to the standard input and output streams.
  • An option and its argument may or may not appear as separate tokens. (In other words, the whitespace separating them is optional.) Thus, ‘-o foo’ and ‘-ofoo’ are equivalent.
  • Multiple options may follow a hyphen delimiter in a single token if the options do not take arguments. Thus, ‘-abc’ is equivalent to ‘-a -b -c’.
  • Options may be supplied in any order, or appear multiple times. The interpretation is left up to the particular application program.
  • Long options consist of ‘--’ followed by a name made of alphanumeric characters and dashes. Option names are typically one to three words long, with hyphens to separate words. Users can abbreviate the option names as long as the abbreviations are unique.
  • To specify an argument for a long option, write ‘--name=value’. This syntax enables a long option to accept an argument that is itself optional.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.