debanator/backend.go

79 lines
1.6 KiB
Go
Raw Normal View History

2023-05-01 01:22:25 +01:00
package debanator
import (
"io"
"io/fs"
2023-05-01 21:28:28 +01:00
"net/http"
2023-05-01 01:22:25 +01:00
"os"
"path"
2023-05-01 21:28:28 +01:00
"path/filepath"
2023-05-01 01:22:25 +01:00
"strings"
log "github.com/sirupsen/logrus"
)
// A backend to search for packages in
type Backend interface {
2023-05-01 21:28:28 +01:00
GetFiles() ([]DebFile, error)
ServeFiles(string) http.Handler
2023-05-01 01:22:25 +01:00
}
2023-05-01 21:28:28 +01:00
type ReaderAtCloser interface {
io.ReaderAt
io.ReadCloser
}
// An abstract interface for reading a debfile. This could be coming from the local fs,
// a remote webdav share, etc...
type DebFile interface {
GetReader() (ReaderAtCloser, error)
GetName() string
}
2023-05-01 01:22:25 +01:00
type FileBackend struct {
path string
}
2023-05-01 21:28:28 +01:00
// A deb file existing on the local filesystem
type fsDebFile struct {
path string
}
func (f fsDebFile) GetReader() (ReaderAtCloser, error) {
return os.Open(f.path)
}
func (f fsDebFile) GetName() string {
_, name := filepath.Split(f.path)
return name
}
2023-05-01 01:22:25 +01:00
func NewFileBackend(path string) FileBackend {
return FileBackend{path}
}
2023-05-01 21:28:28 +01:00
func (fb FileBackend) ServeFiles(prefix string) http.Handler {
return http.StripPrefix(path.Join(prefix, "pool"), http.FileServer(http.Dir(fb.path)))
2023-05-01 01:22:25 +01:00
}
2023-05-01 21:28:28 +01:00
func (fb FileBackend) GetFiles() ([]DebFile, error) {
var debs []DebFile
fs.WalkDir(os.DirFS(fb.path), ".", func(dirpath string, dir fs.DirEntry, err error) error {
2023-05-01 01:22:25 +01:00
if err != nil {
log.WithFields(log.Fields{
2023-05-01 21:28:28 +01:00
"path": dirpath,
2023-05-01 01:22:25 +01:00
"error": err,
}).Warn("Error scanning for debs")
return nil
}
2023-05-01 21:28:28 +01:00
if !dir.IsDir() && strings.HasSuffix(dir.Name(), ".deb") {
debs = append(debs, DebFile(fsDebFile{
filepath.Join(fb.path, dirpath),
}))
2023-05-01 01:22:25 +01:00
}
return nil
})
2023-05-01 21:28:28 +01:00
log.Infof("got files: %v", debs)
return debs, nil
2023-05-01 01:22:25 +01:00
}