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"
|
2024-08-15 21:40:17 +01:00
|
|
|
"strings"
|
2024-05-31 00:11:02 +01:00
|
|
|
)
|
|
|
|
|
2024-08-15 21:40:17 +01:00
|
|
|
const filePrefix string = "file@"
|
|
|
|
|
|
|
|
func ReadContents(text string) (string, error) {
|
|
|
|
if !strings.HasPrefix(text, filePrefix) {
|
|
|
|
return text, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return ReadTextFile(strings.TrimPrefix(text, filePrefix))
|
|
|
|
}
|
|
|
|
|
|
|
|
func ReadTextFile(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
|
|
|
|
}
|
2024-08-16 18:53:08 +01:00
|
|
|
|
|
|
|
func SaveTextToFile(path, text string) error {
|
|
|
|
file, err := os.Create(path)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to open %q: %w", path, err)
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
if _, err := fmt.Fprint(file, text); err != nil {
|
|
|
|
return fmt.Errorf("received an error writing the text to the file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|