github.com/octohelm/wagon@v0.0.0-20240308040401-88662650dc0b/pkg/engine/plan/task/core/fs.go (about)

     1  package core
     2  
     3  import (
     4  	"context"
     5  	"sync"
     6  
     7  	"dagger.io/dagger"
     8  	"github.com/octohelm/wagon/pkg/engine/daggerutil"
     9  	"github.com/opencontainers/go-digest"
    10  	"github.com/pkg/errors"
    11  )
    12  
    13  func init() {
    14  	DefaultFactory.Register(&FS{})
    15  }
    16  
    17  type FS struct {
    18  	Meta struct {
    19  		Fs struct {
    20  			ID string `json:"id,omitempty"`
    21  		} `json:"fs"`
    22  	} `json:"$wagon"`
    23  }
    24  
    25  func (fs *FS) SetDirectoryIDBy(ctx context.Context, d *dagger.Directory) error {
    26  	dir, err := d.Sync(ctx)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	id, err := dir.ID(ctx)
    31  	if err != nil || id == "" {
    32  		return errors.Wrap(err, "resolve dir id failed")
    33  	}
    34  	fs.SetDirectoryID(id)
    35  	return nil
    36  }
    37  
    38  var fsids = sync.Map{}
    39  
    40  func (fs *FS) SetDirectoryID(id dagger.DirectoryID) {
    41  	key := digest.FromString(string(id)).String()
    42  	fsids.Store(key, id)
    43  	fs.Meta.Fs.ID = key
    44  }
    45  
    46  func (fs *FS) DirectoryID() dagger.DirectoryID {
    47  	if k, ok := fsids.Load(fs.Meta.Fs.ID); ok {
    48  		return k.(dagger.DirectoryID)
    49  	}
    50  	return ""
    51  }
    52  
    53  func (fs *FS) LoadDirectory(c *dagger.Client) *dagger.Directory {
    54  	if id := fs.DirectoryID(); id != "" {
    55  		return c.LoadDirectoryFromID(id)
    56  	}
    57  	return c.Directory()
    58  }
    59  
    60  func (f *FS) Type() string {
    61  	return "fs"
    62  }
    63  
    64  func (f *FS) CanExport() bool {
    65  	return f.Meta.Fs.ID != ""
    66  }
    67  
    68  func (f *FS) ExportTo(ctx context.Context, localPath string) error {
    69  	return daggerutil.Do(ctx, func(c *dagger.Client) error {
    70  		_, err := f.LoadDirectory(c).Export(ctx, localPath)
    71  		return err
    72  	})
    73  }