wg-portal/internal/adapters/filesystem.go

55 lines
1.2 KiB
Go
Raw Normal View History

2023-02-12 23:13:04 +01:00
package adapters
import (
2023-07-24 21:00:45 +02:00
"fmt"
"github.com/sirupsen/logrus"
2023-02-12 23:13:04 +01:00
"io"
"os"
"path/filepath"
)
2023-07-24 21:00:45 +02:00
type FilesystemRepo struct {
2023-02-12 23:13:04 +01:00
basePath string
}
2023-07-24 21:00:45 +02:00
func NewFileSystemRepository(basePath string) (*FilesystemRepo, error) {
if basePath == "" {
return nil, nil // no path, return empty repository
}
r := &FilesystemRepo{basePath: basePath}
2023-02-12 23:13:04 +01:00
if err := os.MkdirAll(r.basePath, os.ModePerm); err != nil {
2023-07-24 21:00:45 +02:00
return nil, fmt.Errorf("failed to create base directory %s: %w", basePath, err)
2023-02-12 23:13:04 +01:00
}
return r, nil
}
2023-07-24 21:00:45 +02:00
func (r *FilesystemRepo) WriteFile(path string, contents io.Reader) error {
2023-02-12 23:13:04 +01:00
filePath := filepath.Join(r.basePath, path)
2023-07-24 21:00:45 +02:00
parentDirectory := filepath.Dir(filePath)
2023-02-12 23:13:04 +01:00
2023-07-24 21:00:45 +02:00
if err := os.MkdirAll(parentDirectory, os.ModePerm); err != nil {
return fmt.Errorf("failed to create parent directory %s: %w", parentDirectory, err)
2023-02-12 23:13:04 +01:00
}
file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if err != nil {
2023-07-24 21:00:45 +02:00
return fmt.Errorf("failed to open file %s: %w", file.Name(), err)
2023-02-12 23:13:04 +01:00
}
2023-07-24 21:00:45 +02:00
defer func(file *os.File) {
if err := file.Close(); err != nil {
logrus.Errorf("failed to close file %s: %v", file.Name(), err)
}
}(file)
2023-02-12 23:13:04 +01:00
_, err = io.Copy(file, contents)
if err != nil {
2023-07-24 21:00:45 +02:00
return fmt.Errorf("failed to write file contents: %w", err)
2023-02-12 23:13:04 +01:00
}
return nil
}