Compare commits

...

10 Commits
v0.1.1 ... main

9 changed files with 183 additions and 103 deletions

29
LICENSE Normal file
View File

@ -0,0 +1,29 @@
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,3 +1,6 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// file_util.go // file_util.go
package utils package utils
@ -20,6 +23,13 @@ func FileSize(filePath string) (size int64) {
return 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 { func IsRegularFile(filePath string) bool {
if filePath != "" { if filePath != "" {
info, err := os.Stat(filePath) info, err := os.Stat(filePath)
@ -45,6 +55,22 @@ func IsSymLink(filePath string) bool {
return false 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 { func IsSymLinkByDirEntry(e os.DirEntry) bool {
info, _ := e.Info() info, _ := e.Info()
return info.Mode()&os.ModeSymlink != 0 return info.Mode()&os.ModeSymlink != 0
@ -69,23 +95,23 @@ func MoveFile(sourcePath, destPath string) (int64, error) {
if err != nil { if err != nil {
inputFile, err := os.Open(sourcePath) inputFile, err := os.Open(sourcePath)
if err != nil { 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) outputFile, err := os.Create(destPath)
if err != nil { if err != nil {
inputFile.Close() 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() defer outputFile.Close()
size, err = io.Copy(outputFile, inputFile) size, err = io.Copy(outputFile, inputFile)
inputFile.Close() inputFile.Close()
if err != nil { if err != nil {
return 0, fmt.Errorf("Writing to output file failed: %s", err) return 0, fmt.Errorf("failed writing to output file: %s", err)
} }
// The copy was successful, so now delete the original file // The copy was successful, so now delete the original file
err = os.Remove(sourcePath) err = os.Remove(sourcePath)
if err != nil { 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 return size, nil
@ -110,7 +136,7 @@ func ParseMemSize(s string) (size int64, err error) {
size, err = strconv.ParseInt(s, 10, 64) size, err = strconv.ParseInt(s, 10, 64)
} }
} else { } else {
err = errors.New("Empty string") err = errors.New("empty string")
} }
return return
} }

View File

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

View File

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

View File

@ -1,3 +1,6 @@
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.
// os-util.go // os-util.go
package utils package utils
@ -129,7 +132,7 @@ func MakeParentDir(filePath string) (dir string, err error) {
dir = filepath.Dir(filePath) dir = filepath.Dir(filePath)
if !IsDirectory(dir) { if !IsDirectory(dir) {
if err1 := os.MkdirAll(dir, 0755); err1 != nil { 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 return
@ -154,7 +157,7 @@ func ExpandFilePathAndMakeParentV(specPath string, maps ...map[string]string) (e
func MakeDir(dirPath string) (err error) { func MakeDir(dirPath string) (err error) {
if !IsDirectory(dirPath) { if !IsDirectory(dirPath) {
if err1 := os.MkdirAll(dirPath, 0755); err1 != nil { 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 return

View File

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

View File

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

View File

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

View File

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