helper

package module
v1.1.6 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2023 License: MIT Imports: 11 Imported by: 11

README

go-helper Paypal donate

Collections of Golang helper functions.

Table Of Content
Features
File Description
common.go Debug flag
crypto.go Crypto function
debug.go Debug functions
err.go Basic error type
file.go File/directory functions
gitCmd.go Git functions
myArray.go A simple generic array type
myCmd.go exec.Command shell wrapper
report.go report/log functions auto detect and apply json marshal indent
string.go string/array functions
common.go
  • var Debug bool = false
  • var DebugReport bool = false
  • var Errs ErrsType
  • var Warns Warnings
  • var NIL_SPRINT string = fmt.Sprint(nil)
  • var NIL_JSON string
  • func init()
crypto.go
  • func BoxSealAnonymous(base64PublicKey, msg *string) *string
debug.go
  • func DebugEnv() bool
  • func DebugLog(msg ...interface{})
  • func ErrCheck(e error)
err.go
  • type Err string
  • type ErrsType struct
  • func (self Err) Error() string
  • func (self *Err) String() string
  • func (self *Err) StringP() *string
file.go
  • func CurrentPath() *string
  • func CurrentDirBase() *string
  • func FullPath(workPathP *string) *string
  • func FullPathStr(workPath string) *string
  • func IsRegularFile(workPath string) bool
  • func IsDir(workPath string) bool
  • func SameDir(path1, path2 string) bool
  • func FileHasExt(name, ext string) bool
  • func FileRemoveExt(filename string) string
  • func FileInDir(dir, filename string) string
  • func FileSimplifyName(filename string) string
gitCmd.go
  • func Git(workPathP *string, optionsP *[]string) *MyCmd
  • func GitClone(workPathP *string, optionsP *[]string) *MyCmd
  • func GitExecExist() bool
  • func GitExecPath() string
  • func GitInit(workPathP *string) *MyCmd
  • func GitBranchCurrent(workPathP *string) *MyCmd
  • func GitPull(workPathP *string, optionsP *[]string) *MyCmd
  • func GitPush(workPathP *string, optionsP *[]string) *MyCmd
  • func GitRemote(workPathP *string, v bool) *[]string
  • func GitRemoteAdd(workPathP *string, name string, git string) *MyCmd
  • func GitRemoteExist(workPathP *string, name string) bool
  • func GitRemoteRemove(workPathP *string, name string) *MyCmd
  • func GitRemoteRemoveAll(workPathP *string)
  • func GitRoot(workPathP *string) string
  • func GitRootSubmodule(workPathP *string) string
myArray.go
  • type myArray[T any] []T
  • func (self *myArray[T]) Empty() bool
  • func (self *myArray[T]) NotEmpty() bool
  • func (self *myArray[T]) Clear()
  • func (self *myArray[T]) Add(t T) *myArray[T]
myCmd.go
  • type MyCmd struct
  • func MyCmdRun(cmdName string, argsP *[]string, workPathP *string) *MyCmd
  • func MyCmdRunWg(cmdName string, argsP *[]string, workPathP *string, title *string, wgP *sync.WaitGroup, output bool) *MyCmd
  • func MyCmdInit(name string, argsP *[]string, workPathP *string) *MyCmd
  • func (self *MyCmd) Init(name string, argsP *[]string, workPathP *string) *MyCmd
  • func (self *MyCmd) Reset() *MyCmd
  • func (self *MyCmd) Run() error
  • func (self *MyCmd) ExitCode() int
report.go
  • type ReportT struct
  • func Report(data any, title string, skipEmpty bool, singleLine bool)
  • func ReportDebug(data any, title string, skipEmpty bool, singleLine bool)
  • func ReportSp(data any, title string, skipEmpty bool, singleLine bool) *string
  • func ReportSpDebug(data any, title string, skipEmpty bool, singleLine bool) *string
  • func ReportStatus(data bool, title string, singleLine bool)
  • func ReportStatusSp(data bool, title string, singleLine bool) *string
  • func ReportNew(data any, title string, skipEmpty bool, singleLine bool) *ReportT
  • func (self *ReportT) String() string
  • func (self *ReportT) StringDebug() string
  • func (self *ReportT) StringP() *string
  • func (self *ReportT) StringPDebug() *string
string.go
  • func BoolString(b bool) string
  • func BoolStatus(b bool) string
  • func BoolYesNo(b bool) string
  • func StrArrayPtrContain(aP *[]string, sP *string) bool
  • func StrArrayPtrRemoveEmpty(saP *[]string) *[]string
  • func StrArrayPtrPrintln(saP *[]string)
  • func StrArrayPtrPrintlnSp(saP *[]string) *string
  • func StrPtrToArrayPtr(sP *string) *[]string
  • func JsonIndentSp(baP *[]byte, endLn bool) *string
  • func numToStr(data any) *string
  • func AnyToJsonMarshalIndentSp(data any, endLn bool) *string
  • func AnyToJsonMarshalSp(data any, endLn bool) *string
  • func StrPtrToJsonIndentSp(strP *string, endLn bool) *string
  • func StrToJsonIndentSp(str string, endLn bool) *string
Doc
Usage
import	"github.com/J-Siu/go-helper"

func main() {
	helper.Debug = true
	helper.DebugLog("debug msg")
}
Test
cd test
# All
go test
# Individual
go test file_test.go
go test gitCmd_test.go
go test myCmd_test.go
go test report_test.go
Used By Project
Repository
Contributors
Change Log
  • 0.0.1
    • Initial Commit
  • 0.9.0
    • Function update
  • 0.9.1
    • Fix git command args
  • v0.9.1
    • Add prefix v for version number
  • v0.9.2
    • Fix MyCmdRunWg() missing wgP.Done()
  • v0.9.3
    • ReportTStringP():
      • fix using wrong var when handling *[]byte
      • add []byte case
  • v0.9.4
    • Report support SingleLine mode
  • v0.9.5
    • Fix ReportT.SpringP() output
  • v0.9.6
    • Fix ReportT.SpringP() skip empty output
  • v0.9.8
    • Fix ReportT.SpringP() logical bug
    • Add report_test.go
  • v0.9.9
    • Add workPath support for gitCmd and myCmd
    • Add GitRoot(), GitRootSubmodule(), GitExecExist(), GitExecPath()
    • Add test
  • v1.0.0
    • file.go
      • Add FullPath()
      • All func return *string
    • gitCmd.go
      • GitPush() correct optionP param type
    • myCmd.go
      • MyCmd.Run() improve debug output
      • MyCmdInit() use full path for WorkDir
    • report.go
      • ReportT.StringP()
        • Add *[]string case
        • case []string, *[]string
          • fix bug only print last line
          • no longer remove empty line
    • string.go
      • StrArrayPtrRemoveEmpty() return new array
      • StrPToArrayP no longer remove empty line
      • func name StrPToArrayP -> StrPtrToArrayPtr
  • v1.0.1
    • Improve comment for godoc
  • v1.1.1
    • Add Git(), GitBranchCurrent(), GitClone(), GitPull()
  • v1.1.2
    • Add IsRegularFile(), IsDir(), SameDir()
    • Add StrPtrToJsonIndentSp(), StrToJsonIndentSp(), AnyToJsonMarshalIndentSp()
    • Add basic error type
    • Add warning type
    • If !Debug, short circuit ReportDebug() ReportSpDebug()
    • Report() support error type
  • v1.1.3
    • Add ErrsType.Empty(), ErrsType.Clear()
    • Add FullPathStr(), FileRemoveExt(), FileInDir(), FileSimplifyName(), FileHasExt()
    • Add MyCmd.Reset(), MyCmd.Init()
    • Add number types/pointers support in ReportT.StringP()
    • Fix #6 - ReportT().StringP add space after title ":"
    • Fix BoxSealAnonymous() decoding length checking
  • v1.1.4
    • ReportT.StringP() handle nil *[]string
  • v1.1.5
    • Go 1.20
  • v1.1.6
    • MyCmd struct
      • Add ExitCode
      • Run() will handle exit code properly
      • Update test cases
License

The MIT License

Copyright (c) 2023 John Siu

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

string.go - a collection of string related helper functions

Index

Constants

This section is empty.

Variables

View Source
var Debug bool = false

Debug flag General debug flag to enable/disable ReportDebug*

View Source
var DebugReport bool = false

Enable/Disable debug print out within report.go

View Source
var NIL_JSON string

nil pointer to string by json.Marshal

View Source
var NIL_SPRINT string = fmt.Sprint(nil)

nil pointer to string by sprint

Functions

func AnyToJsonMarshalIndentSp added in v1.1.3

func AnyToJsonMarshalIndentSp(data any, endLn bool) *string

Json marshal indent format any

  • String to json indent format
  • If <endLn> is true, add new line at end of string if not exist.
  • Return string pointer.

func AnyToJsonMarshalSp added in v1.1.3

func AnyToJsonMarshalSp(data any, endLn bool) *string

Json marshal format any

  • String to json format
  • If <endLn> is true, add new line at end of string if not exist.
  • Return string pointer.

func BoolStatus

func BoolStatus(b bool) string

bool to "OK"/"Fail"

func BoolString

func BoolString(b bool) string

bool to "true"/"false"

func BoolYesNo

func BoolYesNo(b bool) string

bool to "Yes/No"

func BoxSealAnonymous

func BoxSealAnonymous(base64PublicKey, msg *string) *string

Encrypt msg with public key using nacl box seal anonymous.

  • Parameter "base64PublicKey" and returning string are base64 encoded.
  • Return nil if error
  • All errors append to Errs

func CurrentDirBase

func CurrentDirBase() *string

Get current directory name. Not full path.

  • Return string pointer.

func CurrentPath added in v0.9.9

func CurrentPath() *string

Get full path of current directory.

  • Return string pointer.

func DebugEnv

func DebugEnv() bool

DebugEnv - set debug flag from env

func DebugLog

func DebugLog(msg ...interface{})

DebugLog - msg

func ErrCheck

func ErrCheck(e error)

ErrCheck - check error

func FileHasExt added in v1.1.3

func FileHasExt(name, ext string) bool

Check file has supplied extension

func FileInDir added in v1.1.3

func FileInDir(dir, filename string) string

Search for file in a directory

  • filename path info removed automatically, only base is used
  • case insensitive search
  • return actually filename if found
  • return empty if not found or error
  • error is added to Errs

func FileRemoveExt added in v1.1.3

func FileRemoveExt(filename string) string

Return filename/path with extension removed

func FileSimplifyName added in v1.1.3

func FileSimplifyName(filename string) string

Apply following to filename:

  • remove extension
  • to lowercase
  • remove -,_

func FullPath added in v1.0.0

func FullPath(workPathP *string) *string

Return full path of path provided.

  • If <workPathP> is empty/nil, use current path.
  • <workPathP> not modified.
  • Return string pointer.

func FullPathStr added in v1.1.3

func FullPathStr(workPath string) *string

Return full path of path provided.

  • If <workPath> is empty, use current path.
  • Return string pointer.

func GitExecExist added in v0.9.9

func GitExecExist() bool

Check git executable exist.

func GitExecPath added in v0.9.9

func GitExecPath() string

Get git executable path.

  • Return empty string if not found.

func GitRemote

func GitRemote(workPathP *string, v bool) *[]string

Run "git remote".

  • If <workPathP> is empty/nil, current directory is used.
  • Return remotes in string array.

func GitRemoteExist

func GitRemoteExist(workPathP *string, name string) bool

Check if a git remote(by name) exist in workPath.

  • If <workPathP> is empty/nil, current directory is used.

func GitRemoteRemoveAll

func GitRemoteRemoveAll(workPathP *string)

Run "git remote remove" all git remotes

  • If <workPathP> is empty/nil, current directory is used.

func GitRoot added in v0.9.9

func GitRoot(workPathP *string) string

Get git root from current directory.

  • If <workPathP> is empty/nil, current directory is used.
  • Return empty string if not a git dir.

func GitRootSubmodule added in v0.9.9

func GitRootSubmodule(workPathP *string) string

Get git submodule root from `workPath`.

  • If <workPathP> is empty/nil, current directory is used.
  • Return empty string if not a submodule dir.

func IsDir added in v1.1.2

func IsDir(workPath string) bool

Check workPath is directory

func IsRegularFile added in v1.1.2

func IsRegularFile(workPath string) bool

Check workPath is regular file

func JsonIndentSp

func JsonIndentSp(baP *[]byte, endLn bool) *string

Json marshal indent format

  • If <endLn> is true, add new line at end of string if not exist.
  • Return string pointer.

func Report

func Report(data any, title string, skipEmpty bool, singleLine bool)

Print any data(optional) with title(optional).

  • If <skipEmpty> is true, will not print title if <data> is empty.
  • If <singleLine> is true, <data> will not start on new line.

Refer to ReportT.StringP() for format handling

func ReportDebug

func ReportDebug(data any, title string, skipEmpty bool, singleLine bool)

Only print if helper.Debug is true.

  • Print any data(optional) with title(optional).
  • If <skipEmpty> is true, will not print title if <data> is empty.
  • If <singleLine> is true, <data> will not start on new line.

Refer to ReportT.StringP() for format handling

func ReportSp

func ReportSp(data any, title string, skipEmpty bool, singleLine bool) *string

Print any data(optional) with title(optional) into a string.

  • If <skipEmpty> is true, will not print title if <data> is empty.
  • If <singleLine> is true, <data> will not start on new line.
  • Return a string pointer.

Refer to ReportT.StringP() for format handling

func ReportSpDebug added in v0.9.8

func ReportSpDebug(data any, title string, skipEmpty bool, singleLine bool) *string

Only print if helper.Debug is true.

  • Print any data(optional) with title(optional) into a string.
  • If <skipEmpty> is true, will not print title if <data> is empty.
  • If <singleLine> is true, <data> will not start on new line.
  • Return a string pointer.

Refer to ReportT.StringP() for format handling

func ReportStatus

func ReportStatus(data bool, title string, singleLine bool)

Print bool into true/false, with title(optional).

  • If <skipEmpty> is true, will not print title if <data> is empty.
  • If <singleLine> is true, <data> will not start on new line.

Refer to ReportT.StringP() for format handling

func ReportStatusSp added in v1.0.1

func ReportStatusSp(data bool, title string, singleLine bool) *string

Only print if helper.Debug is true.

  • Print bool into true/false, with title(optional), into a string.
  • If <skipEmpty> is true, will not print title if <data> is empty.
  • If <singleLine> is true, <data> will not start on new line.
  • Return a string pointer.

Refer to ReportT.StringP() for format handling

func SameDir added in v1.1.2

func SameDir(path1, path2 string) bool

Check two paths have same parent directory

func StrArrayPtrContain

func StrArrayPtrContain(aP *[]string, sP *string) bool

Check if string array contain a string.

func StrArrayPtrPrintln

func StrArrayPtrPrintln(saP *[]string)

*[]string output, each element followed by "\n"

func StrArrayPtrPrintlnSp added in v1.0.1

func StrArrayPtrPrintlnSp(saP *[]string) *string

*[]string to *string, each element followed by "\n"

func StrArrayPtrRemoveEmpty

func StrArrayPtrRemoveEmpty(saP *[]string) *[]string

Return a new *[]string with empty lines removed from *[]string.

  • Original []string not modified.

func StrPtrToArrayPtr added in v1.0.0

func StrPtrToArrayPtr(sP *string) *[]string

*string to *[]string, split by "\n"

func StrPtrToJsonIndentSp added in v1.1.2

func StrPtrToJsonIndentSp(strP *string, endLn bool) *string

Json marshal indent format

  • String to json indent format
  • If <endLn> is true, add new line at end of string if not exist.
  • Return string pointer.

func StrToJsonIndentSp added in v1.1.2

func StrToJsonIndentSp(str string, endLn bool) *string

Json marshal indent format

  • String to json indent format
  • If <endLn> is true, add new line at end of string if not exist.
  • Return string pointer.

Types

type Err added in v1.1.2

type Err string

Type Err is a string with error interface

func (Err) Error added in v1.1.2

func (self Err) Error() string

`error` interface

func (*Err) String added in v1.1.2

func (self *Err) String() string

Return content of Err as string

func (*Err) StringP added in v1.1.2

func (self *Err) StringP() *string

Return content of Err as *string

type MyArray added in v1.1.5

type MyArray[T any] []T
var Errs MyArray[error]

error list

var Warns MyArray[string]

warning list

func (*MyArray[T]) Add added in v1.1.5

func (self *MyArray[T]) Add(t T) *MyArray[T]

func (*MyArray[T]) Clear added in v1.1.5

func (self *MyArray[T]) Clear()

Clear the ErrsType array

func (*MyArray[T]) Empty added in v1.1.5

func (self *MyArray[T]) Empty() bool

Return true if ErrsType array is empty

func (*MyArray[T]) NotEmpty added in v1.1.5

func (self *MyArray[T]) NotEmpty() bool

Return true if ErrsType array is not empty

type MyCmd

type MyCmd struct {
	ArgsP    *[]string    `json:"ArgsP"`   // In : Command args
	CmdLn    string       `json:"CmdLn"`   // Out: Command line
	CmdName  string       `json:"CmdName"` // In : Command name
	Err      error        `json:"Err"`     // Out: run error
	ExitCode int          `json:ExitCode`  // Out: Exit Code
	Ran      bool         `json:"Ran"`     // Out: Set to true by Run()
	Stderr   bytes.Buffer `json:"Stderr"`  // Out: Stderr
	Stdout   bytes.Buffer `json:"Stdout"`  // Out: Stdout
	WorkDir  string       `json:"WorkDir"` // In : Command working dir
}

A exec.Cmd wrapper

func Git added in v1.1.1

func Git(workPathP *string, optionsP *[]string) *MyCmd

Run "git <optionsP>".

  • If <workPathP> is empty/nil, current directory is used.
  • Return a MyCmd pointer for execution information.

func GitBranchCurrent added in v1.1.1

func GitBranchCurrent(workPathP *string) *MyCmd

Run "git branch --show-current".

  • If <workPathP> is empty/nil, current directory is used.
  • Return a MyCmd pointer for execution information.

func GitClone added in v1.1.1

func GitClone(workPathP *string, optionsP *[]string) *MyCmd

Run "git clone <optionsP>".

  • If <workPathP> is empty/nil, current directory is used.
  • Return a MyCmd pointer for execution information.

func GitInit

func GitInit(workPathP *string) *MyCmd

Run "git init".

  • If <workPathP> is empty/nil, current directory is used.
  • Return a MyCmd pointer for execution information.

func GitPull added in v1.1.1

func GitPull(workPathP *string, optionsP *[]string) *MyCmd

Run "git pull <optionsP>".

  • If <workPathP> is empty/nil, current directory is used.
  • Return a MyCmd pointer for execution information.

func GitPush

func GitPush(workPathP *string, optionsP *[]string) *MyCmd

Run "git push <optionsP>".

  • If <workPathP> is empty/nil, current directory is used.
  • Return a MyCmd pointer for execution information.

func GitRemoteAdd

func GitRemoteAdd(workPathP *string, name string, git string) *MyCmd

Run "git remote add <name> <git>".

  • If <workPathP> is empty/nil, current directory is used.
  • Return a MyCmd pointer for execution information.

func GitRemoteRemove

func GitRemoteRemove(workPathP *string, name string) *MyCmd

Run "git remote remove".

  • If <workPathP> is empty/nil, current directory is used.
  • If remote exist Return a MyCmd pointer for execution information.
  • If remote does not exit, return nil.(Nothing to remove)

func MyCmdInit added in v0.9.9

func MyCmdInit(name string, argsP *[]string, workPathP *string) *MyCmd

Setup and return MyCmd pointer.

  • If <workPathP> is empty/nil, current directory is used.

func MyCmdRun

func MyCmdRun(cmdName string, argsP *[]string, workPathP *string) *MyCmd

MyCmd run func wrapper.

  • If <workPathP> is empty/nil, current directory is used.

func MyCmdRunWg

func MyCmdRunWg(cmdName string, argsP *[]string, workPathP *string, title *string, wgP *sync.WaitGroup, output bool) *MyCmd

MyCmd run func wrapper with sync.WaitGroup support.

  • If <workPathP> is empty/nil, current directory is used.
  • Print if <output> is true

func (*MyCmd) Init added in v1.1.3

func (self *MyCmd) Init(name string, argsP *[]string, workPathP *string) *MyCmd

Setup and return MyCmd pointer.

  • If <workPathP> is empty/nil, current directory is used.

func (*MyCmd) Reset added in v1.1.3

func (self *MyCmd) Reset() *MyCmd

Reset MyCmd

func (*MyCmd) Run

func (self *MyCmd) Run() error

A exec.Cmd.Run() wrapper.

type ReportT

type ReportT struct {
	Data       any    `json:"Data"`       // Data to be printed
	Title      string `json:"Title"`      // Title of print out
	ModeStatus bool   `json:"ModeStatus"` // bool to "OK/Failed"
	SkipEmpty  bool   `json:"SkipEmpty"`  //  - Return empty string if Data is empty
	SingleLine bool   `json:"SingleLine"` // No need line after title
}

ReportT is the base structure for the Report.StringP() function, which support printing a wide range of data types.

func ReportNew

func ReportNew(data any, title string, skipEmpty bool, singleLine bool) *ReportT

Setup ReportT with data(optional/nil), title(optional/""), <skipEmpty>, <singleLine>.

  • Return the ReportT pointer.

Refer to ReportT.StringP() for format handling

func (*ReportT) String

func (self *ReportT) String() string

Print self.Data, self.Title to string

  • If self.SkipEmpty is true, will not print self.Title if self.Data is empty.
  • If self.SingleLine is true, self.Data will not start on new line.

Refer to ReportT.StringP() for format handling

func (*ReportT) StringDebug

func (self *ReportT) StringDebug() string

Only print if helper.Debug is true.

  • Print self.Data, self.Title to string
  • If self.SkipEmpty is true, will not print self.Title if self.Data is empty.
  • If self.SingleLine is true, self.Data will not start on new line.

Refer to ReportT.StringP() for format handling

func (*ReportT) StringP

func (self *ReportT) StringP() *string

Print self.Data, self.Title to string pointer

  • If self.SkipEmpty is true, will not print self.Title if self.Data is empty.
  • If self.SingleLine is true, self.Data will not start on new line.
  • self.Data formatting
  • []byte, string, Err, MyArray[error], MyArray[string], including array and pointer, are treated as string and processed by StrToJsonIndentSp()/StrPtrToJsonIndentSp()
  • MyArray[any] is processed by AnyToJsonMarshalIndentSp()
  • int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, including pointer, are processed by AnyToJsonMarshalSp()
  • All pointer types mentioned above, if nil, are treated as empty string
  • Others, usually struct, not specified, are processed by AnyToJsonMarshalIndentSp()

func (*ReportT) StringPDebug

func (self *ReportT) StringPDebug() *string

Only print if helper.Debug is true.

  • Print self.Data, self.Title to string pointer
  • If self.SkipEmpty is true, will not print self.Title if self.Data is empty.
  • If self.SingleLine is true, self.Data will not start on new line.

Refer to ReportT.StringP() for format handling

Jump to

Keyboard shortcuts

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