util

package
v2.0.14 Latest Latest
Warning

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

Go to latest
Published: May 24, 2025 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Utility functions (inspired by Kotlin) for slices.

Index

Constants

View Source
const MAX_HISTORY = 30
View Source
const MatchAnyRemainingArgs = "MatchCommandWithAnyRemainingArgs"

Can be used use as last value of [TestExecutor.fakeResponses] [ExecuteResponse.Args]

Variables

View Source
var CurrentVersion string
View Source
var StableVersion string

Functions

func AddToHistory added in v2.0.13

func AddToHistory(history []string, newHistoryItem string) []string

Add a most recently used item to history.

func Execute added in v2.0.13

func Execute(options ExecuteOptions, programName string, args ...string) (string, error)

Executes a shell program with arguments.

func ExecuteOrDie added in v2.0.13

func ExecuteOrDie(options ExecuteOptions, programName string, args ...string) string

Executes a shell program with arguments. Panics if there is an error.

func FilterSlice

func FilterSlice[V any](slice []V, f func(V) bool) []V

Returns a slice containing only elements matching the given predicate.

func FirstOriginMainCommit

func FirstOriginMainCommit(branchName string) string

Returns most recent commit of the given branch that is on origin/main.

func Fprint added in v2.0.13

func Fprint(w io.Writer, a ...any)

print or dies.

func Fprintln added in v2.0.13

func Fprintln(w io.Writer, a ...any)

println or dies.

func GetCurrentBranchName

func GetCurrentBranchName() string

Returns current branch name.

func GetLocalHasBranchOrDie added in v2.0.13

func GetLocalHasBranchOrDie(branchName string) bool

func GetLoggedInUsername added in v2.0.13

func GetLoggedInUsername() string

func GetMainBranchForHelp

func GetMainBranchForHelp() string

Returns name of main branch, or "main" if cannot be determined. For use by CLI help.

func GetMainBranchOrDie

func GetMainBranchOrDie() string

Returns name of main branch, or panics if cannot be determined.

func GetRepoName added in v2.0.13

func GetRepoName() string

func GetRepoNameWithOwner added in v2.0.13

func GetRepoNameWithOwner() string

Returns "repository-owner/repository-name".

func GetUsername

func GetUsername() string

func MapSlice

func MapSlice[V, R any](slice []V, f func(V) R) []R

Returns a slice containing the results of applying the given transform function to each element in the original array.

func PopStash

func PopStash(popStash bool)

func ReadHistory added in v2.0.13

func ReadHistory(appConfig AppConfig, historyFilename string) []string

history items are returned as: [0] least recent [last element] most recent

func RemoteHasBranch

func RemoteHasBranch(branchName string) bool

Returns whether branchName is on remote.

func RequireMainBranch

func RequireMainBranch()

func RequireNotEmptyString added in v2.0.13

func RequireNotEmptyString(s string)

func SetDefaultSleep

func SetDefaultSleep(newSleep func(d time.Duration))

Override the default sleep. For use by tests.

func SetGlobalExecutor added in v2.0.13

func SetGlobalExecutor(executor Executor)

Sets the executor that Execute will use.

func SetHistory added in v2.0.13

func SetHistory(appConfig AppConfig, historyFileName string, history []string)

Add a most recently used item to history.

func Sleep

func Sleep(d time.Duration)

Sleep function that can be overridden for testing. Default is time.Sleep

func Stash

func Stash(forName string) bool

Types

type AppConfig added in v2.0.13

type AppConfig struct {
	Io            StdIo
	AppExecutable string         // Path of this executable.
	Exit          func(code int) // Call os.Exit with the given code, or panic during unit tests.
	UserCacheDir  string         // os.UserCacheDir or a dir specific for each test in unit tests.
}

Config to help with unit testing the app. For example, it allows testing code paths that would otherwise call os.Exit().

type AsyncAppConfig added in v2.0.13

type AsyncAppConfig struct {
	App AppConfig
	// Method to defer to when running code async.
	// Will exit app after logging message if panic was called.
	GracefulRecover func()
}

type DefaultExecutor added in v2.0.13

type DefaultExecutor struct{}

Default implementation of Executor.

func (DefaultExecutor) Execute added in v2.0.13

func (defaultExecutor DefaultExecutor) Execute(options ExecuteOptions, programName string, args ...string) (string, error)

Implementation of Execute that uses exec.Command.

type ExecuteOptions added in v2.0.13

type ExecuteOptions struct {
	// What to use for input and output. Overriding input is useful for "git apply"
	// If output is not set then output is returned from Execute.
	// Any nil In/Err/Out values are ignored.
	Io StdIo
	// For example "MY_VAR=some_value"
	EnvironmentVariables []string
}

Options for [ExecuteWithOptions].

type ExecutedResponse added in v2.0.13

type ExecutedResponse struct {
	Out         string   // Out to return.
	Err         error    // error to return.
	ProgramName string   // Program name to match or that was used.
	Args        []string // Arguments that were used.
	Faked       bool     // Whether this response was faked.
}

Response that was executed or will be faked.

type Executor added in v2.0.13

type Executor interface {
	Execute(options ExecuteOptions, programName string, args ...string) (string, error)
}

Provides a simple way to execute shell commands. Allows swapping in a TestExecutor via Dependency Injection during tests.

type GitRollbackManager

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

func (*GitRollbackManager) Clear

func (rollbackManager *GitRollbackManager) Clear()

func (*GitRollbackManager) CreatedBranch

func (rollbackManager *GitRollbackManager) CreatedBranch(branchName string)

func (*GitRollbackManager) Restore

func (rollbackManager *GitRollbackManager) Restore(err any)

func (*GitRollbackManager) SaveState

func (rollbackManager *GitRollbackManager) SaveState()

type PrettyHandler

type PrettyHandler struct {
	slog.Handler // delegate all Handler methods to this object, except Handle which is overridden.
	// contains filtered or unexported fields
}

Handler for slog that uses diffdrent ANSI colors for each level (DEBUG, INFO, etc.).

Modified from https://betterstack.com/community/guides/logging/logging-in-go/

func NewPrettyHandler

func NewPrettyHandler(
	out io.Writer,
	opts slog.HandlerOptions,
) *PrettyHandler

Create a new PrettyHandler.

func (*PrettyHandler) Handle

func (h *PrettyHandler) Handle(ctx context.Context, r slog.Record) error

Print a log record.

func (*PrettyHandler) SetOut added in v2.0.13

func (h *PrettyHandler) SetOut(out io.Writer)

type StdIo added in v2.0.13

type StdIo struct {
	Out io.Writer
	Err io.Writer
	In  io.Reader
}

Allows unit testing the use of standard i/o.

type TestExecutor added in v2.0.13

type TestExecutor struct {
	Responses []ExecutedResponse
	// contains filtered or unexported fields
}

Fake Executor for testing.

func (*TestExecutor) Execute added in v2.0.13

func (t *TestExecutor) Execute(options ExecuteOptions, programName string, args ...string) (string, error)

Checks [TestExecutor.fakeResponses] for any match before calling DefaultExecutor.Execute.

func (*TestExecutor) SetResponse added in v2.0.13

func (t *TestExecutor) SetResponse(out string, err error, fakeProgramName string, fakeArgs ...string)

Adds a response to [TestExecutor.fakeResponses]. If [fakeArgs] ends with MatchAnyRemainingArgs, then the last argument is treated as a wildcard for any remaining args. Response are checked in the reverse order that they are added (in other words, the most recent response that was added is checked first)

func (*TestExecutor) SetResponseFunc added in v2.0.13

func (t *TestExecutor) SetResponseFunc(out string, err error, isMatch func(programName string, args ...string) bool)

Adds a response to [TestExecutor.fakeResponses].

Jump to

Keyboard shortcuts

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