buildr/internal/plugins/downloader.go
Peter 34c431790e
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/tag Build is failing
refactor: use connect-go instead of regular Google gRPC
- support binary name for plugins
- register plugins for container jobs
2023-09-12 18:43:34 +02:00

88 lines
1.9 KiB
Go

package plugins
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"code.icb4dc0.de/buildr/buildr/internal/ioutils"
)
type Downloader interface {
Download(ctx context.Context, target string, src *url.URL) error
}
var (
ErrUnsupportedProtocol = errors.New("unsupported protocol")
_ Downloader = (*GenericDownloader)(nil)
_ Downloader = (*HTTPDownloader)(nil)
_ Downloader = (*FileDownloader)(nil)
)
type GenericDownloader map[string]Downloader
func (g GenericDownloader) Download(ctx context.Context, target string, src *url.URL) error {
if protocolDownloader, ok := g[src.Scheme]; !ok {
return fmt.Errorf("%w: %s", ErrUnsupportedProtocol, src.Scheme)
} else {
return protocolDownloader.Download(ctx, target, src)
}
}
type HTTPDownloader struct {
Client *http.Client
}
func (h HTTPDownloader) Download(ctx context.Context, target string, src *url.URL) (err error) {
var req *http.Request
req, err = http.NewRequest(http.MethodGet, src.String(), nil)
if err != nil {
return err
}
client := h.Client
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req.WithContext(ctx))
if err != nil {
return err
}
defer func() {
err = errors.Join(err, resp.Body.Close())
}()
var out io.WriteCloser
if out, err = os.Create(target); err != nil {
return err
}
defer func() {
err = errors.Join(err, out.Close())
}()
_, err = ioutils.CopyWithPooledBuffer(out, resp.Body)
return err
}
type FileDownloader struct{}
func (f FileDownloader) Download(_ context.Context, target string, src *url.URL) error {
if src.Scheme != "file" {
return fmt.Errorf("%w: %s", ErrUnsupportedProtocol, src.Scheme)
}
if _, err := os.Stat(target); err == nil {
if err = os.Remove(target); err != nil {
return err
}
}
return os.Link(src.Path, target)
}