86 lines
1.9 KiB
Go
86 lines
1.9 KiB
Go
|
// Copyright Earl Warren <contact@earl-warren.org>
|
||
|
// Copyright Loïc Dachary <loic@dachary.org>
|
||
|
// SPDX-License-Identifier: MIT
|
||
|
|
||
|
package filesystem
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"io"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
|
||
|
"code.forgejo.org/f3/gof3/v3/f3"
|
||
|
"code.forgejo.org/f3/gof3/v3/id"
|
||
|
"code.forgejo.org/f3/gof3/v3/tree/generic"
|
||
|
)
|
||
|
|
||
|
type assetDriver struct {
|
||
|
nodeDriver
|
||
|
}
|
||
|
|
||
|
func newAssetDriver(content f3.Interface) generic.NodeDriverInterface {
|
||
|
n := newNodeDriver(content).(*nodeDriver)
|
||
|
a := &assetDriver{
|
||
|
nodeDriver: *n,
|
||
|
}
|
||
|
return a
|
||
|
}
|
||
|
|
||
|
func (o *assetDriver) getPath() string {
|
||
|
f := o.nodeDriver.content.(*f3.ReleaseAsset)
|
||
|
options := o.GetTreeDriver().(*treeDriver).options
|
||
|
return filepath.Join(options.Directory, "objects", f.SHA256[0:2], f.SHA256[2:4], f.SHA256)
|
||
|
}
|
||
|
|
||
|
func (o *assetDriver) save(ctx context.Context) {
|
||
|
assetFormat := o.nodeDriver.content.(*f3.ReleaseAsset)
|
||
|
objectsHelper := o.getF3Tree().GetObjectsHelper()
|
||
|
sha, tmpPath := objectsHelper.Save(assetFormat.DownloadFunc())
|
||
|
assetFormat.SHA256 = sha
|
||
|
path := o.getPath()
|
||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
if err := os.Rename(tmpPath, path); err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
o.GetNode().Trace("%s %s", assetFormat.SHA256, path)
|
||
|
}
|
||
|
|
||
|
func (o *assetDriver) setDownloadFunc() {
|
||
|
f := o.nodeDriver.content.(*f3.ReleaseAsset)
|
||
|
f.DownloadFunc = func() io.ReadCloser {
|
||
|
f, err := os.Open(o.getPath())
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
return f
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (o *assetDriver) Put(ctx context.Context) id.NodeID {
|
||
|
return o.upsert(ctx)
|
||
|
}
|
||
|
|
||
|
func (o *assetDriver) Patch(ctx context.Context) {
|
||
|
o.upsert(ctx)
|
||
|
}
|
||
|
|
||
|
func (o *assetDriver) upsert(ctx context.Context) id.NodeID {
|
||
|
assetFormat := o.nodeDriver.content.(*f3.ReleaseAsset)
|
||
|
if assetFormat.SHA256 != "" {
|
||
|
o.save(ctx)
|
||
|
}
|
||
|
o.setDownloadFunc()
|
||
|
return o.nodeDriver.upsert(ctx)
|
||
|
}
|
||
|
|
||
|
func (o *assetDriver) Get(ctx context.Context) bool {
|
||
|
if o.nodeDriver.Get(ctx) {
|
||
|
o.setDownloadFunc()
|
||
|
return true
|
||
|
}
|
||
|
return false
|
||
|
}
|