enbas/internal/utilities/file.go
Dan Anglin c0f1f7d03a
All checks were successful
REUSE Compliance Check / check (push) Successful in 11s
feat: deleting statuses
This commit adds support for deleting statuses.

Before sending the delete request to the instance, Enbas will first
verify that the status that the user wants to delete actually belongs to
them.

The user has the option to save the text of the deleted status. This
will be written to a text file within the cache directory.

PR: #48
Resolves: #44
2024-08-16 18:53:08 +01:00

71 lines
1.4 KiB
Go

package utilities
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
)
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) {
file, err := os.Open(path)
if err != nil {
return "", fmt.Errorf("unable to open %q: %w", path, err)
}
defer file.Close()
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
}
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
}
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
}