common

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package common provides shared utilities for CLI commands.

Index

Constants

View Source
const (
	ErrCodeNotConfigured    = "E001"
	ErrCodeAuthFailed       = "E002"
	ErrCodeNetworkError     = "E003"
	ErrCodeNotFound         = "E004"
	ErrCodePermissionDenied = "E005"
	ErrCodeInvalidInput     = "E006"
	ErrCodeRateLimited      = "E007"
	ErrCodeServerError      = "E008"
)

ErrorCode constants for common errors.

View Source
const (
	// Machine-readable formats
	DateFormat     = "2006-01-02"
	TimeFormat     = "15:04"
	DateTimeFormat = "2006-01-02 15:04"

	// Display formats (user-friendly)
	DisplayDateFormat = "Jan 2, 2006"
	DisplayTimeFormat = "3:04 PM"
	DisplayDateTime   = "Jan 2, 2006 3:04 PM"

	// Extended display formats with timezone
	DisplayDateTimeWithTZ     = "Jan 2, 2006 3:04 PM MST"
	DisplayWeekdayDateTime    = "Mon, Jan 2, 2006 at 3:04 PM MST"
	DisplayTimeWithTZ         = "3:04 PM MST"
	DisplayWeekdayShort       = "Mon Jan 2, 3:04 PM"
	DisplayWeekdayShortWithTZ = "Mon Jan 2, 3:04 PM MST"

	// Full weekday formats with year
	DisplayWeekdayFull       = "Mon Jan 2, 2006 3:04 PM"
	DisplayWeekdayFullWithTZ = "Mon Jan 2, 2006 3:04 PM MST"

	// Weekday formats with comma separator
	DisplayWeekdayComma   = "Mon, Jan 2, 2006 3:04 PM"
	DisplayWeekdayCommaAt = "Mon, Jan 2, 2006 at 3:04 PM"

	// Long formats (full weekday, full month)
	DisplayDateLong  = "Monday, January 2, 2006"
	DisplayMonthYear = "January 2006"

	// Short formats
	ShortDateTime = "Jan 2 15:04"
	ShortDate     = "Jan 2"
)

Standard date/time format constants.

Variables

View Source
var (
	// Basic colors
	Cyan   = color.New(color.FgCyan)
	Green  = color.New(color.FgGreen)
	Yellow = color.New(color.FgYellow)
	Red    = color.New(color.FgRed)
	Blue   = color.New(color.FgBlue)

	// Styles
	Bold = color.New(color.Bold)
	Dim  = color.New(color.Faint)

	// Bold colors
	BoldWhite  = color.New(color.FgWhite, color.Bold)
	BoldCyan   = color.New(color.FgCyan, color.Bold)
	BoldGreen  = color.New(color.FgGreen, color.Bold)
	BoldBlue   = color.New(color.FgBlue, color.Bold)
	BoldYellow = color.New(color.FgYellow, color.Bold)
	BoldRed    = color.New(color.FgRed, color.Bold)

	// High intensity
	HiBlack = color.New(color.FgHiBlack)

	// Reset (no formatting)
	Reset = color.New(color.Reset)
)

Common color definitions used across CLI commands. Import these instead of defining package-local color vars.

View Source
var SpinnerFrames = struct {
	Dots    []string
	Line    []string
	Circle  []string
	Arrow   []string
	Default []string
}{
	Dots:    []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
	Line:    []string{"-", "\\", "|", "/"},
	Circle:  []string{"◐", "◓", "◑", "◒"},
	Arrow:   []string{"←", "↖", "↑", "↗", "→", "↘", "↓", "↙"},
	Default: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
}

SpinnerFrames defines available spinner styles.

Functions

func AddForceFlag

func AddForceFlag(cmd *cobra.Command, target *bool)

AddForceFlag adds a --force/-f flag for skipping confirmations.

func AddFormatFlag

func AddFormatFlag(cmd *cobra.Command, target *string)

AddFormatFlag adds a --format/-f flag for output format.

func AddIDFlag

func AddIDFlag(cmd *cobra.Command, target *bool)

AddIDFlag adds a --id flag to show resource IDs.

func AddJSONFlag

func AddJSONFlag(cmd *cobra.Command, target *bool)

AddJSONFlag adds a --json flag for JSON output.

func AddLimitFlag

func AddLimitFlag(cmd *cobra.Command, target *int, defaultValue int)

AddLimitFlag adds a --limit/-n flag with the given default.

func AddOutputFlags

func AddOutputFlags(cmd *cobra.Command)

AddOutputFlags adds common output flags to a command These flags are inherited by all subcommands when added to a parent

func AddPageTokenFlag

func AddPageTokenFlag(cmd *cobra.Command, target *string)

AddPageTokenFlag adds a --page-token flag for pagination.

func AddVerboseFlag

func AddVerboseFlag(cmd *cobra.Command, target *bool)

AddVerboseFlag adds a --verbose/-v flag for verbose output.

func AddYesFlag

func AddYesFlag(cmd *cobra.Command, target *bool)

AddYesFlag adds a --yes/-y flag for skipping confirmations.

func Confirm

func Confirm(prompt string, defaultYes bool) bool

Confirm prompts for user confirmation.

func CopyToClipboard

func CopyToClipboard(text string) error

CopyToClipboard copies text to the system clipboard. On Linux, it supports both X11 (xclip/xsel) and Wayland (wl-copy). On macOS and Windows, it uses the native clipboard.

func CreateContext

func CreateContext() (context.Context, context.CancelFunc)

CreateContext creates a context with the standard API timeout. Returns the context and a cancel function that should be deferred.

func CreateContextWithTimeout

func CreateContextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)

CreateContextWithTimeout creates a context with a custom timeout.

func CreateLongContext

func CreateLongContext() (context.Context, context.CancelFunc)

CreateLongContext creates a context with the OAuth timeout (5 minutes). Use for operations requiring user interaction (OAuth flows, browser auth).

func Debug

func Debug(msg string, args ...any)

Debug logs a debug message.

func DebugAPI

func DebugAPI(operation string, args ...any)

DebugAPI logs API operation details in debug mode.

func DebugHTTP

func DebugHTTP(method, url string, statusCode int, duration string)

DebugHTTP logs HTTP request/response details in debug mode.

func Error

func Error(msg string, args ...any)

Error logs an error message.

func FetchAllPages

func FetchAllPages[T any](ctx context.Context, config PaginationConfig, fetcher PageFetcher[T]) ([]T, error)

FetchAllPages fetches all pages using the provided fetcher function.

func FetchAllWithProgress

func FetchAllWithProgress[T any](ctx context.Context, fetcher PageFetcher[T], maxItems int) ([]T, error)

FetchAllWithProgress fetches all pages and shows a progress indicator.

func FindExecutableInPath

func FindExecutableInPath(name string) (string, error)

FindExecutableInPath finds an executable in the system PATH. Returns the full path or an error if not found.

func FormatDate

func FormatDate(t time.Time) string

FormatDate formats a time as a date string (YYYY-MM-DD).

func FormatDisplayDate

func FormatDisplayDate(t time.Time) string

FormatDisplayDate formats a time for user display.

func FormatError

func FormatError(err error) string

FormatError formats an error for CLI display.

func FormatParticipant

func FormatParticipant(p domain.EmailParticipant) string

FormatParticipant formats an email participant for display.

func FormatParticipants

func FormatParticipants(participants []domain.EmailParticipant) string

FormatParticipants formats a slice of email participants.

func FormatSize

func FormatSize(bytes int64) string

FormatSize formats a file size in bytes to a human-readable string.

func FormatTimeAgo

func FormatTimeAgo(t time.Time) string

FormatTimeAgo formats a time as a relative string (e.g., "2 hours ago").

func GetAPIKey

func GetAPIKey() (string, error)

GetAPIKey returns the API key from environment variable or keyring. It checks in this order: 1. Environment variable (NYLAS_API_KEY) - highest priority 2. System keyring (if available) 3. Encrypted file store (if keyring unavailable)

func GetCachedNylasClient

func GetCachedNylasClient() (ports.NylasClient, error)

GetCachedNylasClient returns a singleton Nylas client. This is useful for CLI commands that need to make multiple API calls in a single command invocation, avoiding the overhead of creating a new client each time.

Note: The client is cached for the lifetime of the process. For long-running processes or tests, use GetNylasClient() instead.

func GetConfigPath

func GetConfigPath(cmd *cobra.Command) string

GetConfigPath walks up the parent command chain to find the --config flag value. Returns empty string if no config path is set.

func GetConfigStore

func GetConfigStore(cmd *cobra.Command) ports.ConfigStore

GetConfigStore returns the appropriate config store based on the --config flag. It walks up the parent command chain to find the flag value. If no custom config path is found, returns the default file store.

func GetGrantID

func GetGrantID(args []string) (string, error)

GetGrantID returns the grant ID from arguments, environment variable, config file, or keyring. It checks in this order: 1. Command line argument (if provided) - supports email lookup if arg contains "@" 2. Environment variable (NYLAS_GRANT_ID) 3. Config file (default_grant) 4. Stored default grant (from keyring/file)

func GetLogger

func GetLogger() *slog.Logger

GetLogger returns the global logger, initializing with defaults if needed.

func GetNylasClient

func GetNylasClient() (ports.NylasClient, error)

GetNylasClient creates a Nylas API client with credentials from environment variables or keyring. It checks credentials in this order: 1. Environment variables (NYLAS_API_KEY, NYLAS_CLIENT_ID, NYLAS_CLIENT_SECRET) - highest priority 2. System keyring (if available and env vars not set) 3. Encrypted file store (if keyring unavailable)

This allows the CLI to work in multiple environments: - CI/CD pipelines (environment variables) - Docker containers (environment variables) - Integration tests (environment variables with NYLAS_DISABLE_KEYRING=true) - Local development (keyring)

func GetOutputOptions

func GetOutputOptions(cmd *cobra.Command, w io.Writer) ports.OutputOptions

GetOutputOptions extracts output options from command flags

func GetOutputWriter

func GetOutputWriter(cmd *cobra.Command) ports.OutputWriter

GetOutputWriter creates an output writer based on command flags

func GetOutputWriterTo

func GetOutputWriterTo(cmd *cobra.Command, w io.Writer) ports.OutputWriter

GetOutputWriterTo creates an output writer to a specific destination

func Info

func Info(msg string, args ...any)

Info logs an info message.

func InitLogger

func InitLogger(debug, quiet bool)

InitLogger initializes the global logger with the specified options.

func IsDebug

func IsDebug() bool

IsDebug returns true if debug mode is enabled.

func IsJSON

func IsJSON(cmd *cobra.Command) bool

IsJSON returns true if JSON output is enabled

func IsQuiet

func IsQuiet() bool

IsQuiet returns true if quiet mode is enabled.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if an error should be retried.

func IsRetryableStatusCode

func IsRetryableStatusCode(statusCode int) bool

IsRetryableStatusCode checks if an HTTP status code should be retried.

func IsWide

func IsWide(cmd *cobra.Command) bool

IsWide returns true if wide output mode is enabled

func NewDeleteCommand

func NewDeleteCommand(config DeleteCommandConfig) *cobra.Command

NewDeleteCommand creates a fully configured delete command.

func NewInputError

func NewInputError(message string) error

NewInputError creates an input validation error.

func NewMutuallyExclusiveError

func NewMutuallyExclusiveError(flag1, flag2 string) error

NewMutuallyExclusiveError creates an error for mutually exclusive flags.

func NewShowCommand

func NewShowCommand(config ShowCommandConfig) *cobra.Command

NewShowCommand creates a fully configured show command with custom display logic.

func NewUserError

func NewUserError(message, suggestion string) error

NewUserError creates a user-facing error with a suggestion.

func NewUserErrorWithSuggestions

func NewUserErrorWithSuggestions(message string, suggestions ...string) error

NewUserErrorWithSuggestions creates a user-facing error with multiple suggestions.

func ParseDate

func ParseDate(s string) (time.Time, error)

ParseDate parses a date string in YYYY-MM-DD format.

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration parses duration strings with extended support for days and weeks. Supports: standard Go durations (1h30m, 30s) plus "d" (days) and "w" (weeks). Examples: "30m", "2h", "24h", "7d", "2w".

func ParseTime

func ParseTime(s string) (time.Time, error)

ParseTime parses a time string in HH:MM format.

func ParseTimeOfDay

func ParseTimeOfDay(s string) (time.Time, error)

ParseTimeOfDay parses time strings like "9am", "14:30", "2:30pm". Uses UTC for the date component; only hour/minute are meaningful.

func ParseTimeOfDayInLocation

func ParseTimeOfDayInLocation(s string, loc *time.Location) (time.Time, error)

ParseTimeOfDayInLocation parses time strings with a specific location. Supports formats: "15:04" (24h), "3:04pm", "3:04 pm", "3pm", "3 pm".

func PrintDoubleSeparator

func PrintDoubleSeparator(width int)

PrintDoubleSeparator prints a double-line separator for section headers.

func PrintEmptyState

func PrintEmptyState(resourceName string)

PrintEmptyState prints a consistent "no items found" message.

func PrintEmptyStateWithHint

func PrintEmptyStateWithHint(resourceName, hint string)

PrintEmptyStateWithHint prints empty state with a helpful hint.

func PrintError

func PrintError(format string, args ...any)

PrintError prints an error message.

func PrintFormattedError

func PrintFormattedError(err error)

PrintFormattedError prints a formatted error to stderr.

func PrintInfo

func PrintInfo(format string, args ...any)

PrintInfo prints an info message.

func PrintJSON

func PrintJSON(data any) error

PrintJSON writes data to stdout as pretty-printed JSON. This is a convenience function for commands that need simple JSON output.

func PrintListHeader

func PrintListHeader(count int, resourceName string)

PrintListHeader prints a consistent "found N items" header.

func PrintSeparator

func PrintSeparator(width int)

PrintSeparator prints a horizontal line separator of specified width. Common widths: 40 (narrow), 50 (medium), 60 (wide), 70 (extra wide).

func PrintSuccess

func PrintSuccess(format string, args ...any)

PrintSuccess prints a success message.

func PrintUpdateSuccess

func PrintUpdateSuccess(resourceName string, details ...string)

PrintUpdateSuccess prints a standardized success message for update operations.

func PrintWarning

func PrintWarning(format string, args ...any)

PrintWarning prints a warning message.

func RemoveTagWithContent

func RemoveTagWithContent(s, tag string) string

RemoveTagWithContent removes a tag and all its content.

func ResetCachedClient

func ResetCachedClient()

ResetCachedClient clears the cached client (useful for testing).

func ResetLogger

func ResetLogger()

ResetLogger resets the logger (for testing).

func RunDelete

func RunDelete(config DeleteConfig) error

RunDelete executes a standard delete operation with confirmation, spinner, and success message.

func RunWithSpinner

func RunWithSpinner(message string, fn func() error) error

RunWithSpinner executes a function while displaying a spinner. It handles spinner start/stop and error propagation.

func RunWithSpinnerResult

func RunWithSpinnerResult[T any](message string, fn func() (T, error)) (T, error)

RunWithSpinnerResult executes a function while displaying a spinner. Returns the result and any error from the function.

func SafeCommand

func SafeCommand(name string, args ...string) (*exec.Cmd, error)

SafeCommand creates a validated exec.Cmd for an external command. It validates the executable path and returns an error if unsafe.

func StripHTML

func StripHTML(s string) string

StripHTML removes HTML tags from a string and decodes HTML entities.

func Truncate

func Truncate(s string, maxLen int) string

Truncate shortens a string to maxLen characters, adding "..." if truncated.

func ValidateAtLeastOne

func ValidateAtLeastOne(name string, values ...string) error

ValidateAtLeastOne returns an error if all values are empty. Use when at least one of several optional flags is required.

Example:

if err := common.ValidateAtLeastOne("update field", url, description, status); err != nil {
    return err
}

func ValidateEmail

func ValidateEmail(name, value string) error

ValidateEmail returns an error if value doesn't look like an email address. This is a basic check for @ symbol, not RFC 5322 compliant.

Example:

if err := common.ValidateEmail("recipient", toEmail); err != nil {
    return err
}

func ValidateExecutablePath

func ValidateExecutablePath(path string) error

ValidateExecutablePath validates that an executable path is safe to use. It checks that the path exists, is executable, and doesn't contain suspicious patterns.

func ValidateOneOf

func ValidateOneOf(name, value string, allowed []string) error

ValidateOneOf returns an error if value is not in the allowed list.

Example:

if err := common.ValidateOneOf("status", status, []string{"pending", "active", "cancelled"}); err != nil {
    return err
}

func ValidateRequired

func ValidateRequired(name, value string) error

ValidateRequired returns an error if value is empty. Use for required command arguments.

Example:

if err := common.ValidateRequired("event ID", args[0]); err != nil {
    return err
}

func ValidateRequiredArg

func ValidateRequiredArg(args []string, name string) error

ValidateRequiredArg returns an error if args is empty or first arg is empty. Use for commands that require at least one argument.

Example:

if err := common.ValidateRequiredArg(args, "message ID"); err != nil {
    return err
}

func ValidateRequiredFlag

func ValidateRequiredFlag(flagName, value string) error

ValidateRequiredFlag returns an error if value is empty. Use for required command flags.

Example:

if err := common.ValidateRequiredFlag("--to", toEmail); err != nil {
    return err
}

func ValidateURL

func ValidateURL(name, value string) error

ValidateURL returns an error if value is not a valid URL.

Example:

if err := common.ValidateURL("webhook URL", webhookURL); err != nil {
    return err
}

func Warn

func Warn(msg string, args ...any)

Warn logs a warning message.

func WithClient

func WithClient[T any](args []string, fn func(ctx context.Context, client ports.NylasClient, grantID string) (T, error)) (T, error)

WithClient is a generic helper that handles client setup, context creation, and grant ID resolution. This reduces boilerplate in commands by handling all the common setup in one place.

Usage:

return common.WithClient(args, func(ctx context.Context, client ports.NylasClient, grantID string) error {
    calendars, err := client.GetCalendars(ctx, grantID)
    if err != nil {
        return err
    }
    // ... process calendars ...
    return nil
})

func WithClientNoGrant

func WithClientNoGrant[T any](fn func(ctx context.Context, client ports.NylasClient) (T, error)) (T, error)

WithClientNoGrant is a generic helper for commands that don't need a grant ID. This is useful for admin commands or commands that operate without a specific account.

Usage:

return common.WithClientNoGrant(func(ctx context.Context, client ports.NylasClient) error {
    // ... use client ...
    return nil
})

func WithRetry

func WithRetry(ctx context.Context, config RetryConfig, fn RetryFunc) error

WithRetry executes a function with retry logic.

func WrapCancelError

func WrapCancelError(resource string, err error) error

WrapCancelError wraps an error from a cancel operation.

func WrapCreateError

func WrapCreateError(resource string, err error) error

WrapCreateError wraps an error from a create operation.

func WrapDateParseError

func WrapDateParseError(flagName string, err error) error

WrapDateParseError wraps a date parsing error with context.

func WrapDecodeError

func WrapDecodeError(resource string, err error) error

WrapDecodeError wraps an error from a decode operation.

func WrapDeleteError

func WrapDeleteError(resource string, err error) error

WrapDeleteError wraps an error from a delete operation.

func WrapDownloadError

func WrapDownloadError(resource string, err error) error

WrapDownloadError wraps an error from a download operation.

func WrapFetchError

func WrapFetchError(resource string, err error) error

WrapFetchError wraps an error from a fetch/list operation.

func WrapGenerateError

func WrapGenerateError(resource string, err error) error

WrapGenerateError wraps an error from a generate operation.

func WrapGetError

func WrapGetError(resource string, err error) error

WrapGetError wraps an error from a GET operation.

func WrapListError

func WrapListError(resource string, err error) error

WrapListError wraps an error from a list operation.

func WrapLoadError

func WrapLoadError(resource string, err error) error

WrapLoadError wraps an error from a load operation.

func WrapMarshalError

func WrapMarshalError(resource string, err error) error

WrapMarshalError wraps an error from a marshal/encode operation.

func WrapRecipientError

func WrapRecipientError(recipientType string, err error) error

WrapRecipientError wraps a recipient parsing error.

func WrapSaveError

func WrapSaveError(resource string, err error) error

WrapSaveError wraps an error from a save operation.

func WrapSearchError

func WrapSearchError(resource string, err error) error

WrapSearchError wraps an error from a search operation.

func WrapSendError

func WrapSendError(resource string, err error) error

WrapSendError wraps an error from a send operation.

func WrapUpdateError

func WrapUpdateError(resource string, err error) error

WrapUpdateError wraps an error from an update operation.

func WrapWriteError

func WrapWriteError(resource string, err error) error

WrapWriteError wraps an error from a write operation.

func WriteListWithColumns

func WriteListWithColumns(cmd *cobra.Command, data any, columns []ports.Column) error

WriteListWithColumns writes list output with appropriate columns based on flags This is a convenience function that handles the common pattern of outputting data

func WriteListWithWideColumns

func WriteListWithWideColumns(cmd *cobra.Command, data any, normalCols, wideCols []ports.Column) error

WriteListWithWideColumns writes list output with different columns for normal vs wide mode This is useful for tables where you want to show full IDs in wide mode

Types

type CLIError

type CLIError struct {
	Err         error
	Message     string
	Suggestion  string   // Single suggestion (deprecated, use Suggestions)
	Suggestions []string // Multiple suggestions
	Code        string
}

CLIError wraps an error with additional context for CLI display.

func WrapError

func WrapError(err error) *CLIError

WrapError wraps an error with CLI-friendly context.

func (*CLIError) Error

func (e *CLIError) Error() string

func (*CLIError) Unwrap

func (e *CLIError) Unwrap() error

type Counter

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

Counter provides a simple counter display.

func NewCounter

func NewCounter(message string) *Counter

NewCounter creates a new counter.

func (*Counter) Count

func (c *Counter) Count() int

Count returns the current count.

func (*Counter) Finish

func (c *Counter) Finish()

Finish completes the counter display.

func (*Counter) Increment

func (c *Counter) Increment()

Increment increments the counter.

type DeleteCommandConfig

type DeleteCommandConfig struct {
	Use               string                                                                // Cobra Use string
	Aliases           []string                                                              // Cobra aliases
	Short             string                                                                // Short description
	Long              string                                                                // Long description
	ResourceName      string                                                                // Resource name for messages
	DeleteFunc        func(ctx context.Context, grantID, resourceID string) error           // Delete function (with grantID)
	DeleteFuncNoGrant func(ctx context.Context, resourceID string) error                    // Delete function (without grantID)
	GetClient         func() (ports.NylasClient, error)                                     // Client getter function
	GetDetailsFunc    func(ctx context.Context, resourceID string) (string, error)          // Optional: Get details for confirmation (no grant)
	ShowDetailsFunc   func(ctx context.Context, grantID, resourceID string) (string, error) // Optional: Get details for confirmation (with grant)
	RequiresGrant     bool                                                                  // Whether this resource requires a grant ID
}

NewDeleteCommand creates a standard delete command with common boilerplate handled.

Example usage (with grantID):

cmd := common.NewDeleteCommand(common.DeleteCommandConfig{
    Use: "delete <contact-id> [grant-id]",
    Aliases: []string{"rm", "remove"},
    Short: "Delete a contact",
    ResourceName: "contact",
    DeleteFunc: client.DeleteContact,
    ShowDetailsFunc: func(ctx, grantID, resourceID string) (string, error) {
        contact, _ := client.GetContact(ctx, grantID, resourceID)
        return fmt.Sprintf("Name: %s\nEmail: %s", contact.Name, contact.Email), nil
    },
})

Example usage (without grantID):

cmd := common.NewDeleteCommand(common.DeleteCommandConfig{
    Use: "delete <webhook-id>",
    Short: "Delete a webhook",
    ResourceName: "webhook",
    DeleteFuncNoGrant: func(ctx context.Context, resourceID string) error {
        client, _ := common.GetNylasClient()
        return client.DeleteWebhook(ctx, resourceID)
    },
    GetDetailsFunc: func(ctx context.Context, resourceID string) (string, error) {
        webhook, _ := client.GetWebhook(ctx, resourceID)
        return fmt.Sprintf("URL: %s", webhook.WebhookURL), nil
    },
})

type DeleteConfig

type DeleteConfig struct {
	ResourceName string                                                      // e.g., "contact", "event"
	ResourceID   string                                                      // The ID to delete
	GrantID      string                                                      // Grant ID
	Force        bool                                                        // Skip confirmation
	DeleteFunc   func(ctx context.Context, grantID, resourceID string) error // Actual delete function
}

DeleteConfig configures a delete operation.

type Formatter

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

Formatter handles output formatting.

func NewFormatter

func NewFormatter(format OutputFormat) *Formatter

NewFormatter creates a new formatter.

func (*Formatter) Format

func (f *Formatter) Format(data any) error

Format formats and outputs data based on the configured format.

func (*Formatter) SetWriter

func (f *Formatter) SetWriter(w io.Writer) *Formatter

SetWriter sets the output writer.

type ListSetup

type ListSetup struct {
	Client  ports.NylasClient
	GrantID string
	Ctx     context.Context
	Cancel  context.CancelFunc
}

ListSetup holds common setup for list commands.

func SetupListCommand

func SetupListCommand(args []string) (*ListSetup, error)

SetupListCommand performs standard setup for list commands: - Gets client - Gets grant ID from args - Creates context Returns ListSetup with all values populated.

type LogLevel

type LogLevel int

LogLevel represents logging levels.

const (
	LogLevelError LogLevel = iota
	LogLevelWarn
	LogLevelInfo
	LogLevelDebug
)

type OutputFormat

type OutputFormat string

OutputFormat represents the output format type.

const (
	FormatTable OutputFormat = "table"
	FormatJSON  OutputFormat = "json"
	FormatCSV   OutputFormat = "csv"
	FormatYAML  OutputFormat = "yaml"
)

func ParseFormat

func ParseFormat(s string) (OutputFormat, error)

ParseFormat parses a format string into OutputFormat.

type PageFetcher

type PageFetcher[T any] func(ctx context.Context, cursor string) (PageResult[T], error)

PageFetcher is a function that fetches a single page of results.

type PageResult

type PageResult[T any] struct {
	Data       []T    // The items in this page
	NextCursor string // Cursor for the next page, empty if no more pages
	RequestID  string // Request ID for debugging
}

PageResult represents a paginated API response.

func (PageResult[T]) HasMore

func (p PageResult[T]) HasMore() bool

HasMore returns true if there are more pages to fetch.

type PaginatedDisplay

type PaginatedDisplay struct {
	PageSize     int
	CurrentPage  int
	TotalFetched int
	Writer       io.Writer
}

PaginatedDisplay handles displaying paginated results with optional streaming.

func NewPaginatedDisplay

func NewPaginatedDisplay(pageSize int) *PaginatedDisplay

NewPaginatedDisplay creates a new paginated display helper.

func (*PaginatedDisplay) DisplayPage

func (p *PaginatedDisplay) DisplayPage(itemsDisplayed int, hasMore bool)

DisplayPage shows a summary after displaying items.

func (*PaginatedDisplay) DisplaySummary

func (p *PaginatedDisplay) DisplaySummary()

DisplaySummary shows a final summary.

func (*PaginatedDisplay) SetWriter

func (p *PaginatedDisplay) SetWriter(w io.Writer) *PaginatedDisplay

SetWriter sets the output writer.

type PaginationConfig

type PaginationConfig struct {
	PageSize     int       // Items per page
	MaxItems     int       // Maximum total items (0 = unlimited)
	MaxPages     int       // Maximum pages to fetch (0 = unlimited)
	ShowProgress bool      // Show progress indicator
	Writer       io.Writer // Output writer for progress
}

PaginationConfig configures pagination behavior.

func DefaultPaginationConfig

func DefaultPaginationConfig() PaginationConfig

DefaultPaginationConfig returns default pagination settings.

type ProgressBar

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

ProgressBar provides a progress bar for determinate operations.

func NewProgressBar

func NewProgressBar(total int, message string) *ProgressBar

NewProgressBar creates a new progress bar.

func (*ProgressBar) Add

func (p *ProgressBar) Add(n int)

Add adds n to the current progress.

func (*ProgressBar) Finish

func (p *ProgressBar) Finish()

Finish completes the progress bar.

func (*ProgressBar) Increment

func (p *ProgressBar) Increment()

Increment increments the progress by 1.

func (*ProgressBar) Set

func (p *ProgressBar) Set(n int)

Set sets the current progress.

func (*ProgressBar) SetWidth

func (p *ProgressBar) SetWidth(width int) *ProgressBar

SetWidth sets the progress bar width.

func (*ProgressBar) SetWriter

func (p *ProgressBar) SetWriter(w io.Writer) *ProgressBar

SetWriter sets the output writer.

type ResourceArgs

type ResourceArgs struct {
	ResourceID string // The resource ID (first argument)
	GrantID    string // The grant ID (second argument or default)
}

ResourceArgs holds parsed arguments for CRUD operations.

func ParseResourceArgs

func ParseResourceArgs(args []string, minArgs int) (*ResourceArgs, error)

ParseResourceArgs parses standard resource arguments: <resource-id> [grant-id] Returns ResourceArgs with both IDs populated.

type RetryConfig

type RetryConfig struct {
	MaxRetries  int           // Maximum number of retries (default: 3)
	BaseDelay   time.Duration // Initial delay (default: 1s)
	MaxDelay    time.Duration // Maximum delay cap (default: 30s)
	Multiplier  float64       // Delay multiplier (default: 2.0)
	JitterRatio float64       // Jitter ratio 0-1 (default: 0.1)
}

RetryConfig holds retry configuration.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns the default retry configuration.

func NoRetryConfig

func NoRetryConfig() RetryConfig

NoRetryConfig returns a config that disables retries.

type RetryFunc

type RetryFunc func() error

RetryFunc is a function that can be retried.

type RetryableError

type RetryableError struct {
	Err        error
	StatusCode int
}

RetryableError wraps an error that should be retried.

func (*RetryableError) Error

func (e *RetryableError) Error() string

func (*RetryableError) Unwrap

func (e *RetryableError) Unwrap() error

type ShowCommandConfig

type ShowCommandConfig struct {
	Use          string                                                                     // Cobra Use string
	Aliases      []string                                                                   // Cobra aliases
	Short        string                                                                     // Short description
	Long         string                                                                     // Long description
	ResourceName string                                                                     // Resource name for error messages
	GetFunc      func(ctx context.Context, grantID, resourceID string) (interface{}, error) // Get function
	DisplayFunc  func(resource interface{}) error                                           // Custom display function
	GetClient    func() (ports.NylasClient, error)                                          // Client getter function
}

ShowCommandConfig configures a show command with custom display logic.

Example usage:

cmd := common.NewShowCommand(common.ShowCommandConfig{
    Use: "show <contact-id> [grant-id]",
    Aliases: []string{"get", "read"},
    Short: "Show contact details",
    ResourceName: "contact",
    GetFunc: client.GetContact,
    DisplayFunc: func(resource interface{}) error {
        contact := resource.(*domain.Contact)
        fmt.Printf("Name: %s\n", contact.DisplayName())
        return nil
    },
    GetClient: getClient,
})

type Spinner

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

Spinner provides an animated spinner for indeterminate operations.

func NewSpinner

func NewSpinner(message string) *Spinner

NewSpinner creates a new spinner with the given message.

func (*Spinner) SetFrames

func (s *Spinner) SetFrames(frames []string) *Spinner

SetFrames sets the spinner animation frames.

func (*Spinner) SetWriter

func (s *Spinner) SetWriter(w io.Writer) *Spinner

SetWriter sets the output writer.

func (*Spinner) Start

func (s *Spinner) Start()

Start starts the spinner animation.

func (*Spinner) Stop

func (s *Spinner) Stop()

Stop stops the spinner animation.

func (*Spinner) StopWithError

func (s *Spinner) StopWithError(message string)

StopWithError stops the spinner with an error message.

func (*Spinner) StopWithMessage

func (s *Spinner) StopWithMessage(message string)

StopWithMessage stops the spinner and prints a final message.

func (*Spinner) StopWithSuccess

func (s *Spinner) StopWithSuccess(message string)

StopWithSuccess stops the spinner with a success message.

type Table

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

Table provides a simple table builder.

func NewTable

func NewTable(headers ...string) *Table

NewTable creates a new table with headers.

func (*Table) AddRow

func (t *Table) AddRow(values ...string) *Table

AddRow adds a row to the table.

func (*Table) AlignRight

func (t *Table) AlignRight(col int) *Table

AlignRight sets right alignment for a column.

func (*Table) Render

func (t *Table) Render()

Render renders the table to the writer.

func (*Table) RowCount

func (t *Table) RowCount() int

RowCount returns the number of rows.

func (*Table) SetMaxWidth

func (t *Table) SetMaxWidth(col int, maxWidth int) *Table

SetMaxWidth sets the maximum width for a column (truncates with ellipsis if exceeded).

func (*Table) SetWriter

func (t *Table) SetWriter(w io.Writer) *Table

SetWriter sets the output writer.

type UpdateSetup

type UpdateSetup struct {
	Client     ports.NylasClient
	ResourceID string
	GrantID    string
	Ctx        context.Context
	Cancel     context.CancelFunc
}

UpdateSetup holds common setup for update commands.

func SetupUpdateCommand

func SetupUpdateCommand(args []string) (*UpdateSetup, error)

SetupUpdateCommand performs standard setup for update commands: - Parses resource ID and grant ID from args - Gets client - Creates context Returns UpdateSetup with all values populated.

Jump to

Keyboard shortcuts

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