From a10a604018d0cb07babfe218d9fb2e00e1c8ae3b Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sat, 7 May 2022 13:17:18 -0600 Subject: Refactor how data dir is initialized --- srv/src/cfg/data_dir.go | 74 ++++++++++++++++++++++++++++++++++++++++++++ srv/src/cfg/mediocre_blog.go | 9 ++++++ 2 files changed, 83 insertions(+) create mode 100644 srv/src/cfg/data_dir.go create mode 100644 srv/src/cfg/mediocre_blog.go (limited to 'srv/src/cfg') diff --git a/srv/src/cfg/data_dir.go b/srv/src/cfg/data_dir.go new file mode 100644 index 0000000..649bc15 --- /dev/null +++ b/srv/src/cfg/data_dir.go @@ -0,0 +1,74 @@ +package cfg + +import ( + "context" + "fmt" + "os" + + "github.com/mediocregopher/mediocre-go-lib/v2/mctx" +) + +// DataDir manages the blog's data directory. +type DataDir struct { + Path string + + deleteOnClose bool +} + +// Init initializes the data directory, creating the directory named at path if +// it doesn't exist. +// +// If Path is not set, then a temporary directory will be created and its path +// set to the Path field. This directory will be removed when Close is called. +func (d *DataDir) Init() error { + if d.Path == "" { + + d.deleteOnClose = true + var err error + + if d.Path, err = os.MkdirTemp("", "mediocre-blog-data-*"); err != nil { + return fmt.Errorf("creating temporary directory: %w", err) + } + + return nil + } + + if err := os.MkdirAll(d.Path, 0700); err != nil { + return fmt.Errorf( + "creating directory (and parents) of %q: %w", + d.Path, + err, + ) + } + + return nil +} + +// SetupCfg implement the cfg.Cfger interface. +func (d *DataDir) SetupCfg(cfg *Cfg) { + + cfg.StringVar(&d.Path, "data-dir", "", "Directory to use for persistent storage. If unset a temp directory will be created, and will be deleted when the process exits.") + + cfg.OnInit(func(ctx context.Context) error { + return d.Init() + }) +} + +// Annotate implements mctx.Annotator interface. +func (d *DataDir) Annotate(a mctx.Annotations) { + a["dataDirPath"] = d.Path +} + +// Close cleans up any temporary state created by DataDir. +func (d *DataDir) Close() error { + + if !d.deleteOnClose { + return nil + } + + if err := os.RemoveAll(d.Path); err != nil { + return fmt.Errorf("removing temp dir %q: %w", d.Path, err) + } + + return nil +} diff --git a/srv/src/cfg/mediocre_blog.go b/srv/src/cfg/mediocre_blog.go new file mode 100644 index 0000000..98fe08c --- /dev/null +++ b/srv/src/cfg/mediocre_blog.go @@ -0,0 +1,9 @@ +package cfg + +// this file contains functionality specific to the mediocre blog. + +// NewBlogCfg returns a Cfg specifically configured for mediocre blog processes. +func NewBlogCfg(params Params) *Cfg { + params.EnvPrefix = "MEDIOCRE_BLOG" + return New(params) +} -- cgit v1.2.3