util

package
v2.6.12 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2024 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package util provides utility functions for the application.

Index

Constants

View Source
const (
	KB = 1 << (10 * (iota + 1))
	MB
	GB
	TB
	PB
	EB
	ZB
	YB
)
View Source
const CCT = "m" // Color Code Terminator
View Source
const CSI = ESC + "[" // Control Sequence Introducer
View Source
const ESC = "\x1b" // Begin ANSI sequence
View Source
const EnvPrefix = "GITHUB_REPO_"

Prefix for relevant environment variables.

View Source
const MUP = CSI + "1A" // Move cursor 1 line up
View Source
const ProcessAlreadyRunning = "gr is already running (pid: %d). Either kill the process or wait for it to terminate."

Message when process with given ID is already running.

View Source
const Verbose envVariable = "VERBOSE"

Verbose env variable.

Variables

View Source
var Logger = func() *logrus.Logger {
	l := logrus.New()
	l.SetLevel(logrus.WarnLevel)
	c := Console()
	l.SetOutput(c.Stdout())
	l.SetFormatter(&logrus.JSONFormatter{
		PrettyPrint: true,
	})

	supererrors.RegisterCallback(func(err error) {
		c := Console()
		l.SetOutput(c.Stderr())

		if l.Level >= logrus.DebugLevel {
			err = tracerr.Wrap(err)

			var frames []string
			for _, frame := range err.(tracerr.Error).StackTrace() {
				switch ctx := frame.String(); {

				case
					strings.Contains(ctx, "supererrors.Except"),
					strings.Contains(ctx, "runtime.main()"),
					strings.Contains(ctx, "runtime.goexit()"):

					continue

				default:
					frames = append(frames, frame.String())

				}
			}

			l.WithField("stack", frames).Fatalln(err)
		}

		l.SetFormatter(&logrus.TextFormatter{
			DisableTimestamp:       true,
			DisableLevelTruncation: true,
		})
		l.Fatalln(err)
	})

	return l
}()

App logger (default format JSON).

Functions

func AcquireProcessIDLock

func AcquireProcessIDLock() interface{ Unlock() }

Record process ID and store it into the PID file. If process is already running, return corresponding message and exit.

func Chdir

func Chdir(path string) interface{ Popd() }

Change current working directory.

func Console

func Console() *consoleTerminal

Access point for terminal information.

func GetExecutablePath

func GetExecutablePath() string

Get path of the executable that started current gr process.

func GetHostnameFromPath

func GetHostnameFromPath(path string) string

Extract hostname from path.

func GetIdealConcurrency

func GetIdealConcurrency() uint

Get ideal number of workers for current CPU.

func Getenv

func Getenv(key envVariable) string

Retrieve environment variable.

func GetenvBool

func GetenvBool(key envVariable) bool

Retrieve environment variable of boolean type.

func IntToSizeBytes

func IntToSizeBytes(s int, unit int64, precision int) string

Format integer as byte size in kMGTPE[B] unit.

func ListFilesByExtension

func ListFilesByExtension(ext string, depth int) []string

List files in current working directory matching given extension (extension has to start with a dot).

func NewColoredYAMLEncoder

func NewColoredYAMLEncoder(w io.Writer, opts ...yaml.EncodeOption) *coloredYAMLEncoder

NewColoredYAMLEncoder creates new colorful YAML encoder for given writer.

func PathExists

func PathExists(path string) bool

Check if path exists.

func PathSanitize

func PathSanitize(paths ...*string)

Format path to UNIX style path, strip volume name if default.

func PreventInterrupt

func PreventInterrupt() interface{ Stop() }

Dispatch watcher.

func PrintlnAndExit

func PrintlnAndExit(format string, a ...any)

Print to Stdout and exit.

func StripPathPrefix

func StripPathPrefix(path string, keepParents uint) string

StripPathPrefix strips prefix from path given a number of parent directories to keep.

func UncolorizeReader

func UncolorizeReader(r io.Reader) (io.Reader, error)

UncolorizeReader is reserved for future use to uncolorize content of a reader.

Types

type PatternList

type PatternList []string

PatternList is a list of regular expressions.

func (PatternList) GlobMatch

func (l PatternList) GlobMatch(target string) bool

GlobMatch checks if target matches any of the globs in the list.

func (PatternList) RegexMatch

func (l PatternList) RegexMatch(target string, timeout time.Duration) bool

RegexMatch checks if target matches any of the regular expressions in the list.

type Progressbar

type Progressbar struct {
	*progressbar.ProgressBar
	// contains filtered or unexported fields
}

Custom implementation of progressbar.

func NewProgressbar

func NewProgressbar(m int, options ...ProgressbarOption) *Progressbar

Create new progressbar with default settings.

func (*Progressbar) Add

func (p *Progressbar) Add(i int) *Progressbar

Increase progressbar counter by i.

func (*Progressbar) ChangeMax

func (p *Progressbar) ChangeMax(max int) *Progressbar

Change max value of progressbar.

func (*Progressbar) Clear

func (p *Progressbar) Clear() *Progressbar

Clear state of progressbar.

func (*Progressbar) Describe

func (p *Progressbar) Describe(format string, a ...any) *Progressbar

Set description.

func (*Progressbar) Inc

func (p *Progressbar) Inc() *Progressbar

Increase state by one.

type ProgressbarOption

type ProgressbarOption = progressbar.Option

Export option

type TablePrinter

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

Table printer prints text in padded, tabular form.

func NewTablePrinter

func NewTablePrinter() *TablePrinter

Create new table printer.

func (*TablePrinter) AddRowField

func (t *TablePrinter) AddRowField(field string, colors ...color.Attribute) *TablePrinter

Add record.

func (*TablePrinter) Align

func (t *TablePrinter) Align() *TablePrinter

Align records to match the maximum column width and prevent index errors.

func (*TablePrinter) EndRow

func (t *TablePrinter) EndRow() *TablePrinter

End row (new line).

func (*TablePrinter) Print

func (t *TablePrinter) Print()

Print to Stdout.

func (*TablePrinter) SetOutputToStdErr

func (t *TablePrinter) SetOutputToStdErr(isStdErr bool) *TablePrinter

Switch between Stdout and Stderr.

func (*TablePrinter) Sort

func (t *TablePrinter) Sort() *TablePrinter

Sort records.

func (*TablePrinter) Sprint

func (t *TablePrinter) Sprint() string

Print through a buffer to deliver rendered string.

Jump to

Keyboard shortcuts

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