app

package
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 12, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package app provides the main application logic for memtui. This file serves as the package entry point. The implementation is split across multiple files following the single responsibility principle:

  • model.go: Model struct, State, FocusMode, Styles definitions
  • init.go: NewModel, Init, accessors, updateComponentSizes
  • update.go: Update method and message handlers
  • keyhandler.go: handleKeyMsg, handleFilterInput, handleCommandExecute
  • commands.go: tea.Cmd functions (connectCmd, loadKeysCmd, etc.)
  • view.go: View method and rendering functions

Package app provides server switching functionality for memtui. This file contains messages, commands, and state management for connecting to and switching between multiple Memcached servers.

Index

Constants

View Source
const MaxKeyLength = 250

MaxKeyLength is the maximum length of a Memcached key (250 bytes)

Variables

This section is empty.

Functions

func BatchDeleteCmd

func BatchDeleteCmd(client BatchDeleter, keys []string) tea.Cmd

BatchDeleteCmd creates a tea.Cmd that deletes multiple keys from Memcached. Returns BatchDeleteResultMsg with the results of all deletion attempts.

func CreateBatchDeleteDialog

func CreateBatchDeleteDialog(_ int) *dialog.InputDialog

CreateBatchDeleteDialog creates an input dialog for batch delete confirmation. The dialog requires the user to type "DELETE" to confirm the operation.

func CreateBatchDeleteDialogWithKeys

func CreateBatchDeleteDialogWithKeys(keys []string) *dialog.InputDialog

CreateBatchDeleteDialogWithKeys creates an input dialog with the keys context attached. This allows the keys to be retrieved when the user confirms the deletion.

func CreateDeleteConfirmDialog

func CreateDeleteConfirmDialog(key string) *dialog.ConfirmDialog

CreateDeleteConfirmDialog creates a confirmation dialog for key deletion. The dialog includes the key name in the message and stores the key in the context for retrieval after confirmation.

func CreateNewKeyDialog

func CreateNewKeyDialog() *dialog.InputDialog

CreateNewKeyDialog creates an input dialog for entering a new key name. The dialog includes validation for Memcached key requirements.

func CreateValueInputDialog

func CreateValueInputDialog(key string) *dialog.InputDialog

CreateValueInputDialog creates an input dialog for entering a value for a key. The key name is stored in the context for retrieval after input is submitted.

func DeleteKeyCmd

func DeleteKeyCmd(client Deleter, key string) tea.Cmd

DeleteKeyCmd creates a tea.Cmd that deletes a key from Memcached. Returns KeyDeletedMsg on success or DeleteErrorMsg on failure.

func DisconnectServerCmd

func DisconnectServerCmd(connector ServerConnector, name, address string) tea.Cmd

DisconnectServerCmd creates a command that disconnects from the current server.

func ExtractBatchDeleteContext

func ExtractBatchDeleteContext(ctx interface{}) ([]string, bool)

ExtractBatchDeleteContext extracts the keys from a BatchDeleteContext. Returns the keys slice and a boolean indicating success.

func ExtractDeleteContext

func ExtractDeleteContext(ctx interface{}) (string, bool)

ExtractDeleteContext extracts the key from a ConfirmResultMsg context. Returns the key string and a boolean indicating success.

func ExtractNewKeyContext

func ExtractNewKeyContext(ctx interface{}) (string, bool)

ExtractNewKeyContext extracts the key from an input result context. Returns the key string and a boolean indicating success.

func HandleBatchDeleteConfirm

func HandleBatchDeleteConfirm(client BatchDeleter, msg BatchDeleteMsg) tea.Cmd

HandleBatchDeleteConfirm processes a batch delete confirmation and returns the command. This is called after the user confirms deletion by typing "DELETE".

func HandleDeleteConfirm

func HandleDeleteConfirm(client Deleter, msg DeleteConfirmMsg) tea.Cmd

HandleDeleteConfirm processes a delete confirmation and returns the appropriate command. This is called after the user confirms deletion in the dialog.

func HandleNewKeyConfirm

func HandleNewKeyConfirm(client Setter, req NewKeyRequest) tea.Cmd

HandleNewKeyConfirm processes a new key request and returns the appropriate command. This is called after the user has entered both key name and value.

func HandleServerSwitch

func HandleServerSwitch(msg tea.Msg, connector ServerConnector, timeout time.Duration) tea.Cmd

HandleServerSwitch processes server-related messages and returns the appropriate command. This function is designed to be called from the main application Update function.

func NewKeyCmd

func NewKeyCmd(client Setter, req NewKeyRequest) tea.Cmd

NewKeyCmd creates a tea.Cmd that creates a new key in Memcached. Returns KeyCreatedMsg on success or NewKeyErrorMsg on failure.

func PingServerCmd

func PingServerCmd(connector ServerConnector, name, address string, timeout time.Duration) tea.Cmd

PingServerCmd creates a command that pings the current server to check connectivity.

func ProcessKeyNameInput

func ProcessKeyNameInput(result dialog.InputResultMsg) (string, error)

ProcessKeyNameInput processes the result of the key name input dialog. Returns the key name if valid, or an error if canceled or invalid.

func ProcessValueInput

func ProcessValueInput(result dialog.InputResultMsg) (string, string, error)

ProcessValueInput processes the result of the value input dialog. Returns the key name from context and the value, or an error if canceled.

func SwitchServerCmd

func SwitchServerCmd(connector ServerConnector, name, address string, timeout time.Duration) tea.Cmd

SwitchServerCmd creates a command that switches to a different server. It connects to the new server and returns the appropriate message.

func ValidateBatchDeleteInput

func ValidateBatchDeleteInput(input string) error

ValidateBatchDeleteInput validates that the input matches "DELETE" exactly. This is a safety measure to prevent accidental batch deletions.

func ValidateKeyName

func ValidateKeyName(key string) error

ValidateKeyName validates a Memcached key name. Returns an error if the key is invalid according to Memcached rules: - Key cannot be empty - Key cannot contain spaces, newlines, or control characters - Key cannot exceed 250 bytes

Types

type BatchDeleteContext

type BatchDeleteContext struct {
	Keys []string
}

BatchDeleteContext holds contextual information for a batch delete operation. Used to pass data between dialog confirmation and batch delete execution.

type BatchDeleteMsg

type BatchDeleteMsg struct {
	Keys []string
}

BatchDeleteMsg is the message that triggers a batch delete operation.

func ProcessBatchInputResult

func ProcessBatchInputResult(result dialog.InputResultMsg) *BatchDeleteMsg

ProcessBatchInputResult processes an input dialog result for batch deletion. Returns a BatchDeleteMsg if confirmed with "DELETE", or nil if canceled or invalid.

type BatchDeleteRequest

type BatchDeleteRequest struct {
	Keys []string
}

BatchDeleteRequest holds the request parameters for batch deletion.

type BatchDeleteResultMsg

type BatchDeleteResultMsg struct {
	Deleted []string         // Keys that were successfully deleted
	Failed  []string         // Keys that failed to delete
	Errors  map[string]error // Error messages for failed keys
}

BatchDeleteResultMsg holds the result of a batch delete operation.

type BatchDeleteSummary

type BatchDeleteSummary struct {
	TotalCount    int      // Total number of keys attempted
	DeletedCount  int      // Number of successfully deleted keys
	FailedCount   int      // Number of failed deletions
	AllSucceeded  bool     // True if all deletions succeeded
	HasErrors     bool     // True if any deletion failed
	ShouldRefresh bool     // Whether the key list should be refreshed
	FailedKeys    []string // List of keys that failed to delete
}

BatchDeleteSummary provides a summary of the batch delete operation result.

func HandleBatchDeleteResult

func HandleBatchDeleteResult(msg BatchDeleteResultMsg) BatchDeleteSummary

HandleBatchDeleteResult processes a BatchDeleteResultMsg and returns a summary.

func (BatchDeleteSummary) String

func (s BatchDeleteSummary) String() string

String returns a human-readable summary of the batch delete result.

type BatchDeleter

type BatchDeleter interface {
	Delete(key string) error
}

BatchDeleter is an interface for deleting keys from Memcached. This allows for easy mocking in tests.

type ClipboardCopyMsg

type ClipboardCopyMsg struct{}

ClipboardCopyMsg is sent when clipboard copy is successful

type ClipboardErrorMsg

type ClipboardErrorMsg struct {
	Err error
}

ClipboardErrorMsg is sent when clipboard copy fails

type ConnectedMsg

type ConnectedMsg struct {
	Version          string
	SupportsMetadump bool
}

ConnectedMsg is sent when connection is established

type ConnectionInfo

type ConnectionInfo struct {
	Connected bool
	Name      string
	Address   string
	Version   string
	Switching bool
	Error     error
}

ConnectionInfo returns a snapshot of the current connection information

type DeleteConfirmMsg

type DeleteConfirmMsg struct {
	Key string
}

DeleteConfirmMsg is sent when user confirms deletion

func ProcessConfirmResult

func ProcessConfirmResult(result dialog.ConfirmResultMsg) *DeleteConfirmMsg

ProcessConfirmResult processes a confirmation dialog result for deletion. Returns a DeleteConfirmMsg if confirmed, or nil if canceled.

type DeleteContext

type DeleteContext struct {
	Key string
}

DeleteContext holds contextual information for a delete operation. Used to pass data between dialog confirmation and delete execution.

type DeleteErrorMsg

type DeleteErrorMsg struct {
	Key string
	Err error
}

DeleteErrorMsg is sent when key deletion fails

type DeleteKeyMsg

type DeleteKeyMsg struct {
	Key string
}

DeleteKeyMsg is sent when user requests to delete a key (before confirmation)

type DeleteResult

type DeleteResult struct {
	ShouldRefresh bool   // Whether the key list should be refreshed
	Error         string // Error message if deletion failed
	DeletedKey    string // Key that was successfully deleted
	FailedKey     string // Key that failed to delete
}

DeleteResult holds the result of a delete operation for UI handling.

func HandleDeleteResult

func HandleDeleteResult(msg tea.Msg) DeleteResult

HandleDeleteResult processes the result of a delete operation. Returns a DeleteResult struct with information about what happened and what the UI should do next.

type Deleter

type Deleter interface {
	Delete(key string) error
}

Deleter is an interface for deleting keys from Memcached. This allows for easy mocking in tests.

type ErrorMsg

type ErrorMsg struct {
	Err string
}

ErrorMsg is sent when an error occurs

type FocusMode

type FocusMode int

FocusMode represents which component has focus

const (
	// FocusKeyList indicates the key list has focus
	FocusKeyList FocusMode = iota
	// FocusViewer indicates the value viewer has focus
	FocusViewer
	// FocusDialog indicates a dialog has focus
	FocusDialog
	// FocusEditor indicates the editor has focus
	FocusEditor
	// FocusCommandPalette indicates the command palette has focus
	FocusCommandPalette
	// FocusHelp indicates the help view has focus
	FocusHelp
	// FocusFilter indicates the filter input has focus
	FocusFilter
)

Focus modes for UI components

type KeyCreatedMsg

type KeyCreatedMsg struct {
	Key string
}

KeyCreatedMsg is sent when a key is successfully created.

type KeyDeletedMsg

type KeyDeletedMsg struct {
	Key string
}

KeyDeletedMsg is sent when a key is successfully deleted

type KeySelectedMsg

type KeySelectedMsg struct {
	Key models.KeyInfo
}

KeySelectedMsg is sent when a key is selected

type KeysLoadedMsg

type KeysLoadedMsg struct {
	Keys []models.KeyInfo
}

KeysLoadedMsg is sent when keys are loaded

type Model

type Model struct {
	// contains filtered or unexported fields
}

Model is the main Bubble Tea model

func NewModel

func NewModel(addr string) *Model

NewModel creates a new app model with default settings

func NewModelWithConfig

func NewModelWithConfig(addr string, cfg *config.Config) *Model

NewModelWithConfig creates a new app model with the given configuration

func (*Model) Error

func (m *Model) Error() string

Error returns the error message

func (*Model) Focus

func (m *Model) Focus() FocusMode

Focus returns the current focus mode

func (*Model) Height

func (m *Model) Height() int

Height returns the terminal height

func (*Model) Init

func (m *Model) Init() tea.Cmd

Init initializes the model

func (*Model) Keys

func (m *Model) Keys() []models.KeyInfo

Keys returns the loaded keys

func (*Model) SetFocus

func (m *Model) SetFocus(focus FocusMode)

SetFocus sets the focus mode (for testing)

func (*Model) State

func (m *Model) State() State

State returns the current state

func (*Model) Update

func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd)

Update handles messages

func (*Model) View

func (m *Model) View() string

View renders the UI

func (*Model) Width

func (m *Model) Width() int

Width returns the terminal width

type NewKeyContext

type NewKeyContext struct {
	Key string
}

NewKeyContext holds contextual information for a new key operation. Used to pass data between dialog confirmation and key creation.

type NewKeyErrorMsg

type NewKeyErrorMsg struct {
	Key string
	Err error
}

NewKeyErrorMsg is sent when key creation fails.

type NewKeyMsg

type NewKeyMsg struct{}

NewKeyMsg is sent when user requests to create a new key (triggers dialog).

type NewKeyRequest

type NewKeyRequest struct {
	Key   string // The key name
	Value string // The initial value
	TTL   int32  // Time to live in seconds (0 = no expiration)
	Flags uint32 // Optional flags for the item
}

NewKeyRequest holds the parameters for creating a new key.

func ProcessNewKeyInputResult

func ProcessNewKeyInputResult(key, value string, ttl int32) *NewKeyRequest

ProcessNewKeyInputResult creates a NewKeyRequest from user input. This is called after the user has entered both key name and value.

type NewKeyResult

type NewKeyResult struct {
	ShouldRefresh bool   // Whether the key list should be refreshed
	Error         string // Error message if creation failed
	CreatedKey    string // Key that was successfully created
	FailedKey     string // Key that failed to create
}

NewKeyResult holds the result of a new key operation for UI handling.

func HandleNewKeyResult

func HandleNewKeyResult(msg tea.Msg) NewKeyResult

HandleNewKeyResult processes the result of a new key operation. Returns a NewKeyResult struct with information about what happened and what the UI should do next.

type ServerConnectedMsg

type ServerConnectedMsg struct {
	Address string // Server address
	Name    string // Human-readable server name
	Version string // Memcached server version
}

ServerConnectedMsg is sent when a server connection is established successfully

type ServerConnectionState

type ServerConnectionState struct {
	// contains filtered or unexported fields
}

ServerConnectionState tracks the current server connection state. This is thread-safe and can be used to track connection status from multiple goroutines if needed.

func NewServerConnectionState

func NewServerConnectionState() *ServerConnectionState

NewServerConnectionState creates a new connection state tracker

func (*ServerConnectionState) ClearError

func (s *ServerConnectionState) ClearError()

ClearError clears the last error

func (*ServerConnectionState) CurrentAddress

func (s *ServerConnectionState) CurrentAddress() string

CurrentAddress returns the address of the currently connected server

func (*ServerConnectionState) CurrentName

func (s *ServerConnectionState) CurrentName() string

CurrentName returns the name of the currently connected server

func (*ServerConnectionState) CurrentVersion

func (s *ServerConnectionState) CurrentVersion() string

CurrentVersion returns the version of the currently connected server

func (*ServerConnectionState) Info

Info returns a snapshot of the current connection state

func (*ServerConnectionState) IsConnected

func (s *ServerConnectionState) IsConnected() bool

IsConnected returns true if currently connected to a server

func (*ServerConnectionState) IsSwitching

func (s *ServerConnectionState) IsSwitching() bool

IsSwitching returns true if currently switching servers

func (*ServerConnectionState) LastError

func (s *ServerConnectionState) LastError() error

LastError returns the last error that occurred

func (*ServerConnectionState) SetConnected

func (s *ServerConnectionState) SetConnected(name, address, version string)

SetConnected updates the state to indicate a successful connection

func (*ServerConnectionState) SetDisconnected

func (s *ServerConnectionState) SetDisconnected()

SetDisconnected updates the state to indicate disconnection

func (*ServerConnectionState) SetError

func (s *ServerConnectionState) SetError(err error)

SetError updates the state to indicate an error

func (*ServerConnectionState) SetSwitching

func (s *ServerConnectionState) SetSwitching(name, address string)

SetSwitching updates the state to indicate a server switch is in progress

func (*ServerConnectionState) SwitchingTo

func (s *ServerConnectionState) SwitchingTo() string

SwitchingTo returns the address being switched to

type ServerConnector

type ServerConnector interface {
	// Connect establishes a connection to the specified server address
	Connect(ctx context.Context, address string) error

	// Disconnect closes the current connection
	Disconnect() error

	// Ping checks if the current connection is alive
	Ping(ctx context.Context) error

	// Version returns the Memcached server version
	Version(ctx context.Context) (string, error)

	// IsConnected returns true if currently connected
	IsConnected() bool

	// Address returns the current server address
	Address() string
}

ServerConnector defines the interface for connecting to Memcached servers. This interface allows for mocking in tests and decouples the server switching logic from the actual client implementation.

type ServerDisconnectedMsg

type ServerDisconnectedMsg struct {
	Address string // Server address that was disconnected
	Name    string // Human-readable server name
}

ServerDisconnectedMsg is sent when a server is disconnected

type ServerErrorMsg

type ServerErrorMsg struct {
	Address string // Server address that was being accessed
	Name    string // Human-readable server name
	Err     error  // The error that occurred
}

ServerErrorMsg is sent when a server operation fails

func (ServerErrorMsg) Error

func (m ServerErrorMsg) Error() string

Error returns the error message

type ServerPingResultMsg

type ServerPingResultMsg struct {
	Address string        // Server address
	Name    string        // Human-readable server name
	Success bool          // Whether the ping was successful
	Latency time.Duration // Round-trip latency
	Err     error         // Error if ping failed
}

ServerPingResultMsg is sent with the result of a server ping operation

type Setter

type Setter interface {
	Set(item *memcache.Item) error
}

Setter is an interface for setting keys in Memcached. This allows for easy mocking in tests.

type State

type State int

State represents the application state

const (
	// StateConnecting indicates the app is connecting to the server
	StateConnecting State = iota
	// StateConnected indicates successful connection
	StateConnected
	// StateLoading indicates data is being loaded
	StateLoading
	// StateReady indicates the app is ready for use
	StateReady
	// StateError indicates an error occurred
	StateError
)

Application states

func (State) String

func (s State) String() string

String returns the string representation of the state

type Styles

type Styles struct {
	Theme      styles.Theme
	Title      lipgloss.Style
	StatusBar  lipgloss.Style
	Error      lipgloss.Style
	KeyList    lipgloss.Style
	Viewer     lipgloss.Style
	Help       lipgloss.Style
	Connecting lipgloss.Style
	Border     lipgloss.Style
}

Styles holds lipgloss styles for the app, derived from a Theme

func DefaultStyles

func DefaultStyles() Styles

DefaultStyles returns the default styles using the dark theme

func NewStylesFromTheme

func NewStylesFromTheme(theme *styles.Theme) Styles

NewStylesFromTheme creates Styles from a Theme

type SwitchServerMsg

type SwitchServerMsg struct {
	Address string // Server address to connect to
	Name    string // Human-readable server name
}

SwitchServerMsg is sent to initiate a server switch

type ValueLoadedMsg

type ValueLoadedMsg struct {
	Key        string
	Value      []byte
	Flags      uint32
	Expiration int32
	CAS        uint64
}

ValueLoadedMsg is sent when a value is loaded

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL