ficsit-cli-flake/cli/disk/main.go

66 lines
1.4 KiB
Go
Raw Normal View History

2022-06-22 22:24:35 +00:00
package disk
import (
"fmt"
2022-06-22 22:24:35 +00:00
"io"
"log/slog"
2022-06-22 22:24:35 +00:00
"net/url"
"path/filepath"
2022-06-22 22:24:35 +00:00
)
type Disk interface {
// Exists checks if the provided file or directory exists
Exists(path string) (bool, error)
// 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)
// Write writes provided byte buffer to the path
2022-06-22 22:24:35 +00:00
Write(path string, data []byte) error
// Remove deletes the provided file or directory recursively
2022-06-22 22:24:35 +00:00
Remove(path string) error
// MkDir creates the provided directory recursively
2022-06-22 22:24:35 +00:00
MkDir(path string) error
// 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)
// 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 {
return nil, fmt.Errorf("failed to parse path: %w", err)
2022-06-22 22:24:35 +00:00
}
switch parsed.Scheme {
case "ftp":
slog.Info("connecting to ftp")
2022-06-22 22:24:35 +00:00
return newFTP(path)
case "sftp":
slog.Info("connecting to sftp")
2022-06-22 22:24:35 +00:00
return newSFTP(path)
}
slog.Info("using local disk", slog.String("path", path))
2022-06-22 22:24:35 +00:00
return newLocal(path)
}
// clean returns a unix-style path
func clean(path string) string {
return filepath.ToSlash(filepath.Clean(path))
}