github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/app/app.go (about)

     1  package app
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  	"runtime"
     7  
     8  	"gopkg.in/yaml.v2"
     9  
    10  	"github.com/machinefi/w3bstream/pkg/depends/conf/deploy"
    11  	"github.com/machinefi/w3bstream/pkg/depends/kit/logr"
    12  )
    13  
    14  type OptSetter = func(conf *Ctx)
    15  
    16  func WithName(name string) OptSetter { return func(c *Ctx) { c.name = name } }
    17  
    18  func WithVersion(version string) OptSetter { return func(c *Ctx) { c.version = version } }
    19  
    20  func WithFeat(feat string) OptSetter { return func(c *Ctx) { c.feat = feat } }
    21  
    22  func WithRoot(root string) OptSetter {
    23  	_, filename, _, _ := runtime.Caller(1)
    24  	return func(c *Ctx) {
    25  		info, err := os.Stat(filepath.Join(".", "config"))
    26  		if err == nil && info.IsDir() {
    27  			c.root = "."
    28  			return
    29  		}
    30  		c.root = filepath.Join(filepath.Dir(filename), root)
    31  	}
    32  }
    33  
    34  func WithLogger(l logr.Logger) OptSetter { return func(c *Ctx) { c.ctx = logr.WithLogger(c.ctx, l) } }
    35  
    36  func WithDeployer(deployers ...deploy.Deployer) OptSetter {
    37  	return func(c *Ctx) {
    38  		if c.deployers == nil {
    39  			c.deployers = make(map[string]deploy.Deployer)
    40  		}
    41  		for _, dpl := range deployers {
    42  			c.deployers[dpl.Name()] = dpl
    43  		}
    44  	}
    45  }
    46  
    47  func WriteYamlFile(filename string, v interface{}) error {
    48  	data, err := yaml.Marshal(v)
    49  	if err != nil {
    50  		return err
    51  	}
    52  	root := filepath.Dir(filename)
    53  	if root != "" {
    54  		if err = os.MkdirAll(root, os.ModePerm); err != nil {
    55  			return err
    56  		}
    57  	}
    58  	return os.WriteFile(filename, data, os.ModePerm)
    59  }