Heavy refactoring, see PR #28

This commit is contained in:
kayos@tcp.direct 2024-06-16 23:57:19 -07:00
parent ab104bb7bc
commit 3337efcb8f
No known key found for this signature in database
GPG key ID: 4B841471B4BEE979
11 changed files with 323 additions and 156 deletions

View file

@ -8,16 +8,20 @@ import (
"os"
"github.com/HikariKnight/ls-iommu/pkg/errorcheck"
"github.com/HikariKnight/quickpassthrough/internal/common"
)
/*
* This just implements repetetive tasks I have to do with files
*/
// Creates a file and appends the content to the file (ending newline must be supplied with content string)
// AppendContent creates a file and appends the content to the file.
// (ending newline must be supplied with content string)
func AppendContent(content string, fileName string) {
// Open the file
f, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
errorcheck.ErrorCheck(err, fmt.Sprintf("Error opening \"%s\" for writing", fileName))
defer f.Close()
@ -26,7 +30,7 @@ func AppendContent(content string, fileName string) {
errorcheck.ErrorCheck(err, fmt.Sprintf("Error writing to %s", fileName))
}
// Reads the file and returns a stringlist with each line
// ReadLines reads the file and returns a stringlist with each line.
func ReadLines(fileName string) []string {
content, err := os.Open(fileName)
errorcheck.ErrorCheck(err, fmt.Sprintf("Error reading file %s", fileName))
@ -46,10 +50,14 @@ func ReadLines(fileName string) []string {
}
// Reads a file and returns all the content as a string
// ReadFile reads a file and returns all the content as a string.
func ReadFile(fileName string) string {
// Read the whole file
content, err := os.ReadFile(fileName)
if errors.Is(err, os.ErrPermission) {
errorcheck.ErrorCheck(err, common.PermissionNotice)
return "" // note: unreachable due to ErrorCheck calling fatal
}
errorcheck.ErrorCheck(err, fmt.Sprintf("Failed to ReadFile on %s", fileName))
// Return all the lines as one string
@ -57,24 +65,25 @@ func ReadFile(fileName string) string {
}
// Checks if a file exists and returns a bool
func FileExist(fileName string) bool {
// FileExist checks if a file exists and returns a bool and any error that isn't os.ErrNotExist.
func FileExist(fileName string) (bool, error) {
var exist bool
// Check if the file exists
if _, err := os.Stat(fileName); !errors.Is(err, os.ErrNotExist) {
// Set the value to true
_, err := os.Stat(fileName)
switch {
case err == nil:
exist = true
} else {
// Set the value to false
case errors.Is(err, os.ErrNotExist):
// Set the value to true
exist = false
err = nil
}
// Return if the file exists
return exist
return exist, err
}
// Copies a FILE from source to dest
// FileCopy copies a FILE from source to dest.
func FileCopy(sourceFile, destFile string) {
// Get the file info
filestat, err := os.Stat(sourceFile)