omnicli

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2024 License: MIT Imports: 7 Imported by: 0

README

omnicli (sdk-go)

Go SDK for building Omni commands.

Overview

omnicli is a Go package that provides functionality to help build commands that will be executed by Omni. It offers various utilities and helpers that make it easier to work with Omni's features from within Go.

Installation

go get github.com/omnicli/sdk-go

Features

Argument Parsing

The SDK can read omni-parsed arguments from environment variables into Go structs:

package main

import (
	"log"

	omnicli "github.com/omnicli/sdk-go"
)

//go:generate omni-metagen-go -struct=Config -output=dist/my-command.metadata.yaml

type Config struct {
	// Fields are automatically mapped to kebab-case CLI arguments
	InputFile string   // maps to --input-file
	Verbose   bool     // maps to --verbose
	LogFile   *string  // maps to --log-file, optional
	Workers   []string // maps to --workers (array)

	// Use tags for custom names or to skip fields
	DBHost   string `omniarg:"db_host"` // custom name
	Internal string `omniarg:"-"`       // skip this field
}

func main() {
	var cfg Config
	_, err := omnicli.ParseArgs(&cfg)
	if err != nil {
		log.Fatalf("Failed to parse args: %v", err)
	}

	if cfg.Verbose {
		log.Println("Verbose mode enabled")
	}
	if cfg.InputFile != "" {
		log.Printf("Processing file: %s", cfg.InputFile)
	}
}

The resulting arguments can be accessed either through the populated struct or through the returned Args object, which provides type-safe getters for all values.

Integration with omni

The argument parser of omni needs to be enabled for your command. This can be done as part of the metadata of your command, which can either be provided as a separate file:

your-repo
└── commands
    ├── your-command.go
    ├── your-command.sh
    └── your-command.metadata.yaml
# your-command.metadata.yaml
argparser: true

Or as part of your command file wrapper header:

#!/usr/bin/env bash
#
# argparser: true
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
go run "${DIR}"/your-command.go "$@"
Metadata Generation

The SDK provides a code generation tool omni-metagen-go that can be used to generate metadata files for your commands. This tool will generate the metadata in YAML format based on the struct you provide. You will still need to indicate the name of the struct and the location of the output file (which should be in the same directory as your command, and named <command>.metadata.yaml).

You can install the tool by running:

go install github.com/omnicli/sdk-go/cmd/omni-metagen-go@latest

Or by using GitHub releases in omni:

up:
  - github-releases:
      omnicli/sdk-go: latest

The example above shows how to setup the metadata generation in your Go code. You can then call go generate ./... to generate the metadata file.

Development

To set up for development:

# Clone the repository
omni clone https://github.com/omnicli/sdk-go.git
# Install dependencies
omni up
# Run tests
omni test

Requirements

  • Go 1.18 or higher (for generics support)
  • No additional dependencies required

Documentation

Overview

Package omnicli provides the Go SDK for building Omni commands.

This package offers various utilities and helpers that make it easier to work with Omni's features from within Go. Currently, it focuses on argument parsing, but future versions will include additional functionality for working with other Omni features.

Argument Parsing

The primary feature currently available is the ability to parse Omni CLI arguments from environment variables into Go structs. The package supports various types including strings, booleans, integers, and floats, both as single values and arrays.

Example usage:

type Config struct {
    // Fields are automatically mapped to kebab-case CLI arguments
    InputFile string    // maps to --input-file
    LogFile   *string   // maps to --log-file, optional
    Workers   []string  // maps to --workers (array)

    // Use tags for custom names or to skip fields
    DBHost    string    `omni:"db_host"`  // custom name
    Internal  string    `omni:"-"`        // skip this field
}

func main() {
    var cfg Config
    args, err := omnicli.ParseArgs(&cfg)
    if err != nil {
        log.Fatal(err)
    }
}

Field Naming

By default, struct field names are converted from CamelCase to kebab-case for matching CLI arguments. For example:

  • InputFile -> input_file
  • LogFile -> log_file
  • DBHost -> db_host
  • OOMScore -> oom_score
  • SuperHTTPServer -> super_http_server

Custom names can be specified using the `omni` struct tag:

type Config struct {
    Host string `omni:"db_replica"` // maps to --db-replica
}

Fields can be excluded from parsing using the `-` tag value:

type Config struct {
    Internal string `omni:"-"` // will be skipped
}

Optional Values

Optional values should be declared as pointers. These will be nil when not set:

type Config struct {
    LogFile *string // nil when --log-file is not provided
    Workers *int    // nil when --workers is not provided
}

Array Values

Array values are supported for all basic types:

type Config struct {
    Hosts []string  // --hosts value1 value2 value3
    Ports []int     // --ports 8080 8081 8082
}

For the latest documentation and updates, visit: https://github.com/omnicli/sdk-go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ArgListMissingError

type ArgListMissingError struct{}

ArgListMissingError is returned when the OMNI_ARG_LIST environment variable is missing.

func (*ArgListMissingError) Error

func (e *ArgListMissingError) Error() string

type ArgTypeMissingError added in v0.2.0

type ArgTypeMissingError struct {
	// contains filtered or unexported fields
}

ArgTypeMissingError is returned when the OMNI_ARG_<argname>_TYPE environment variable is missing.

func (*ArgTypeMissingError) Error added in v0.2.0

func (e *ArgTypeMissingError) Error() string

type Args

type Args struct {
	// contains filtered or unexported fields
}

Args represents the parsed arguments with type-specific storage. Each map stores pointers to values, where nil indicates a declared but unset value.

func NewArgs

func NewArgs() *Args

NewArgs creates a new Args instance with initialized maps. This is typically not called directly, as ParseArgs will create and return an Args instance.

func ParseArgs

func ParseArgs(targets ...interface{}) (*Args, error)

ParseArgs reads omni arguments from environment variables and optionally fills provided structs. If target structs are provided, it will attempt to fill each one before returning.

Example:

var config Config
var flags Flags
args, err := ParseArgs(&config, &flags)

func (*Args) Fill

func (a *Args) Fill(v interface{}, prefix ...string) error

Fill populates a struct with values from the parsed arguments. The struct fields are matched with argument names based on their name or 'omniarg' tag. Field names are converted to lowercase for matching. It returns an error if any field cannot be filled or if types don't match.

func (*Args) FillAll

func (a *Args) FillAll(targets ...interface{}) error

FillAll attempts to fill multiple target structs. It stops and returns an error on the first failure.

func (*Args) GetAllArgs

func (a *Args) GetAllArgs() map[string]interface{}

GetAllArgs returns all declared arguments

func (*Args) GetBool

func (a *Args) GetBool(name string) (bool, bool)

GetBool returns a bool value and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetBoolGroups added in v0.2.0

func (a *Args) GetBoolGroups(name string) ([][]bool, bool)

GetBoolGroups returns a slice of slices of bool values and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetBoolSlice

func (a *Args) GetBoolSlice(name string) ([]bool, bool)

GetBoolSlice returns a slice of bool values and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetFloat

func (a *Args) GetFloat(name string) (float64, bool)

GetFloat returns a float value and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetFloatGroups added in v0.2.0

func (a *Args) GetFloatGroups(name string) ([][]float64, bool)

GetFloatGroups returns a slice of slices of float values and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetFloatSlice

func (a *Args) GetFloatSlice(name string) ([]float64, bool)

GetFloatSlice returns a slice of float values and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetInt

func (a *Args) GetInt(name string) (int, bool)

GetInt returns an int value and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetIntGroups added in v0.2.0

func (a *Args) GetIntGroups(name string) ([][]int, bool)

GetIntGroups returns a slice of slices of int values and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetIntSlice

func (a *Args) GetIntSlice(name string) ([]int, bool)

GetIntSlice returns a slice of int values and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetString

func (a *Args) GetString(name string) (string, bool)

GetString returns a string value and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetStringGroups added in v0.2.0

func (a *Args) GetStringGroups(name string) ([][]string, bool)

GetStringGroups returns a slice of slices of string values and whether it exists. The boolean return value indicates whether the argument exists and is set.

func (*Args) GetStringSlice

func (a *Args) GetStringSlice(name string) ([]string, bool)

GetStringSlice returns a slice of string values and whether it exists. The boolean return value indicates whether the argument exists and is set.

type InvalidBooleanValueError

type InvalidBooleanValueError struct {
	// contains filtered or unexported fields
}

InvalidBooleanValueError is returned when a boolean value cannot be parsed. Only "true" and "false" (case insensitive) are valid boolean values.

func (*InvalidBooleanValueError) Error

func (e *InvalidBooleanValueError) Error() string

type InvalidFloatValueError

type InvalidFloatValueError struct {
	// contains filtered or unexported fields
}

InvalidFloatValueError is returned when a float value cannot be parsed.

func (*InvalidFloatValueError) Error

func (e *InvalidFloatValueError) Error() string

type InvalidIntegerValueError

type InvalidIntegerValueError struct {
	// contains filtered or unexported fields
}

InvalidIntegerValueError is returned when an integer value cannot be parsed.

func (*InvalidIntegerValueError) Error

func (e *InvalidIntegerValueError) Error() string

type InvalidTypeStringError added in v0.2.0

type InvalidTypeStringError struct {
	// contains filtered or unexported fields
}

InvalidTypeStringError is returned when the OMNI_ARG_<argname>_TYPE environment variable is not one of the supported types.

func (*InvalidTypeStringError) Error added in v0.2.0

func (e *InvalidTypeStringError) Error() string

type TypeMismatchError

type TypeMismatchError struct {
	// contains filtered or unexported fields
}

TypeMismatchError is returned when an argument's type doesn't match the struct field type. This can happen when the declared type in environment variables doesn't match the Go struct field type.

func (*TypeMismatchError) Error

func (e *TypeMismatchError) Error() string

Directories

Path Synopsis
cmd
omni-metagen-go command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL