gocore

package module
v0.0.0-...-b820cfb Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2024 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 (
	// Host identifies the local host.
	Host, _ = os.Hostname()

	// Platform identifies the local OS.
	Platform = runtime.GOOS + "_" + runtime.GOARCH

	Uname = func() Utsname {
		var utsname unix.Utsname
		if err := unix.Uname(&utsname); err == nil {
			return Utsname{
				Sysname:  C.GoString((*C.char)(unsafe.Pointer(&utsname.Sysname[0]))),
				Nodename: C.GoString((*C.char)(unsafe.Pointer(&utsname.Nodename[0]))),
				Release:  C.GoString((*C.char)(unsafe.Pointer(&utsname.Release[0]))),
				Version:  C.GoString((*C.char)(unsafe.Pointer(&utsname.Version[0]))),
				Machine:  C.GoString((*C.char)(unsafe.Pointer(&utsname.Machine[0]))),
			}
		}
		return Utsname{}
	}()

	// executable identifies the full command path.
	Executable, _ = os.Executable()

	// Version of module: version.major.minor-timestamp-commithash
	Version string
)
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
	}()
)

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 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 Comparator

type Comparator interface{ ~int | ~string }

Comparator is a value returned by the Order function of a Table for sorting.

type Display

type Display[N Node, V any] func(int, N, Table[N, V])

Display shows the value of a Node at particular depth in Tree.

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 interface{ ~int | ~string }

Node is the comparable type for each node of Tree.

type Order

type Order[N Node, C Comparator, V any] func(N, Table[N, V]) C

Order distinguishes similar Node values for sorting.

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 any] map[N]V

Table refers to the data corresponding the nodes of a tree.

type Tree

type Tree[N Node, C Comparator, V any] map[N]Tree[N, C, V]

Tree defines a hierarchy of Nodes of comparable type.

func (Tree[N, C, V]) Add

func (tr Tree[N, C, V]) Add(nodes ...N)

Add inserts a node into a tree.

func (Tree[N, C, V]) FindTree

func (tr Tree[N, C, V]) FindTree(node N) Tree[N, C, V]

FindTree finds the subtree anchored by a specific node.

func (Tree[N, C, V]) Flatten

func (tr Tree[N, C, V]) Flatten(tbl Table[N, V], order Order[N, C, V]) []N

Flatten walks the tree to build an ordered slice of the nodes.

func (Tree[N, C, V]) Traverse

func (tr Tree[N, C, V]) Traverse(depth int, tbl Table[N, V], order Order[N, C, V], display Display[N, V])

Traverse walks the tree and invokes function fn for each node.

type Utsname

type Utsname struct {
	Sysname  string
	Nodename string
	Release  string
	Version  string
	Machine  string
}

Utsname contains Go format system uname

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.

Jump to

Keyboard shortcuts

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