Fix: avoid silent fatalities

demo: https://tcp.ac/i/JMSUc.gif
This commit is contained in:
kayos@tcp.direct 2024-06-17 00:30:24 -07:00
parent 3337efcb8f
commit 395f5ab6bc
No known key found for this signature in database
GPG key ID: 4B841471B4BEE979
13 changed files with 115 additions and 78 deletions

View file

@ -7,8 +7,6 @@ import (
"io"
"os"
"github.com/HikariKnight/ls-iommu/pkg/errorcheck"
"github.com/HikariKnight/quickpassthrough/internal/common"
)
@ -22,18 +20,18 @@ 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))
common.ErrorCheck(err, fmt.Sprintf("Error opening \"%s\" for writing", fileName))
defer f.Close()
// Write the content
_, err = f.WriteString(content)
errorcheck.ErrorCheck(err, fmt.Sprintf("Error writing to %s", fileName))
common.ErrorCheck(err, fmt.Sprintf("Error writing to %s", fileName))
}
// 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))
common.ErrorCheck(err, fmt.Sprintf("Error reading file %s", fileName))
defer content.Close()
// Make a list of lines
@ -55,10 +53,10 @@ 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)
common.ErrorCheck(err, common.PermissionNotice)
return "" // note: unreachable due to ErrorCheck calling fatal
}
errorcheck.ErrorCheck(err, fmt.Sprintf("Failed to ReadFile on %s", fileName))
common.ErrorCheck(err, fmt.Sprintf("Failed to ReadFile on %s", fileName))
// Return all the lines as one string
return string(content)
@ -87,22 +85,22 @@ func FileExist(fileName string) (bool, error) {
func FileCopy(sourceFile, destFile string) {
// Get the file info
filestat, err := os.Stat(sourceFile)
errorcheck.ErrorCheck(err, "Error getting fileinfo of: %s", sourceFile)
common.ErrorCheck(err, "Error getting fileinfo of: %s", sourceFile)
// If the file is a regular file
if filestat.Mode().IsRegular() {
// Open the source file for reading
source, err := os.Open(sourceFile)
errorcheck.ErrorCheck(err, "Error opening %s for copying", sourceFile)
common.ErrorCheck(err, "Error opening %s for copying", sourceFile)
defer source.Close()
// Create the destination file
dest, err := os.Create(destFile)
errorcheck.ErrorCheck(err, "Error creating %s", destFile)
common.ErrorCheck(err, "Error creating %s", destFile)
defer dest.Close()
// Copy the contents of source to dest using io
_, err = io.Copy(dest, source)
errorcheck.ErrorCheck(err, "Failed to copy \"%s\" to \"%s\"", sourceFile, destFile)
common.ErrorCheck(err, "Failed to copy \"%s\" to \"%s\"", sourceFile, destFile)
}
}