gocore

package module
v0.0.0-...-6475e22 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2025 License: BSD-3-Clause Imports: 31 Imported by: 13

README

The GoCore Package

The gocore package provides core functions for Go language commands.

The functions provide

  • a command line framework
  • extensions to the Go flag package
  • help for command syntax
  • enhanced logging
  • sub-process spawner

The gocore package defines the following command line flags:

  • -version: to report the current version of the command
  • -cpuprofile: profile CPU performance of command
  • -memprofile: profile memory usage of command

Copyright © 2021-2023 The Gomon Project.

Documentation

Overview

Package gocore implements functionality used by commands. Functions support

  • a command line framework
  • extensions to the Go flag package
  • help for command syntax
  • enhanced logging

The gocore package defines the following command line flags:

  • -version: to report the current version of the command
  • -cpuprofile: profile CPU performance of command
  • -memprofile: profile memory usage of command

Index

Constants

View Source
const (
	// RFC3339Milli used for formatting timestamps.
	RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"
)

Variables

View Source
var (

	// loggingLevel maps requested LOG_LEVEL to index.
	LoggingLevel = func() LogLevel {
		switch strings.ToUpper(os.Getenv("LOG_LEVEL")) {
		case "TRACE":
			return LevelTrace
		case "DEBUG":
			return LevelDebug
		case "WARN":
			return LevelWarn
		case "ERROR":
			return LevelError
		case "FATAL":
			return LevelFatal
		}
		return LevelInfo
	}()

	// Log is the default log message formatter and writer.
	Log = func(msg LogMessage, level LogLevel) {
		if level >= LoggingLevel {
			if msg.E == nil && level > LevelInfo {
				level = LevelInfo
			}
			log.Printf("%s %-5s %s", time.Now().Format(RFC3339Milli), logLevels[level], msg.Error())
		}
	}
)
View Source
var (
	// Boottime gets the system boot time.
	Boottime = func() time.Time {
		f, err := os.Open("/proc/stat")
		if err != nil {
			Error("/proc/stat open", err).Err()
			return time.Time{}
		}
		defer f.Close()
		sc := bufio.NewScanner(f)
		for sc.Scan() {
			l := sc.Text()
			k, v, _ := strings.Cut(l, " ")
			switch k {
			case "btime":
				sec, err := strconv.Atoi(v)
				if err != nil {
					Error("/proc/stat btime", err).Err()
					return time.Time{}
				}
				return time.Unix(int64(sec), 0)
			}
		}

		Error("/proc/stat btime", sc.Err()).Err()
		return time.Time{}
	}()
)
View Source
var (
	// DarkAppearance indicates whether system appearance is "dark" or "light"
	DarkAppearance bool
)
View Source
var (
	// Flags defines and initializes the command line flags
	Flags = flags{
		FlagSet: flag.FlagSet{},

		CommandDescription:   "",
		ArgumentDescriptions: [][2]string{},
		// contains filtered or unexported fields
	}
)
View Source
var (
	// HostEndian enables byte order conversion between local and network integers.
	HostEndian = func() binary.ByteOrder {
		n := uint16(1)
		a := (*[2]byte)(unsafe.Pointer(&n))[:]
		b := []byte{0, 1}
		if bytes.Equal(a, b) {
			return binary.BigEndian
		}
		return binary.LittleEndian
	}()
)
View Source
var (

	// Version of module: version.major.minor-timestamp-commithash
	Version string
)

Functions

func CamelCase

func CamelCase(s string) string

CamelCase converts a snake_case name to CamelCase to follow Go naming conventions.

func Capitalize

func Capitalize(s string) string

Capitalize uppercases the leading character of a name.

func ChDir

func ChDir(dir string) (string, error)

ChDir is a convenience function for changing the current directory and reporting its canonical path. If changing the directory fails, ChDir returns the error and canonical path of the current directory.

func FdPath

func FdPath(fd int) (string, error)

FdPath gets the path for an open file descriptor.

func Format

func Format(name, tag string, val reflect.Value, fn Formatter) (ms []any)

Format recurses through a structures' fields to encode them using the Formatter.

func GoString

func GoString[C int8 | byte](char *C) string

GoStringN interprets a null terminated C char array as a GO string.

func GoStringN

func GoStringN[
	C int8 | byte,
	L int | uint | int8 | uint8 | int16 | uint16 | int32 | uint32 | int64 | uint64,
](char *C, l L) string

GoStringN interprets a length specified and possibly null terminated C char array as a GO string.

func Groupname

func Groupname(gid int) string

Groupname retrieves and caches group name for gid.

func Hostname

func Hostname(addr string) string

Hostname retrieves and caches host name for ip address.

func IsTerminal

func IsTerminal(f *os.File) bool

IsTerminal reports if a file handle is connected to the terminal.

func Main

func Main(main func(context.Context) error)

Main drives the show.

func Measures

func Measures(filename string) (map[string]string, error)

Measures reads a /proc filesystem file and produces a map of name:value pairs.

func Module

func Module(dir string) modval

Module retrieves and caches go module information.

func MountMap

func MountMap() (map[string]string, error)

MountMap builds a map of mount points to file systems.

func MsToTime

func MsToTime(ms uint64) time.Time

MsToTime converts Unix era milliseconds to Go time.Time.

func Ordered

func Ordered[K comparable, V any](m map[K]V, cmp func(a, b K) int) iter.Seq2[K, V]

Ordered walks a map, returning an ordered sequence of each map element's key and value by key, ordered with a comparison function.

func Seteuid

func Seteuid()

seteuid current process to file owner.

func Setuid

func Setuid()

setuid current process to user.

func SnakeCase

func SnakeCase(s string) string

SnakeCase converts a CamelCase name to snake_case to follow JSON and data base naming conventions.

func Spawn

func Spawn(ctx context.Context, cmdline []string) (*bufio.Scanner, error)

Spawn starts a command and returns a scanner for reading stdout.

func Subdir

func Subdir(base, targ string) (string, error)

Subdir acts like filepath.Rel() but returns an error if the target path is not on the base path.

func Uncapitalize

func Uncapitalize(s string) string

Uncapitalize lowercases the leading character of a name.

func Unsupported

func Unsupported() error

Unsupported reports that a specific OS does not support a function

func Username

func Username(uid int) string

Username retrieves and caches user name for uid.

Types

type Formatter

type Formatter func(name, tag string, val reflect.Value) any

Formatter function prototype for functions that encode values for the Format function.

type LogLevel

type LogLevel int

LogLevel indexes the literal log levels.

const (
	// enum of logging levels corresponding to log levels.
	LevelTrace LogLevel = iota - 2
	LevelDebug
	LevelInfo // default
	LevelWarn
	LevelError
	LevelFatal
)

type LogMessage

type LogMessage struct {
	Source string
	E      error
	File   string
	Line   int
	Detail map[string]string
}

LogMessage is custom logging error type.

func Error

func Error(source string, err error, details ...map[string]string) LogMessage

Error records the function source, error message, code location, and any details of initial error, preserving the initial error for percolation.

func (LogMessage) Debug

func (msg LogMessage) Debug()

Debug log debug message.

func (LogMessage) Err

func (msg LogMessage) Err()

Error log error message.

func (LogMessage) Error

func (msg LogMessage) Error() string

Error method to comply with error interface.

func (LogMessage) Info

func (msg LogMessage) Info()

Info log info message (default logging level).

func (LogMessage) Trace

func (msg LogMessage) Trace()

Trace log trace message.

func (LogMessage) Unwrap

func (msg LogMessage) Unwrap() error

Unwrap method to comply with error interface.

func (LogMessage) Warn

func (msg LogMessage) Warn()

Warn log warning message.

type Node

type Node = comparable

Node is the comparable type for each node of Tree.

type Options

type Options struct {
	List     []string
	Selected []string
}

Options is a command line flag type.

func (*Options) Set

func (o *Options) Set(text string) error

Set is a flag.Value interface method to enable Options as a command line flag.

func (Options) String

func (o Options) String() string

String is a flag.Value interface method to enable Options as a command line flag.

type Regexp

type Regexp struct {
	*regexp.Regexp
}

Regexp is a command line flag type.

func (*Regexp) Set

func (r *Regexp) Set(pattern string) (err error)

Set is a flag.Value interface method to enable Regexp as a command line flag.

func (Regexp) String

func (r Regexp) String() string

String is a flag.Value interface method to enable Regexp as a command line flag.

type Table

type Table[N Node, V Value[N]] map[N]V

Table provides an optional dictionary of values for the Nodes. If used, insert new Nodes here first to ensure uniqueness in Tree.

func (Table[N, V]) BuildTree

func (tb Table[N, V]) BuildTree() Tree[N]

BuildTree builds the tree.

func (Table[N, V]) Parent

func (tb Table[N, V]) Parent(node N) (N, V)

Parent returns the node and value for a parent node as determined by the current node's value.

type Tree

type Tree[N Node] map[N]Tree[N]

Tree defines a hierarchy of Nodes of comparable type.

func (Tree[N]) Add

func (tr Tree[N]) Add(nodes ...N)

Add adds new Nodes as a branch to the Tree.

func (Tree[N]) All

func (tr Tree[N]) All() iter.Seq2[int, N]

All walks the tree, returning a sequence of each node and its depth in the tree and descending through its subnodes.

func (Tree[N]) Ancestors

func (tr Tree[N]) Ancestors(node N) []N

Ancestors creates a slice of the ancestor nodes of the node.

func (Tree[N]) DepthTree

func (tr Tree[N]) DepthTree() int

DepthTree enables ordering of tree nodes depth first.

func (Tree[N]) Family

func (tr Tree[N]) Family(node N) Tree[N]

Family creates a tree of the selected node with its ancestors.

func (Tree[N]) FindTree

func (tr Tree[N]) FindTree(node N) Tree[N]

FindTree finds the subtree anchored by a specific node.

func (Tree[N]) Ordered

func (tr Tree[N]) Ordered(cmp func(a, b N) int) iter.Seq2[int, N]

Ordered walks the tree, ordering node values with a comparison function at each depth as it descends each node's subtree, reporting each node's depth and value in depth first order.

type ValidValue

type ValidValue[T ~string] map[T]int

ValidValue defines list of values that are valid for a type safe string.

func (ValidValue[T]) Define

func (vv ValidValue[T]) Define(values ...T) ValidValue[T]

Define initializes a ValidValue type with its valid values.

func (ValidValue[T]) Index

func (vv ValidValue[T]) Index(v T) int

Index returns the position of a value in the valid value list.

func (ValidValue[T]) IsValid

func (vv ValidValue[T]) IsValid(v T) bool

IsValid returns whether a value is valid.

func (ValidValue[T]) ValidValues

func (vv ValidValue[T]) ValidValues() []string

ValidValues returns an ordered list of valid values for the type.

type Value

type Value[N Node] interface {
	HasParent() bool
	Parent() N
}

Value defines the interface for a node's value to specify its parent node for building a tree.

Jump to

Keyboard shortcuts

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