109 lines
2.2 KiB
Go
109 lines
2.2 KiB
Go
|
package utils
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
)
|
||
|
|
||
|
// AppendLineToFile appends the line l to file
|
||
|
func AppendLineToFile(file string, l string) error {
|
||
|
f, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0660)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
defer f.Close()
|
||
|
|
||
|
if _, err = f.WriteString(l + "\n"); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// CreateFolder creates a the folder f
|
||
|
func CreateFolder(f string) error {
|
||
|
err := os.Mkdir(f, 0700)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// GetAllFilesInFolderByExtension returns all files by extension of a given folder recursively
|
||
|
func GetAllFilesInFolderByExtension(pathToFolder string, extension string) []string {
|
||
|
files := []string{}
|
||
|
|
||
|
filepath.Walk(pathToFolder,
|
||
|
func(path string, info os.FileInfo, err error) error {
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
if info.IsDir() {
|
||
|
return nil
|
||
|
}
|
||
|
if filepath.Ext(path) != extension {
|
||
|
return nil
|
||
|
}
|
||
|
files = append(files, path)
|
||
|
return nil
|
||
|
})
|
||
|
|
||
|
return files
|
||
|
}
|
||
|
|
||
|
// GetPathToParrentFolderOfThisExecutable returns the path to the folder where this executable is located
|
||
|
func GetPathToParrentFolderOfThisExecutable() string {
|
||
|
return filepath.Dir(GetPathToThisExecutable())
|
||
|
}
|
||
|
|
||
|
// GetPathToThisExecutable returns the path where this executable is located
|
||
|
func GetPathToThisExecutable() string {
|
||
|
e, err := os.Executable()
|
||
|
if err != nil {
|
||
|
return "."
|
||
|
}
|
||
|
|
||
|
return e
|
||
|
}
|
||
|
|
||
|
// GetSizeOfFileInBytes returns the size of a file in bytes
|
||
|
func GetSizeOfFileInBytes(p string) (int64, error) {
|
||
|
if !DoesFileExist(p) {
|
||
|
return 0, errors.New("not a file or does not exist")
|
||
|
}
|
||
|
|
||
|
fileInfo, err := os.Stat(p)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
return fileInfo.Size(), nil
|
||
|
}
|
||
|
|
||
|
// LoadStringFromFile writes a string to a file
|
||
|
func LoadStringFromFile(pathOfFile string) (string, error) {
|
||
|
if !DoesFileExist(pathOfFile) {
|
||
|
return "", errors.New("file " + pathOfFile + "does not exist")
|
||
|
}
|
||
|
|
||
|
fileContent, err := os.ReadFile(pathOfFile)
|
||
|
if err != nil {
|
||
|
return "", errors.New("could not read file " + pathOfFile)
|
||
|
}
|
||
|
|
||
|
return string(fileContent), nil
|
||
|
}
|
||
|
|
||
|
// WriteStringToFile writes a string to a file
|
||
|
func WriteStringToFile(file string, s string) error {
|
||
|
err := os.WriteFile(file, []byte(s+"\n"), 0660)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|