2024-05-31 00:11:02 +01:00
|
|
|
package utilities
|
|
|
|
|
|
|
|
import (
|
2024-08-15 15:24:25 +01:00
|
|
|
"bufio"
|
2024-06-22 01:16:24 +01:00
|
|
|
"errors"
|
2024-05-31 00:11:02 +01:00
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
func ReadFile(path string) (string, error) {
|
2024-08-15 15:24:25 +01:00
|
|
|
file, err := os.Open(path)
|
2024-05-31 00:11:02 +01:00
|
|
|
if err != nil {
|
2024-08-15 15:24:25 +01:00
|
|
|
return "", fmt.Errorf("unable to open %q: %w", path, err)
|
2024-05-31 00:11:02 +01:00
|
|
|
}
|
2024-08-15 15:24:25 +01:00
|
|
|
defer file.Close()
|
2024-05-31 00:11:02 +01:00
|
|
|
|
2024-08-15 15:24:25 +01:00
|
|
|
scanner := bufio.NewScanner(file)
|
|
|
|
|
|
|
|
var lines []string
|
|
|
|
|
|
|
|
for scanner.Scan() {
|
|
|
|
lines = append(lines, scanner.Text())
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
|
|
return "", fmt.Errorf("received an error after scanning the contents from %q: %w", path, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if lines[len(lines)-1] == "" {
|
|
|
|
lines = lines[:len(lines)-1]
|
|
|
|
}
|
|
|
|
|
|
|
|
return strings.Join(lines, "\n"), nil
|
2024-05-31 00:11:02 +01:00
|
|
|
}
|
2024-06-22 01:16:24 +01:00
|
|
|
|
|
|
|
func FileExists(path string) (bool, error) {
|
|
|
|
if _, err := os.Stat(path); err != nil {
|
|
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return false, fmt.Errorf("unable to check if the file exists: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return true, nil
|
|
|
|
}
|