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