2022-06-22 22:24:35 +00:00
|
|
|
package disk
|
|
|
|
|
|
|
|
import (
|
2023-12-16 14:19:53 +00:00
|
|
|
"fmt"
|
2022-06-22 22:24:35 +00:00
|
|
|
"io"
|
2023-12-16 14:19:53 +00:00
|
|
|
"log/slog"
|
2022-06-22 22:24:35 +00:00
|
|
|
"net/url"
|
2023-12-28 00:13:09 +00:00
|
|
|
"path/filepath"
|
2022-06-22 22:24:35 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Disk interface {
|
2023-12-06 19:37:33 +00:00
|
|
|
// Exists checks if the provided file or directory exists
|
2023-12-28 00:13:09 +00:00
|
|
|
Exists(path string) (bool, error)
|
2023-12-06 19:37:33 +00:00
|
|
|
|
|
|
|
// Read returns the entire file as a byte buffer
|
|
|
|
//
|
|
|
|
// Returns error if provided path is not a file
|
2022-06-22 22:24:35 +00:00
|
|
|
Read(path string) ([]byte, error)
|
2023-12-06 19:37:33 +00:00
|
|
|
|
|
|
|
// Write writes provided byte buffer to the path
|
2022-06-22 22:24:35 +00:00
|
|
|
Write(path string, data []byte) error
|
2023-12-06 19:37:33 +00:00
|
|
|
|
|
|
|
// Remove deletes the provided file or directory recursively
|
2022-06-22 22:24:35 +00:00
|
|
|
Remove(path string) error
|
2023-12-06 19:37:33 +00:00
|
|
|
|
|
|
|
// MkDir creates the provided directory recursively
|
2022-06-22 22:24:35 +00:00
|
|
|
MkDir(path string) error
|
2023-12-06 19:37:33 +00:00
|
|
|
|
|
|
|
// ReadDir returns all entries within the directory
|
|
|
|
//
|
|
|
|
// Returns error if provided path is not a directory
|
2022-06-22 22:24:35 +00:00
|
|
|
ReadDir(path string) ([]Entry, error)
|
2023-12-06 19:37:33 +00:00
|
|
|
|
|
|
|
// Open opens provided path for writing
|
2022-06-22 22:24:35 +00:00
|
|
|
Open(path string, flag int) (io.WriteCloser, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type Entry interface {
|
|
|
|
IsDir() bool
|
|
|
|
Name() string
|
|
|
|
}
|
|
|
|
|
|
|
|
func FromPath(path string) (Disk, error) {
|
|
|
|
parsed, err := url.Parse(path)
|
|
|
|
if err != nil {
|
2023-12-16 14:19:53 +00:00
|
|
|
return nil, fmt.Errorf("failed to parse path: %w", err)
|
2022-06-22 22:24:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
switch parsed.Scheme {
|
|
|
|
case "ftp":
|
2023-12-28 00:13:09 +00:00
|
|
|
slog.Info("connecting to ftp")
|
2022-06-22 22:24:35 +00:00
|
|
|
return newFTP(path)
|
|
|
|
case "sftp":
|
2023-12-28 00:13:09 +00:00
|
|
|
slog.Info("connecting to sftp")
|
2022-06-22 22:24:35 +00:00
|
|
|
return newSFTP(path)
|
|
|
|
}
|
|
|
|
|
2023-12-16 14:19:53 +00:00
|
|
|
slog.Info("using local disk", slog.String("path", path))
|
2022-06-22 22:24:35 +00:00
|
|
|
return newLocal(path)
|
|
|
|
}
|
2023-12-28 00:13:09 +00:00
|
|
|
|
|
|
|
// clean returns a unix-style path
|
|
|
|
func clean(path string) string {
|
|
|
|
return filepath.ToSlash(filepath.Clean(path))
|
|
|
|
}
|