Compare commits

..

No commits in common. "main" and "v0.1.0" have entirely different histories.
main ... v0.1.0

10 changed files with 105 additions and 184 deletions

29
LICENSE
View File

@ -1,29 +0,0 @@
Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Celestino Amoroso, nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,6 +1,3 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// file_util.go
package utils
@ -23,13 +20,6 @@ func FileSize(filePath string) (size int64) {
return
}
// Return true if filePath exists
func FileExists(filePath string) bool {
_, osErr := os.Stat(filePath)
return osErr == nil || osErr == os.ErrExist
}
// Return true if filePath exists and it is a regular file
func IsRegularFile(filePath string) bool {
if filePath != "" {
info, err := os.Stat(filePath)
@ -55,22 +45,6 @@ func IsSymLink(filePath string) bool {
return false
}
func IsSocket(filePath string) bool {
if filePath != "" {
info, err := os.Stat(filePath)
return (err == nil || errors.Is(err, os.ErrExist)) && (info.Mode()&os.ModeSocket != 0)
}
return false
}
func IsNamedPipe(filePath string) bool {
if filePath != "" {
info, err := os.Stat(filePath)
return (err == nil || errors.Is(err, os.ErrExist)) && (info.Mode()&os.ModeNamedPipe != 0)
}
return false
}
func IsSymLinkByDirEntry(e os.DirEntry) bool {
info, _ := e.Info()
return info.Mode()&os.ModeSymlink != 0
@ -95,23 +69,23 @@ func MoveFile(sourcePath, destPath string) (int64, error) {
if err != nil {
inputFile, err := os.Open(sourcePath)
if err != nil {
return 0, fmt.Errorf("couldn't open source file: %s", err)
return 0, fmt.Errorf("Couldn't open source file: %s", err)
}
outputFile, err := os.Create(destPath)
if err != nil {
inputFile.Close()
return 0, fmt.Errorf("couldn't open dest file: %s", err)
return 0, fmt.Errorf("Couldn't open dest file: %s", err)
}
defer outputFile.Close()
size, err = io.Copy(outputFile, inputFile)
inputFile.Close()
if err != nil {
return 0, fmt.Errorf("failed writing to output file: %s", err)
return 0, fmt.Errorf("Writing to output file failed: %s", err)
}
// The copy was successful, so now delete the original file
err = os.Remove(sourcePath)
if err != nil {
return 0, fmt.Errorf("failed removing original file: %s", err)
return 0, fmt.Errorf("Failed removing original file: %s", err)
}
}
return size, nil
@ -136,7 +110,7 @@ func ParseMemSize(s string) (size int64, err error) {
size, err = strconv.ParseInt(s, 10, 64)
}
} else {
err = errors.New("empty string")
err = errors.New("Empty string")
}
return
}

3
go.mod
View File

@ -1,5 +1,6 @@
module git.portale-stac.it/go-pkg/utils
module portale-stac.it/packages/utils
go 1.21
require golang.org/x/text v0.3.7

View File

@ -1,6 +1,3 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// gzip-util.go
package utils
@ -15,9 +12,9 @@ import (
const GZIP_SUFFIX = ".gz"
func CreateGzipReader(in io.Reader) (reader *bufio.Reader, err error) {
var inflate *gzip.Reader
if inflate, err = gzip.NewReader(in); err != nil {
err = fmt.Errorf("can't inflate gzipped input stream: %v", err)
inflate, err := gzip.NewReader(in)
if err != nil {
fmt.Errorf("Can't inflate gzipped input stream: %v", err)
} else {
reader = bufio.NewReader(inflate)
}
@ -25,10 +22,10 @@ func CreateGzipReader(in io.Reader) (reader *bufio.Reader, err error) {
}
func CreateGzipFile(in io.Reader, fileName string) (reader *bufio.Reader, err error) {
var inflate *gzip.Reader
if len(fileName) > 0 && strings.HasSuffix(fileName, GZIP_SUFFIX) {
if inflate, err = gzip.NewReader(in); err != nil {
err = fmt.Errorf("can't inflate gzipped input stream %#v: %v", fileName, err)
inflate, err := gzip.NewReader(in)
if err != nil {
fmt.Errorf("Can't inflate gzipped input stream %#v: %v", fileName, err)
} else {
reader = bufio.NewReader(inflate)
}

View File

@ -1,7 +1,3 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// misc-utis.go
package utils
import (
@ -20,7 +16,7 @@ func NewEnglishPrinter() *message.Printer {
return message.NewPrinter(language.English)
}
func ExitErrorf(rc int, format string, args ...any) {
func ExitErrorf(rc int, format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
os.Exit(rc)
}
@ -31,7 +27,7 @@ func ExitMessagef(rc int, format string, args ...interface{}) {
}
func OnStringIndex(index uint, values ...string) (value string) {
if index < uint(len(values)) {
if index >= 0 && index < uint(len(values)) {
value = values[index]
}
return
@ -42,13 +38,12 @@ func OnEmpty(s string, altValues ...string) (value string) {
for _, altValue := range altValues {
if len(altValue) > 0 {
value = altValue
break
}
}
} else {
value = s
}
return value
return s
}
func OnCond(cond bool, trueValue, falseValue string) string {

View File

@ -1,6 +1,3 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// os-util.go
package utils
@ -132,7 +129,7 @@ func MakeParentDir(filePath string) (dir string, err error) {
dir = filepath.Dir(filePath)
if !IsDirectory(dir) {
if err1 := os.MkdirAll(dir, 0755); err1 != nil {
err = fmt.Errorf("can't make parent path of %#v: %v", filePath, err1)
err = fmt.Errorf("Can't make parent path of %#v: %v", filePath, err1)
}
}
return
@ -157,7 +154,7 @@ func ExpandFilePathAndMakeParentV(specPath string, maps ...map[string]string) (e
func MakeDir(dirPath string) (err error) {
if !IsDirectory(dirPath) {
if err1 := os.MkdirAll(dirPath, 0755); err1 != nil {
err = fmt.Errorf("can't make directory path %#v: %v", dirPath, err1)
err = fmt.Errorf("Can't make directory path %#v: %v", dirPath, err1)
}
}
return

View File

@ -1,6 +1,3 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// string
package utils

View File

@ -1,6 +1,3 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// text-util.go
package utils
@ -59,26 +56,26 @@ func NewTextTemplate(args ...string) (instance *TextTemplate) {
return
}
func (tt *TextTemplate) initVarMap() {
tt.varMap["dt"] = "Current timestamp as YYYY-MM-DD_HH-MM-SS"
tt.varMap["ymd"] = "Current date as YYYY-MM-DD"
tt.varMap["hm"] = "Current time as HH-MM"
tt.varMap["h"] = "Current time as HH"
tt.varMap["hms"] = "Current time as HH-MM-SS"
tt.varMap["month"] = "Month name"
tt.varMap["month-num"] = "Month as number (mm)"
tt.varMap["week-day"] = "Week day name"
tt.varMap["week-day-num"] = "Week day as number"
tt.varMap["yesterday"] = "Yesterday date"
tt.varMap["uid"] = tt.Uid
tt.varMap["username"] = tt.UserName
tt.varMap["home"] = tt.HomeDir
tt.varMap["progdir"] = tt.ProgramDir
tt.varMap["hostname"], _ = os.Hostname()
func (self *TextTemplate) initVarMap() {
self.varMap["dt"] = "Current timestamp as YYYY-MM-DD_HH-MM-SS"
self.varMap["ymd"] = "Current date as YYYY-MM-DD"
self.varMap["hm"] = "Current time as HH-MM"
self.varMap["h"] = "Current time as HH"
self.varMap["hms"] = "Current time as HH-MM-SS"
self.varMap["month"] = "Month name"
self.varMap["month-num"] = "Month as number (mm)"
self.varMap["week-day"] = "Week day name"
self.varMap["week-day-num"] = "Week day as number"
self.varMap["yesterday"] = "Yesterday date"
self.varMap["uid"] = self.Uid
self.varMap["username"] = self.UserName
self.varMap["home"] = self.HomeDir
self.varMap["progdir"] = self.ProgramDir
self.varMap["hostname"], _ = os.Hostname()
}
func (tt *TextTemplate) AddVar(name, value string) {
tt.varMap[name] = value
func (self *TextTemplate) AddVar(name, value string) {
self.varMap[name] = value
}
// func MakeVarMap() map[string]string {
@ -92,21 +89,21 @@ func (tt *TextTemplate) AddVar(name, value string) {
// }
// }
func (tt *TextTemplate) updateVarMap() {
func (self *TextTemplate) updateVarMap() {
var now = time.Now()
tt.varMap["ymd"] = fmt.Sprintf("%04d-%02d-%02d", now.Year(), now.Month(), now.Day())
tt.varMap["hms"] = fmt.Sprintf("%02d-%02d-%02d", now.Hour(), now.Minute(), now.Second())
tt.varMap["hm"] = fmt.Sprintf("%02d-%02d", now.Hour(), now.Minute())
tt.varMap["h"] = fmt.Sprintf("%02d", now.Hour())
tt.varMap["month"] = now.Format("January")
tt.varMap["month-num"] = fmt.Sprintf("%02d", now.Month())
tt.varMap["week-day-num"] = fmt.Sprintf("%d", 1+now.Weekday())
tt.varMap["week-day"] = now.Format("Monday")
tt.varMap["dt"] = tt.varMap["ymd"] + "_" + tt.varMap["hms"]
self.varMap["ymd"] = fmt.Sprintf("%04d-%02d-%02d", now.Year(), now.Month(), now.Day())
self.varMap["hms"] = fmt.Sprintf("%02d-%02d-%02d", now.Hour(), now.Minute(), now.Second())
self.varMap["hm"] = fmt.Sprintf("%02d-%02d", now.Hour(), now.Minute())
self.varMap["h"] = fmt.Sprintf("%02d", now.Hour())
self.varMap["month"] = now.Format("January")
self.varMap["month-num"] = fmt.Sprintf("%02d", now.Month())
self.varMap["week-day-num"] = fmt.Sprintf("%d", 1+now.Weekday())
self.varMap["week-day"] = now.Format("Monday")
self.varMap["dt"] = self.varMap["ymd"] + "_" + self.varMap["hms"]
yday := now.AddDate(0, 0, -1)
tt.varMap["yesterday"] = fmt.Sprintf("%04d-%02d-%02d", yday.Year(), yday.Month(), yday.Day())
self.varMap["yesterday"] = fmt.Sprintf("%04d-%02d-%02d", yday.Year(), yday.Month(), yday.Day())
// self.varMap["uid"] = strconv.Itoa(int(self.Uid))
// self.varMap["uid"] = self.Uid
// self.varMap["username"] = self.UserName
@ -114,12 +111,12 @@ func (tt *TextTemplate) updateVarMap() {
// self.varMap["home"] = self.HomeDir
}
func (tt *TextTemplate) Expand(template string) string {
func (self *TextTemplate) Expand(template string) string {
tt.updateVarMap()
self.updateVarMap()
result := os.Expand(template, func(name string) string {
value, ok := tt.varMap[name]
value, ok := self.varMap[name]
if ok {
return value
} else {
@ -130,11 +127,11 @@ func (tt *TextTemplate) Expand(template string) string {
return result
}
func (tt *TextTemplate) ExpandEnv(template string) (result string) {
func (self *TextTemplate) ExpandEnv(template string) (result string) {
if len(template) > 0 {
tt.updateVarMap()
self.updateVarMap()
result = os.Expand(template, func(name string) string {
value, ok := tt.varMap[name]
value, ok := self.varMap[name]
if ok {
return value
} else {
@ -159,22 +156,22 @@ func (tt *TextTemplate) ExpandEnv(template string) (result string) {
return result
}
func (tt *TextTemplate) Value(key string) (value string, ok bool) {
value, ok = tt.varMap[key]
func (self *TextTemplate) Value(key string) (value string, ok bool) {
value, ok = self.varMap[key]
return
}
func (tt *TextTemplate) String() string {
func (self *TextTemplate) String() string {
var sb strings.Builder
keys := make([]string, 0, len(tt.varMap))
for k := range tt.varMap {
keys := make([]string, 0, len(self.varMap))
for k := range self.varMap {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
sb.WriteString(fmt.Sprintf("%s=%#v\n", k, tt.varMap[k]))
sb.WriteString(fmt.Sprintf("%s=%#v\n", k, self.varMap[k]))
}
// for k, v := range self.varMap {
// sb.WriteString(fmt.Sprintf("%s=%#v\n", k, v))

View File

@ -1,7 +1,3 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// time.go
package utils
import (

View File

@ -1,7 +1,3 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// tty-utils.go
package utils
import (
@ -29,142 +25,142 @@ type TTYContext struct {
isTTY [3]bool
}
func (ctx *TTYContext) Init() {
for i := range ctx.isTTY {
ctx.isTTY[i] = StreamIsTerminal(getStream(uint(i)))
func (self *TTYContext) Init() {
for i, _ := range self.isTTY {
self.isTTY[i] = StreamIsTerminal(getStream(uint(i)))
}
}
func (ctx *TTYContext) IsTTY(fd uint) bool {
func (self *TTYContext) IsTTY(fd uint) bool {
if fd == STDERR || fd == STDOUT {
return ctx.isTTY[fd]
return self.isTTY[fd]
}
return false
}
func (ctx *TTYContext) Clean() {
for i := range ctx.isTTY {
ctx.isTTY[i] = false
func (self *TTYContext) Clean() {
for i, _ := range self.isTTY {
self.isTTY[i] = false
}
}
func (ctx *TTYContext) Bold(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) Bold(fd uint) string {
if self.isTTY[fd] {
return "\x1b[1m"
}
return ""
}
func (ctx *TTYContext) BoldOff(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) BoldOff(fd uint) string {
if self.isTTY[fd] {
return "\x1b[22m"
}
return ""
}
func (ctx *TTYContext) Underline(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) Underline(fd uint) string {
if self.isTTY[fd] {
return "\x1b[4m"
}
return ""
}
func (ctx *TTYContext) UnderlineOff(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) UnderlineOff(fd uint) string {
if self.isTTY[fd] {
return "\x1b[24m"
}
return ""
}
func (ctx *TTYContext) Italic(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) Italic(fd uint) string {
if self.isTTY[fd] {
return "\x1b[3m"
}
return ""
}
func (ctx *TTYContext) ItalicOff(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) ItalicOff(fd uint) string {
if self.isTTY[fd] {
return "\x1b[23m"
}
return ""
}
func (ctx *TTYContext) BlackFg(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) BlackFg(fd uint) string {
if self.isTTY[fd] {
return "\x1b[30m"
}
return ""
}
func (ctx *TTYContext) RedFg(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) RedFg(fd uint) string {
if self.isTTY[fd] {
return "\x1b[31m"
}
return ""
}
func (ctx *TTYContext) GreenFg(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) GreenFg(fd uint) string {
if self.isTTY[fd] {
return "\x1b[32m"
}
return ""
}
func (ctx *TTYContext) BrownFg(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) BrownFg(fd uint) string {
if self.isTTY[fd] {
return "\x1b[33m"
}
return ""
}
func (ctx *TTYContext) BlueFg(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) BlueFg(fd uint) string {
if self.isTTY[fd] {
return "\x1b[34m"
}
return ""
}
func (ctx *TTYContext) MagentaFg(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) MagentaFg(fd uint) string {
if self.isTTY[fd] {
return "\x1b[35m"
}
return ""
}
func (ctx *TTYContext) CyanFg(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) CyanFg(fd uint) string {
if self.isTTY[fd] {
return "\x1b[36m"
}
return ""
}
func (ctx *TTYContext) WhiteFg(fd uint) string {
if ctx.isTTY[fd] {
func (self *TTYContext) WhiteFg(fd uint) string {
if self.isTTY[fd] {
return "\x1b[37m"
}
return ""
}
func (ctx *TTYContext) FgColor(fd uint, n uint) string {
func (self *TTYContext) FgColor(fd uint, n uint) string {
var color string
switch n {
case BLACK:
color = ctx.BlackFg(fd)
color = self.BlackFg(fd)
case WHITE:
color = ctx.WhiteFg(fd)
color = self.WhiteFg(fd)
case RED:
color = ctx.RedFg(fd)
color = self.RedFg(fd)
case GREEN:
color = ctx.GreenFg(fd)
color = self.GreenFg(fd)
case BLUE:
color = ctx.BlueFg(fd)
color = self.BlueFg(fd)
case BROWN:
color = ctx.BrownFg(fd)
color = self.BrownFg(fd)
case CYAN:
color = ctx.CyanFg(fd)
color = self.CyanFg(fd)
case MAGENTA:
color = ctx.MagentaFg(fd)
color = self.MagentaFg(fd)
}
return color
}
@ -188,7 +184,7 @@ func (ctx *TTYContext) FgColor(fd uint, n uint) string {
// return color
// }
func (ctx *TTYContext) Reset(fd uint) string {
func (self *TTYContext) Reset(fd uint) string {
if StreamIsTerminal(getStream(fd)) {
return "\x1b[0m"
}