goext

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2025 License: MIT Imports: 14 Imported by: 1

README

goext

Various small go extensions without dependencies.

Feel free to include this library or just copy the needed files or parts of them to your projects.

CommandRunner:

Cmd:

Env:

Files:

Maps:

Run:

  • TODO

Slices:

Strings:

TablePrinter:

Ternary:

CommandRunner

Allows running executable with arguments and various options.

The following options are available:

  • WorkingDirectory: Runs the command in the given working directory
  • OutputToConsole: Outputs stdout to the console
  • SkipPostProcessOutput: Does not post-process the output (remove newlines)
  • AdditionalEnv: Specify addional environment variables that should be set

Runners can be configured with setting the properties or by using With... methods in a fluent manner.

You can create and configure a runner and re-use it to run multiple commands.

There are also a few pre-defined runners available that can be used as follows:

// Default runner with no options
goext.CmdRunners.Default.Run("cmd", "arg1")
// Runner that outputs to the console
goext.CmdRunners.Console.Run("cmd", "arg1")

Usually, each argument is passed as its own value. If you have a string with all arguments, you can use the following so split the arguments:

goext.CmdRunners.Console.Run("cmd", goext.Cmd.SplitArgs("arg1 arg2")...)

Usage is as follows:

err := goext.NewCmdRunner().With<...>.Run("cmd", "arg1", "arg2")
Run

Runs the command with the given options.

err := goext.NewCmdRunner().Run("myapp", "arg1", "arg2")
RunGetOutput

Runs the command and returns the separate output from stdout and stderr.

stdout, stderr, err := goext.NewCmdRunner().RunGetOutput("myapp")
RunGetCombinedOutput

Runs the command and returns the output from stdout and stderr combined.

output, err := goext.NewCmdRunner().RunGetCombinedOutput("myapp")

Cmd

SplitArgs
args := goext.Cmd.SplitArgs("arg1 arg2")
ErrorExitCode
err := <execute cmd>
exitCode := goext.Cmd.ErrorExitCode(err)

Env

Exists

Checks if the given environment variable exists or not.

exists := goext.Env.Exists("MY_VAR")
ValueOrDefault

Returns the value if the environment variable exists or the default otherwise.

value, exists := goext.Env.ValueOrDefault("MY_VAR", "default")

Files

CopyFile

Copies a file copy from source to destination.

FileExists

Checks if a file exists (and it is not a directory).

WriteJsonToFile

Writes the given object into a file.

Maps

MapSortedByKey

Returns an iterator for the given map that yields the key-value pairs in sorted order.

myMap := map[int]string{1: "b", 0: "a", 3: "d", 2: "c"}
for key, value := range goext.MapSortedByKey(myMap) {
    fmt.Printf("%d->%s\n", key, value)
}
// Always prints
// 0->a
// 1->b
// 2->c
// 3->d

Run

A runner for go functions with various options.

Slices

SliceAppendIf

Appends the given values to a slice if the condition is fulfilled.

mySlice := []int{1, 2, 3}
mySlice = goext.SliceAppendIf(mySlice, myCondition, 4, 5)
SliceAppendIfFunc

Appends the given value if the condition is fulfilled. The value is lazily evaluated.

valueFunc := func() []int { return []int{4, 5} }
mySlice := []int{1, 2, 3}
mySlice = goext.SliceAppendIfFunc(mySlice, myCondition, valueFunc)
SliceAppendIfMissing

Appends the given elements if it is missing in the slice.

mySlice := []int{1, 2, 3}
mySlice = goext.SliceAppendIfMissing(mySlice, 3, 4)
SliceAppendIfMissingFunc

Appends the given elements if it is missing in the slice. The value is lazily evaluated.

valueFunc := func() []int { return []int{3, 4} }
mySlice := []int{1, 2, 3}
mySlice = goext.SliceAppendIfMissingFunc(mySlice, valueFunc)
SlicePrepend

Prepends the given elements to the given array.

mySlice := []int{1, 2, 3}
mySlice = goext.SlicePrepend(testSlice, 4, 5)
// [4, 5, 1, 2, 3]
SlicePrependIf

Prepends the given values to a slice if the condition is fulfilled.

mySlice := []int{1, 2, 3}
mySlice = goext.SlicePrependIf(mySlice, myCondition, 4, 5)
SlicePrependIfFunc

Prepends the given value if the condition is fulfilled. The value is lazily evaluated.

valueFunc := func() []int { return []int{4, 5} }
mySlice := []int{1, 2, 3}
mySlice = goext.SlicePrependIfFunc(mySlice, myCondition, valueFunc)

Strings

StringContainsAny

Checks if the string contains at least one of the substrings.

goext.StringContainsAny("Hello", "Hello", "World")
goext.StringContainsAny("World", []string{"Hello", "World"}...)
// Both return true
StringTrimAllPrefix

Trims all occurrences of the given prefix from the start of the string.

value := goext.StringTrimAllPrefix("xxxyyyxxx", "x")
StringTrimAllSuffix

Trims all occurrences of the given suffix from the end of the string.

value := goext.StringTrimAllSuffix("xxxyyyxxx", "x")
StringTrimNewlineSuffix

Trims all occurrences of newline characters from the end of the string.

value := goext.StringTrimNewlineSuffix("my-text\n\r\n")
StringSplitByNewLine

Splits the string by new line characters, supporting both "\n" and "\r\n".

lines := goext.StringSplitByNewLine("line1\r\nline2\nline3")

TablePrinter

Examples
tablePrinter := goext.NewTablePrinter(nil)
tablePrinter.SetHeaders("Id", "Name", "Age", "City")
tablePrinter.Columns[0].ValueAlignment = goext.TABLE_PRINTER_ALIGNMENT_RIGHT
tablePrinter.AddRows(
    []any{1, "Alice", "30", "New York"},
    []any{2, "Bob", "25", "Los Angeles"},
    []any{3, "Charlie", "35", "Chicago"},
)
tablePrinter.PrintStdout()
/* Prints:
┌──────┬───────────┬───────┬───────────────┐
│  Id  │  Name     │  Age  │  City         │
├──────┼───────────┼───────┼───────────────┤
│   1  │  Alice    │  30   │  New York     │
│   2  │  Bob      │  25   │  Los Angeles  │
│   3  │  Charlie  │  35   │  Chicago      │
└──────┴───────────┴───────┴───────────────┘
*/

Ternary

Ternary

A simple ternary function that returns one of two values based on a boolean condition.

value := goext.Ternary(myCondition, "Value A", "Value B")
TernaryFunc

Like Ternary but uses functions to lazily evaluate the values.

aFunc := func() string { return "Value A" }
bFunc := func() string { return "Value B"}
value := goext.TernaryFunc(myCondition, aFunc, bFunc)
TernaryFuncErr

Like TernaryFunc but returns an error as well.

aFunc := func() (string,error) { return "Value A", nil }
bFunc := func() (string,error) { return "Value B", nil }
value, err := goext.TernaryFuncErr(myCondition, aFunc, bFunc)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Cmd cmdNamespace = 0

Contains methods regarding commands.

View Source
var CmdRunners cmdRunners = cmdRunners{
	Default: NewCmdRunner(),
	Console: NewCmdRunner().WithConsoleOutput(),
}

Contains a few pre-configured CmdRunners for easy access.

View Source
var Env envNamespace = 0

Contains methods regarding environment variables.

View Source
var TablePrinterStyleAscii = &TablePrinterStyle{
	TopLeft:               "+",
	TopRight:              "+",
	TopIntersection:       "+",
	TopSpacer:             "-",
	MiddleLeft:            "|",
	MiddleRight:           "|",
	MiddleIntersection:    "|",
	SeparatorLeft:         "+",
	SeparatorRight:        "+",
	SeparatorIntersection: "+",
	SeparatorSpacer:       "-",
	BottomLeft:            "+",
	BottomRight:           "+╯",
	BottomIntersection:    "+",
	BottomSpacer:          "-",
}
View Source
var TablePrinterStyleDefault = &TablePrinterStyle{
	TopLeft:               "┌",
	TopRight:              "┐",
	TopIntersection:       "┬",
	TopSpacer:             "─",
	MiddleLeft:            "│",
	MiddleRight:           "│",
	MiddleIntersection:    "│",
	SeparatorLeft:         "├",
	SeparatorRight:        "┤",
	SeparatorIntersection: "┼",
	SeparatorSpacer:       "─",
	BottomLeft:            "└",
	BottomRight:           "┘",
	BottomIntersection:    "┴",
	BottomSpacer:          "─",
}
View Source
var TablePrinterStyleRounded = &TablePrinterStyle{
	TopLeft:               "╭",
	TopRight:              "╮",
	TopIntersection:       "┬",
	TopSpacer:             "─",
	MiddleLeft:            "│",
	MiddleRight:           "│",
	MiddleIntersection:    "│",
	SeparatorLeft:         "├",
	SeparatorRight:        "┤",
	SeparatorIntersection: "┼",
	SeparatorSpacer:       "─",
	BottomLeft:            "╰",
	BottomRight:           "╯",
	BottomIntersection:    "┴",
	BottomSpacer:          "─",
}

Functions

func CopyFile added in v0.6.0

func CopyFile(src string, dst string) (int64, error)

Copies a file copy from source to destination.

func FileExists added in v0.6.0

func FileExists(filePath string) (bool, error)

Checks if a file exists (and it is not a directory).

func MapSortedByKey

func MapSortedByKey[Map ~map[K]V, K cmp.Ordered, V any](m Map) iter.Seq2[K, V]

Returns an iterator for the given map that yields the key-value pairs in sorted order.

func RunInDirectory added in v0.4.0

func RunInDirectory(path string, f func() error) (err error)

func RunInDirectory1P added in v0.4.0

func RunInDirectory1P[P1 any](path string, f func() (P1, error)) (P1, error)

func RunInDirectory2P added in v0.4.0

func RunInDirectory2P[P1 any, P2 any](path string, f func() (P1, P2, error)) (P1, P2, error)

func RunInDirectory3P added in v0.4.0

func RunInDirectory3P[P1 any, P2 any, P3 any](path string, f func() (P1, P2, P3, error)) (P1, P2, P3, error)

func RunWithEnvs added in v0.4.0

func RunWithEnvs(envVariables map[string]string, f func() error) error

func RunWithEnvs1P added in v0.4.0

func RunWithEnvs1P[P1 any](envVariables map[string]string, f func() (P1, error)) (P1, error)

func RunWithEnvs2P added in v0.4.0

func RunWithEnvs2P[P1 any, P2 any](envVariables map[string]string, f func() (P1, P2, error)) (P1, P2, error)

func RunWithEnvs3P added in v0.4.0

func RunWithEnvs3P[P1 any, P2 any, P3 any](envVariables map[string]string, f func() (P1, P2, P3, error)) (P1, P2, P3, error)

func RunWithOptions added in v0.4.0

func RunWithOptions(f func() error, options ...RunOption) (err error)

Runs a given method with additional options.

func RunWithOptions1P added in v0.4.0

func RunWithOptions1P[P1 any](f func() (P1, error), options ...RunOption) (P1, error)

Runs a given method with returns one parameter with additional options.

func RunWithOptions2P added in v0.4.0

func RunWithOptions2P[P1 any, P2 any](f func() (P1, P2, error), options ...RunOption) (P1, P2, error)

Runs a given method with returns two parameters with additional options.

func RunWithOptions3P added in v0.4.0

func RunWithOptions3P[P1 any, P2 any, P3 any](f func() (P1, P2, P3, error), options ...RunOption) (P1, P2, P3, error)

Runs a given method with returns three parameters with additional options.

func SliceAppendIf

func SliceAppendIf[T any](slice []T, cond bool, values ...T) []T

Appends the given values to a slice if the condition is fulfilled.

func SliceAppendIfFunc

func SliceAppendIfFunc[T any](slice []T, cond bool, f func() []T) []T

Appends the given value if the condition is fulfilled. The value is lazily evaluated.

func SliceAppendIfMissing added in v0.8.0

func SliceAppendIfMissing[T comparable](slice []T, values ...T) []T

Appends the given elements if it is missing in the slice.

func SliceAppendIfMissingFunc added in v0.8.0

func SliceAppendIfMissingFunc[T comparable](slice []T, f func() []T) []T

Appends the given elements if it is missing in the slice. The value is lazily evaluated.

func SlicePrepend

func SlicePrepend[T any](slice []T, elems ...T) []T

Prepends the given elements to the given array.

func SlicePrependIf

func SlicePrependIf[T any](slice []T, cond bool, values ...T) []T

Prepends the given values to a slice if the condition is fulfilled.

func SlicePrependIfFunc

func SlicePrependIfFunc[T any](slice []T, cond bool, f func() []T) []T

Prepends the given value if the condition is fulfilled. The value is lazily evaluated.

func StringContainsAny

func StringContainsAny(s string, substrings ...string) bool

Checks if the string contains at least one of the substrings.

func StringSplitByNewLine added in v0.2.0

func StringSplitByNewLine(value string) []string

Splits the string by new line characters, supporting both "\n" and "\r\n".

func StringTrimAllPrefix added in v0.2.0

func StringTrimAllPrefix(s, prefix string) string

Trims all occurrences of the given prefix from the start of the string.

func StringTrimAllSuffix added in v0.2.0

func StringTrimAllSuffix(s, suffix string) string

Trims all occurrences of the given suffix from the end of the string.

func StringTrimNewlineSuffix added in v0.2.0

func StringTrimNewlineSuffix(v string) string

Trims all occurrences of newline characters from the end of the string.

func Ternary

func Ternary[T any](cond bool, vtrue, vfalse T) T

A simple ternary function that returns one of two values based on a boolean condition.

func TernaryFunc

func TernaryFunc[T any](cond bool, vtrue, vfalse func() T) T

Like Ternary but uses functions to lazily evaluate the values.

func TernaryFuncErr

func TernaryFuncErr[T any](cond bool, vtrue, vfalse func() (T, error)) (T, error)

Like TernaryFunc but returns an error as well.

func WriteJsonToFile added in v0.6.0

func WriteJsonToFile(object any, outputFilePath string, indented bool) error

Writes the given object into a file.

Types

type CmdRunner added in v0.3.0

type CmdRunner struct {
	WorkingDirectory      string
	OutputToConsole       bool
	SkipPostProcessOutput bool
	AdditionalEnv         map[string]string
}

The CmdRunner struct that holds the configuration for running commands.

func NewCmdRunner added in v0.3.0

func NewCmdRunner() *CmdRunner

Creates a new CmdRunner with the given options.

func (*CmdRunner) Clone added in v0.5.0

func (r *CmdRunner) Clone() *CmdRunner

Clones the CmdRunner with its current configuration.

func (*CmdRunner) Run added in v0.3.0

func (r *CmdRunner) Run(executable string, arguments ...string) error

Runs the command with the given options.

func (*CmdRunner) RunGetCombinedOutput added in v0.3.0

func (r *CmdRunner) RunGetCombinedOutput(executable string, arguments ...string) (string, error)

Runs the command and returns the output from stdout and stderr combined.

func (*CmdRunner) RunGetOutput added in v0.3.0

func (r *CmdRunner) RunGetOutput(executable string, arguments ...string) (string, string, error)

Runs the command and returns the separate output from stdout and stderr.

func (*CmdRunner) WithConsoleOutput added in v0.3.0

func (r *CmdRunner) WithConsoleOutput() *CmdRunner

Sets to output to console.

func (*CmdRunner) WithEnv added in v0.3.0

func (r *CmdRunner) WithEnv(key, value string) *CmdRunner

Adds an environment variable to the command.

func (*CmdRunner) WithSkipPostProcessOutput added in v0.3.0

func (r *CmdRunner) WithSkipPostProcessOutput() *CmdRunner

Sets to skip post-processing of output (trimming newlines).

func (*CmdRunner) WithWorkingDirectory added in v0.3.0

func (r *CmdRunner) WithWorkingDirectory(workingDirectory string) *CmdRunner

Sets the working directory for the command.

type RunOption added in v0.4.0

type RunOption interface {
	// contains filtered or unexported methods
}

An option that can be used to run which is applied before the run and reverted after.

func RunOptionInDirectory added in v0.4.0

func RunOptionInDirectory(path string) RunOption

Option that allows changing the working directory during a run.

func RunOptionWithEnvs added in v0.4.0

func RunOptionWithEnvs(envVariables map[string]string) RunOption

Option that allows setting/overriding environment variables during a run.

type TablePrinter

type TablePrinter struct {
	Options *TablePrinterOptions
	Columns []*TablePrinterColumn
	Rows    []*TablePrinterRow
}

func NewTablePrinter

func NewTablePrinter(options *TablePrinterOptions) *TablePrinter

Create a new TablePrinter with the given options or default options.

func (*TablePrinter) AddRows

func (tp *TablePrinter) AddRows(valueRows ...[]any)

Add rows to the TablePrinter with the given values.

func (*TablePrinter) Print

func (tp *TablePrinter) Print(writer io.Writer)

Print the table to the given writer.

func (*TablePrinter) PrintStdout

func (tp *TablePrinter) PrintStdout()

Print the table to stdout.

func (*TablePrinter) PrintToFile

func (tp *TablePrinter) PrintToFile(filePath string) error

Print the table to a file.

func (*TablePrinter) SetHeaders

func (tp *TablePrinter) SetHeaders(headers ...string)

Set the headers for the TablePrinter.

type TablePrinterAlignment

type TablePrinterAlignment int
const (
	TABLE_PRINTER_ALIGNMENT_LEFT TablePrinterAlignment = iota
	TABLE_PRINTER_ALIGNMENT_RIGHT
)

type TablePrinterColumn

type TablePrinterColumn struct {
	Header          string
	HeaderAlignment TablePrinterAlignment
	ValueAlignment  TablePrinterAlignment
	Hide            bool
	// contains filtered or unexported fields
}

type TablePrinterOptions

type TablePrinterOptions struct {
	Padding int
	Style   *TablePrinterStyle
}

type TablePrinterRow

type TablePrinterRow struct {
	Values []string
}

type TablePrinterStyle

type TablePrinterStyle struct {
	TopLeft               string
	TopRight              string
	TopIntersection       string
	TopSpacer             string
	MiddleLeft            string
	MiddleRight           string
	MiddleIntersection    string
	SeparatorLeft         string
	SeparatorRight        string
	SeparatorIntersection string
	SeparatorSpacer       string
	BottomLeft            string
	BottomRight           string
	BottomIntersection    string
	BottomSpacer          string
}

Jump to

Keyboard shortcuts

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