common.go

  1package common
  2
  3import (
  4	"context"
  5	"fmt"
  6
  7	"github.com/charmbracelet/lipgloss"
  8	"github.com/charmbracelet/log"
  9	"github.com/charmbracelet/soft-serve/git"
 10	"github.com/charmbracelet/soft-serve/pkg/backend"
 11	"github.com/charmbracelet/soft-serve/pkg/config"
 12	"github.com/charmbracelet/soft-serve/pkg/ui/keymap"
 13	"github.com/charmbracelet/soft-serve/pkg/ui/styles"
 14	"github.com/charmbracelet/ssh"
 15	zone "github.com/lrstanley/bubblezone"
 16	"github.com/muesli/termenv"
 17)
 18
 19type contextKey struct {
 20	name string
 21}
 22
 23// Keys to use for context.Context.
 24var (
 25	ConfigKey = &contextKey{"config"}
 26	RepoKey   = &contextKey{"repo"}
 27)
 28
 29// Common is a struct all components should embed.
 30type Common struct {
 31	ctx           context.Context
 32	Width, Height int
 33	Styles        *styles.Styles
 34	KeyMap        *keymap.KeyMap
 35	Zone          *zone.Manager
 36	Output        *termenv.Output
 37	Logger        *log.Logger
 38	HideCloneCmd  bool
 39}
 40
 41// NewCommon returns a new Common struct.
 42func NewCommon(ctx context.Context, out *lipgloss.Renderer, width, height int) Common {
 43	if ctx == nil {
 44		ctx = context.TODO()
 45	}
 46	return Common{
 47		ctx:    ctx,
 48		Width:  width,
 49		Height: height,
 50		Output: out.Output(),
 51		Styles: styles.DefaultStyles(out),
 52		KeyMap: keymap.DefaultKeyMap(),
 53		Zone:   zone.New(),
 54		Logger: log.FromContext(ctx).WithPrefix("ui"),
 55	}
 56}
 57
 58// SetValue sets a value in the context.
 59func (c *Common) SetValue(key, value interface{}) {
 60	c.ctx = context.WithValue(c.ctx, key, value)
 61}
 62
 63// SetSize sets the width and height of the common struct.
 64func (c *Common) SetSize(width, height int) {
 65	c.Width = width
 66	c.Height = height
 67}
 68
 69// Context returns the context.
 70func (c *Common) Context() context.Context {
 71	return c.ctx
 72}
 73
 74// Config returns the server config.
 75func (c *Common) Config() *config.Config {
 76	return config.FromContext(c.ctx)
 77}
 78
 79// Backend returns the Soft Serve backend.
 80func (c *Common) Backend() *backend.Backend {
 81	return backend.FromContext(c.ctx)
 82}
 83
 84// Repo returns the repository.
 85func (c *Common) Repo() *git.Repository {
 86	v := c.ctx.Value(RepoKey)
 87	if r, ok := v.(*git.Repository); ok {
 88		return r
 89	}
 90	return nil
 91}
 92
 93// PublicKey returns the public key.
 94func (c *Common) PublicKey() ssh.PublicKey {
 95	v := c.ctx.Value(ssh.ContextKeyPublicKey)
 96	if p, ok := v.(ssh.PublicKey); ok {
 97		return p
 98	}
 99	return nil
100}
101
102// CloneCmd returns the clone command string.
103func (c *Common) CloneCmd(publicURL, name string) string {
104	if c.HideCloneCmd {
105		return ""
106	}
107	return fmt.Sprintf("git clone %s", RepoURL(publicURL, name))
108}