Package subcommand code
This commit is contained in:
121
cmd/util/util.go
Normal file
121
cmd/util/util.go
Normal file
@@ -0,0 +1,121 @@
|
||||
// Common utilities used by various subcommands
|
||||
package util
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
|
||||
"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/cache"
|
||||
"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/config"
|
||||
"github.com/pterm/pterm"
|
||||
)
|
||||
|
||||
type Utils struct {
|
||||
ctx context.Context
|
||||
config *config.Config
|
||||
logger *pterm.Logger
|
||||
cache *cache.Cache
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type UtilOpts struct {
|
||||
Ctx context.Context
|
||||
Config *config.Config
|
||||
Logger *pterm.Logger
|
||||
Cache *cache.Cache
|
||||
}
|
||||
|
||||
type utilsCtxKey uint8
|
||||
|
||||
const UtilsKey utilsCtxKey = iota
|
||||
|
||||
func AddToCtx(ctx context.Context, u *Utils) context.Context {
|
||||
return context.WithValue(ctx, UtilsKey, u)
|
||||
}
|
||||
|
||||
func MustFromCtx(ctx context.Context) *Utils {
|
||||
utils, err := FromCtx(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return utils
|
||||
}
|
||||
|
||||
func FromCtx(ctx context.Context) (*Utils, error) {
|
||||
utils, avail := ctx.Value(UtilsKey).(*Utils)
|
||||
if !avail {
|
||||
return nil, errors.New("invalid util in context")
|
||||
} else if utils == nil {
|
||||
return nil, errors.New("util never set in context")
|
||||
}
|
||||
|
||||
return utils, nil
|
||||
}
|
||||
|
||||
func (u *Utils) Init(opts *UtilOpts) {
|
||||
u.ctx = opts.Ctx
|
||||
u.SetConfig(opts.Config)
|
||||
u.SetLogger(opts.Logger)
|
||||
u.SetCache(opts.Cache)
|
||||
}
|
||||
|
||||
func (u *Utils) SetCache(c *cache.Cache) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
|
||||
u.Lock()
|
||||
defer u.Unlock()
|
||||
u.cache = c
|
||||
}
|
||||
|
||||
func (u *Utils) Cache() *cache.Cache {
|
||||
u.RLock()
|
||||
defer u.RUnlock()
|
||||
return u.cache
|
||||
}
|
||||
|
||||
func (u *Utils) SetLogger(l *pterm.Logger) {
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
|
||||
u.Lock()
|
||||
defer u.Unlock()
|
||||
u.logger = l
|
||||
}
|
||||
|
||||
func (u *Utils) Logger() *pterm.Logger {
|
||||
u.RLock()
|
||||
defer u.RUnlock()
|
||||
return u.logger
|
||||
}
|
||||
|
||||
func (u *Utils) SetConfig(conf *config.Config) {
|
||||
if conf == nil {
|
||||
return
|
||||
}
|
||||
|
||||
u.Lock()
|
||||
defer u.Unlock()
|
||||
u.config = conf
|
||||
}
|
||||
|
||||
func (u *Utils) Config() *config.Config {
|
||||
u.RLock()
|
||||
defer u.RUnlock()
|
||||
return u.config
|
||||
}
|
||||
|
||||
func (u *Utils) SetContext(c context.Context) {
|
||||
u.Lock()
|
||||
defer u.Unlock()
|
||||
u.ctx = c
|
||||
}
|
||||
|
||||
func (u *Utils) Context() context.Context {
|
||||
u.RLock()
|
||||
defer u.RUnlock()
|
||||
return u.ctx
|
||||
}
|
||||
Reference in New Issue
Block a user