pomme/internal/util/fs.go
2023-02-06 14:39:08 +00:00

40 lines
958 B
Go

package util
import (
"errors"
"fmt"
"os"
)
var errEmptyFile = errors.New("will not save empty file to FS")
func MakeLocal(filename, username string, buf []byte) error {
if _, err := os.Stat(fmt.Sprintf("/tmp/tmpfile-%s-%s", filename, username)); !os.IsNotExist(err) {
return fmt.Errorf("file %s already exists: %w", filename, err)
}
if len(buf) == 0 {
return errEmptyFile
}
f, err := os.Create("/tmp/tmpfile-" + filename + "-" + username) //nolint: gosec
// this is set to nolint because I am doing everything os.CreateTemp does but here since I don't like some of the limitations
if err != nil {
return fmt.Errorf("failed to write file locally: %w", err)
}
// close and remove the temporary file at the end of the program
defer func() {
if err = f.Close(); err != nil {
return
}
}()
err = os.WriteFile(f.Name(), buf, 0o600)
if err != nil {
return fmt.Errorf("failed to write file locally: %w", err)
}
return nil
}