utils

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2022 License: MIT Imports: 36 Imported by: 6

Documentation

Overview

Package utils provides some utility functions for internal usage.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Chinese
	GB2312  = simplifiedchinese.HZGB2312
	GB18030 = simplifiedchinese.GB18030
	GBK     = simplifiedchinese.GBK
	Big5    = traditionalchinese.Big5
	// Korean
	EUCKR = korean.EUCKR
	// Japanese
	EUCJP     = japanese.EUCJP
	ISO2022JP = japanese.ISO2022JP
	ShiftJIS  = japanese.ShiftJIS
	// Unicode
	UTF8             = unicode.UTF8
	UTF8BOM          = unicode.UTF16(unicode.BigEndian, unicode.UseBOM)
	UCS2BigEndian    = unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM)
	UCS2LittleEndian = unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM)
)
View Source
var (
	ErrEOF              = errors.New("EOF")
	ErrUnexpectedEOF    = errors.New("unexpected EOF")
	ErrNoProgress       = errors.New("multiple Read calls return no data or error")
	ErrSrcPathInvalid   = errors.New("srcPath is not a valid directory path")
	ErrDstPathInvalid   = errors.New("destPath is not a valid directory path")
	ErrSrcSameAsDst     = errors.New("destPath must be different from srcPath")
	ErrChanWriteTimeout = errors.New("write chan time out")
	ErrChanReadTimeout  = errors.New("read chan time out")
	ErrChanOptCanceled  = errors.New("chan operation canceled")
	ErrNotFound         = errors.New("404")
)
View Source
var (
	ANSI_CYAN    = "\x1b[36;1m"
	ANSI_RESET   = "\x1b[0m"
	ANSI_DEFAULT = "\x1b[39;1m"
	ANSI_BLUE    = "\x1b[34;1m"
	ANSI_BLACK   = "\x1b[30;1m"
	ANSI_RED     = "\x1b[31;1m"
	ANSI_GREEN   = "\x1b[32;1m"
	ANSI_YELLOW  = "\x1b[33;1m"
	ANSI_WHITE   = "\x1b[37;1m"
	ANSI_MAGENTA = "\x1b[35;1m"
)
View Source
var (
	// DefaultTrimChars are the characters which are stripped by Trim* functions in default.
	DefaultTrimChars = string([]byte{
		'\t',
		'\v',
		'\n',
		'\r',
		'\f',
		' ',
		0x00,
		0x85,
		0xA0,
	})
)
View Source
var Ord = func(char byte) int {
	return int(char)
}

ord use char as parameter, rerturn ascii number

View Source
var PBTheme = map[string]progressbar.Option{
	"=>": progressbar.OptionSetTheme(progressbar.Theme{
		Saucer:        "[green]=[reset]",
		SaucerHead:    "[green]>[reset]",
		SaucerPadding: " ",
		BarStart:      "[",
		BarEnd:        "]",
	}),
	"█": progressbar.OptionSetTheme(progressbar.Theme{
		Saucer:        "[green]█[reset]",
		SaucerHead:    "[green] [reset]",
		SaucerPadding: " ",
		BarStart:      "|",
		BarEnd:        "|",
	}),
}

Functions

func BytesDecode

func BytesDecode(coding encoding.Encoding, s []byte) ([]byte, string, error)

func BytesToHex

func BytesToHex(src []byte) []byte

Covert bytes to hex bytes, aim to make []byte{0x5B, 0x47, 0x4F, 0x5D}) ==> []byte("5b474f5d")

func BytesToNumber

func BytesToNumber[T any](nbytes []byte, bigEndian ...bool) (data T)

T can be bool, int8/16/32/64, uint8/16/32/64, float32/64 T also could be slice of type bool/int8~64, uint8~64, float32~64

func CaseFoldIn

func CaseFoldIn(target string, str_array []string) bool

CaseFoldIn check if str_array contains target case insensitively, return true if contains, otherwise false.

func CaseIn

func CaseIn(target string, str_array []string) bool

CaseIn check if str_array contains target case sensitively, return true if contains, otherwise false.

func CharsetDecode

func CharsetDecode(coding encoding.Encoding, src []byte) []byte

func CharsetEncode

func CharsetEncode(coding encoding.Encoding, src []byte) []byte

func ChdirToPos

func ChdirToPos(p ...string) (err error)

Chdir to the real application exist path

func CopyDir

func CopyDir(srcPath, desPath string) error

Only the contents of the source directory are recursively copied to the destination path, source directory itself not copied. Returns error if source/destination path does not exist. And srcPath must be different from desPath.

func CopyFile

func CopyFile(src, des string) (written int64, err error)

func CopyToNewDir

func CopyToNewDir(srcPath, desPath string) error

desPath is not exist

func CreateFile

func CreateFile(path string, data string, mode fs.FileMode) error

func Cwd

func Cwd(child ...string) string

func DeleteFiles

func DeleteFiles(path string, regexpr string)

func DeletePath

func DeletePath(path string) error

Delete the directory

func DeleteThingsInDir

func DeleteThingsInDir(targetDir string) error

Delete all files in the directory, left an empty directory(targetDir)

func DetermineDecode

func DetermineDecode(s []byte, contentType ...string) ([]byte, string, error)

Probe the bytes encoding and try to convert to UTF-8

func EqualFoldWithoutChars

func EqualFoldWithoutChars(s1, s2 string) bool

EqualFoldWithoutChars checks string `s1` and `s2` equal case-insensitively, with/without chars '-'/'_'/'.'/' '.

func Error

func Error(layer int, format string, args ...interface{})

func ErrorWithoutHeader

func ErrorWithoutHeader(format string, args ...interface{})

func Exec

func Exec(name string, args ...string) error

func ExitIfError

func ExitIfError(err error, fn ...any) error

CheckIfError should be used to naively panics if an error is not nil. Eg: utils.ExitIfError(errTest, log.Warningf, "%s %s", "warning", "message")

Example
package main

import (
	"errors"

	"github.com/lovelacelee/clsgo/v1/log"
	"github.com/lovelacelee/clsgo/v1/utils"
)

var errMessage = "ok"
var errTest = errors.New(errMessage)

func main() {
	utils.ExitIfError(errTest, log.Infof, "%s %s", "ERROR", "message")
}
Output:

func ExitIfErrorWithoutHeader

func ExitIfErrorWithoutHeader(err error, fn ...any) error
Example
package main

import (
	"errors"

	"github.com/lovelacelee/clsgo/v1/utils"
)

var errMessage = "ok"
var errTest = errors.New(errMessage)

func main() {
	utils.ExitIfErrorWithoutHeader(errTest)
}
Output:

func FileIsExisted

func FileIsExisted(filename string) bool

func FormatCmdKey

func FormatCmdKey(s string) string

FormatCmdKey formats string `s` as command key using uniformed format.

func FormatEnvKey

func FormatEnvKey(s string) string

FormatEnvKey formats string `s` as environment key using uniformed format.

func GetCurrentAbPath

func GetCurrentAbPath() string

Get current project's absolute path

func HexDump

func HexDump(src []byte, show ...func(fmt string, args ...any))

func HexString

func HexString(src []byte) string

func HexToBytes

func HexToBytes(src []byte) []byte

BytesToHex BytesToHex, aim to make []byte("5b474f5d")) ==> []byte{0x5B, 0x47, 0x4F, 0x5D}

func HexToString

func HexToString(src []byte) string

func HomePath

func HomePath() string

func IfError

func IfError(err error, fn ...any) error

Only output in terminal in Error message, Eg: utils.IfError(errTest, log.Errorf, "%s %s", "error", "error message")

func IfErrorWithoutHeader

func IfErrorWithoutHeader(err error, fn ...any) error

func Impt

func Impt(layer int, format string, args ...interface{})

func ImptWithoutHeader

func ImptWithoutHeader(format string, args ...interface{})

func Info

func Info(layer int, format string, args ...interface{})

func InfoIfError

func InfoIfError(err error, fn ...any) error

Only output in terminal in [INFO] message, Eg: utils.InfoIfError(errTest, log.Infof, "%s %s", "warning", "message")

Example
package main

import (
	"errors"

	"github.com/lovelacelee/clsgo/v1/log"
	"github.com/lovelacelee/clsgo/v1/utils"
)

var errMessage = "ok"
var errTest = errors.New(errMessage)

func main() {
	utils.InfoIfErrorWithoutHeader(errTest, log.Green, "%s %s", "INFO", "message")
	utils.InfoIfError(errTest, log.Infof, "%s %s", "INFO", "message")
}
Output:

func InfoIfErrorWithoutHeader

func InfoIfErrorWithoutHeader(err error, fn ...any) error

func InfoWithoutHeader

func InfoWithoutHeader(format string, args ...interface{})

func IsArray

func IsArray(value interface{}) bool

IsArray checks whether given value is array/slice. Note that it uses reflect internally implementing this feature.

func IsDir

func IsDir(name string) bool

func IsEmpty

func IsEmpty(value interface{}) bool

IsEmpty checks whether given `value` empty. It returns true if `value` is in: 0, nil, false, "", len(slice/map/chan) == 0, or else it returns false.

func IsFloat

func IsFloat(value interface{}) bool

IsFloat checks whether `value` is type of float.

func IsInt

func IsInt(value interface{}) bool

IsInt checks whether `value` is type of int.

func IsLetter

func IsLetter(b byte) bool

IsLetter checks whether the given byte b is a letter.

func IsLetterLower

func IsLetterLower(b byte) bool

IsLetterLower checks whether the given byte b is in lower case.

func IsLetterUpper

func IsLetterUpper(b byte) bool

IsLetterUpper checks whether the given byte b is in upper case.

func IsMap

func IsMap(value interface{}) bool

IsMap checks whether `value` is type of map.

func IsNil

func IsNil(value interface{}, traceSource ...bool) bool

IsNil checks whether given `value` is nil, especially for interface{} type value. Parameter `traceSource` is used for tracing to the source variable if given `value` is type of pinter that also points to a pointer. It returns nil if the source is nil when `traceSource` is true. Note that it might use reflect feature which affects performance a little.

func IsNumeric

func IsNumeric(s string) bool

IsNumeric checks whether the given string s is numeric. Note that float string like "123.456" is also numeric.

func IsSlice

func IsSlice(value interface{}) bool

IsSlice checks whether `value` is type of slice.

func IsStruct

func IsStruct(value interface{}) bool

IsStruct checks whether `value` is type of struct.

func IsUint

func IsUint(value interface{}) bool

IsUint checks whether `value` is type of uint.

func ListDir

func ListDir(dirPth string, suffix ...string) (dirs []string, files []string, err error)

Return all files and dirs in [dirPath], optional matching suffix, sub directories ignored

func ListToMapByKey

func ListToMapByKey(list []map[string]interface{}, key string) map[string]interface{}

ListToMapByKey converts `list` to a map[string]interface{} of which key is specified by `key`. Note that the item value may be type of slice.

func MakeDir

func MakeDir(path string, perm fs.FileMode, isfile ...bool) error

Create directory: The path parameter can be a directory or a file. If it is a file path, it will be truncated by the Dir function

func MapContainsPossibleKey

func MapContainsPossibleKey(data map[string]interface{}, key string) bool

MapContainsPossibleKey checks if the given `key` is contained in given map `data`. It checks the key ignoring cases and symbols.

Note that this function might be of low performance.

func MapPossibleItemByKey

func MapPossibleItemByKey(data map[string]interface{}, key string) (foundKey string, foundValue interface{})

MapPossibleItemByKey tries to find the possible key-value pair for given key ignoring cases and symbols.

Note that this function might be of low performance.

func MoveFile

func MoveFile(src, des string)

func NumberToBytes

func NumberToBytes[T any](n T, bigEndian ...bool) []byte

T can be bool, int8/16/32/64, uint8/16/32/64, float32/64 T also could be slice of type bool/int8~64, uint8~64, float32~64

func NumberToString

func NumberToString[T any](n T) string

func Param

func Param[T any](p []T, def T) T

func PatchClean

func PatchClean(p string) string

func PathFix

func PathFix(p string) string

func PathJoin

func PathJoin(elem ...string) string

func PathReplace

func PathReplace(path string, from string, to string) string

func ProgressBar

func ProgressBar(max int64, spin int, theme string, descPrefix ...string) *progressbar.ProgressBar

If max == -1, enable spinner progress bar, theme if one of PBTheme key

func ReadChanWithTimeout

func ReadChanWithTimeout[T any](ctx context.Context, c <-chan T, timeouts ...time.Duration) (T, error)

func RemoveSymbols

func RemoveSymbols(s string) string

RemoveSymbols removes all symbols from string and lefts only numbers and letters.

func ReplaceByMap

func ReplaceByMap(origin string, replaces map[string]string) string

ReplaceByMap returns a copy of `origin`, which is replaced by a map in unordered way, case-sensitively.

func RunIn

func RunIn(dir string, c string, args ...string) error

func RunInDir

func RunInDir(dir string, cmd *exec.Cmd) (err error)

cmd := exec.Command("git", "push", remote, "--tags", "--force") utils.RunInDir(w.Filesystem.Root(), cmd)

func SessionId

func SessionId(length ...int) string

length must > 0

func SetupExitNotify

func SetupExitNotify(done chan os.Signal)

Set up channel on which to send signal notifications. We must use a buffered channel or risk missing the signal if we're not ready to receive when the signal is sent.

Example
package main

import (
	"os"
	"testing"
	"time"

	"github.com/gogf/gf/v2/test/gtest"
	"github.com/lovelacelee/clsgo/v1/utils"
)

func main() {
	gtest.C(&testing.T{}, func(t *gtest.T) {
		exit := make(chan os.Signal, 1)
		utils.SetupExitNotify(exit)
		go func(x chan os.Signal) {
			time.Sleep(time.Second * 2)
			x <- os.Interrupt
		}(exit)
		e := <-exit
		t.Assert(e, os.Interrupt)
	})
}
Output:

func SplitAndTrim

func SplitAndTrim(str, delimiter string, characterMask ...string) []string

SplitAndTrim splits string `str` by a string `delimiter` to an array, and calls Trim to every element of this array. It ignores the elements which are empty after Trim.

func StringConvert

func StringConvert(from string, to string, src string) (string, error)

Wrapper for gcharset of goframe

func StringToHex

func StringToHex(s string) []byte

func StripSlashes

func StripSlashes(str string) string

StripSlashes un-quotes a quoted string by AddSlashes.

func TailToHead

func TailToHead(a []any) []any

func TempPath

func TempPath(p string) string

func Trim

func Trim(str string, characterMask ...string) string

Trim strips whitespace (or other characters) from the beginning and end of a string. The optional parameter `characterMask` specifies the additional stripped characters.

func UUID

func UUID() string

func UUIDV1

func UUIDV1() string

Time based and error ignored, not safe way

func UcFirst

func UcFirst(s string) string

UcFirst returns a copy of the string s with the first letter mapped to its upper case.

func ValueToInterface

func ValueToInterface(v reflect.Value) (value interface{}, ok bool)

ValueToInterface converts reflect value to its interface type.

func WalkDir

func WalkDir(dirPth string, suffix ...string) (dirs []string, files []string, err error)

Get all files in the specified directory and all subdirectories, matching suffix filtering.

func Warn

func Warn(layer int, format string, args ...interface{})

func WarnIfError

func WarnIfError(err error, fn ...any) error

Only output in terminal in [WARN] message, Eg: utils.WarnIfError(errTest, log.Warningf, "%s %s", "warning", "message")

Example
package main

import (
	"errors"

	"github.com/lovelacelee/clsgo/v1/log"
	"github.com/lovelacelee/clsgo/v1/utils"
)

var errMessage = "ok"
var errTest = errors.New(errMessage)

func main() {
	utils.WarnIfError(errTest)
	utils.WarnIfError(errTest, log.Warningf, "%s %s", "warning", "message")

}
Output:

func WarnIfErrorWithoutHeader

func WarnIfErrorWithoutHeader(err error, fn ...any) error

func WarnWithoutHeader

func WarnWithoutHeader(format string, args ...interface{})

func WriteChanWithTimeout

func WriteChanWithTimeout[T any](ctx context.Context, c chan T, data T, timeouts ...time.Duration) error

General Chan write function

Types

type Loggerf

type Loggerf = func(f string, v ...any)

Type of package log functions

type OriginTypeAndKindOutput

type OriginTypeAndKindOutput struct {
	InputType  reflect.Type
	InputKind  reflect.Kind
	OriginType reflect.Type
	OriginKind reflect.Kind
}

func OriginTypeAndKind

func OriginTypeAndKind(value interface{}) (out OriginTypeAndKindOutput)

OriginTypeAndKind retrieves and returns the original reflect type and kind.

type OriginValueAndKindOutput

type OriginValueAndKindOutput struct {
	InputValue  reflect.Value
	InputKind   reflect.Kind
	OriginValue reflect.Value
	OriginKind  reflect.Kind
}

func OriginValueAndKind

func OriginValueAndKind(value interface{}) (out OriginValueAndKindOutput)

OriginValueAndKind retrieves and returns the original reflect value and kind.

Jump to

Keyboard shortcuts

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