Documentation
¶
Overview ¶
Package common provides shared utilities for CLI commands.
Index ¶
- Constants
- Variables
- func AddForceFlag(cmd *cobra.Command, target *bool)
- func AddFormatFlag(cmd *cobra.Command, target *string)
- func AddIDFlag(cmd *cobra.Command, target *bool)
- func AddJSONFlag(cmd *cobra.Command, target *bool)
- func AddLimitFlag(cmd *cobra.Command, target *int, defaultValue int)
- func AddOutputFlags(cmd *cobra.Command)
- func AddPageTokenFlag(cmd *cobra.Command, target *string)
- func AddVerboseFlag(cmd *cobra.Command, target *bool)
- func AddYesFlag(cmd *cobra.Command, target *bool)
- func Confirm(prompt string, defaultYes bool) bool
- func CopyToClipboard(text string) error
- func CreateContext() (context.Context, context.CancelFunc)
- func CreateContextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)
- func CreateLongContext() (context.Context, context.CancelFunc)
- func Debug(msg string, args ...any)
- func DebugAPI(operation string, args ...any)
- func DebugHTTP(method, url string, statusCode int, duration string)
- func Error(msg string, args ...any)
- func FetchAllPages[T any](ctx context.Context, config PaginationConfig, fetcher PageFetcher[T]) ([]T, error)
- func FetchAllWithProgress[T any](ctx context.Context, fetcher PageFetcher[T], maxItems int) ([]T, error)
- func FindExecutableInPath(name string) (string, error)
- func FormatDate(t time.Time) string
- func FormatDisplayDate(t time.Time) string
- func FormatError(err error) string
- func FormatParticipant(p domain.EmailParticipant) string
- func FormatParticipants(participants []domain.EmailParticipant) string
- func FormatSize(bytes int64) string
- func FormatTimeAgo(t time.Time) string
- func GetAPIKey() (string, error)
- func GetCachedNylasClient() (ports.NylasClient, error)
- func GetConfigPath(cmd *cobra.Command) string
- func GetConfigStore(cmd *cobra.Command) ports.ConfigStore
- func GetGrantID(args []string) (string, error)
- func GetLogger() *slog.Logger
- func GetNylasClient() (ports.NylasClient, error)
- func GetOutputOptions(cmd *cobra.Command, w io.Writer) ports.OutputOptions
- func GetOutputWriter(cmd *cobra.Command) ports.OutputWriter
- func GetOutputWriterTo(cmd *cobra.Command, w io.Writer) ports.OutputWriter
- func Info(msg string, args ...any)
- func InitLogger(debug, quiet bool)
- func IsDebug() bool
- func IsJSON(cmd *cobra.Command) bool
- func IsQuiet() bool
- func IsRetryable(err error) bool
- func IsRetryableStatusCode(statusCode int) bool
- func IsWide(cmd *cobra.Command) bool
- func NewDeleteCommand(config DeleteCommandConfig) *cobra.Command
- func NewInputError(message string) error
- func NewMutuallyExclusiveError(flag1, flag2 string) error
- func NewShowCommand(config ShowCommandConfig) *cobra.Command
- func NewUserError(message, suggestion string) error
- func NewUserErrorWithSuggestions(message string, suggestions ...string) error
- func ParseDate(s string) (time.Time, error)
- func ParseDuration(s string) (time.Duration, error)
- func ParseTime(s string) (time.Time, error)
- func ParseTimeOfDay(s string) (time.Time, error)
- func ParseTimeOfDayInLocation(s string, loc *time.Location) (time.Time, error)
- func PrintDoubleSeparator(width int)
- func PrintEmptyState(resourceName string)
- func PrintEmptyStateWithHint(resourceName, hint string)
- func PrintError(format string, args ...any)
- func PrintFormattedError(err error)
- func PrintInfo(format string, args ...any)
- func PrintJSON(data any) error
- func PrintListHeader(count int, resourceName string)
- func PrintSeparator(width int)
- func PrintSuccess(format string, args ...any)
- func PrintUpdateSuccess(resourceName string, details ...string)
- func PrintWarning(format string, args ...any)
- func RemoveTagWithContent(s, tag string) string
- func ResetCachedClient()
- func ResetLogger()
- func RunDelete(config DeleteConfig) error
- func RunWithSpinner(message string, fn func() error) error
- func RunWithSpinnerResult[T any](message string, fn func() (T, error)) (T, error)
- func SafeCommand(name string, args ...string) (*exec.Cmd, error)
- func StripHTML(s string) string
- func Truncate(s string, maxLen int) string
- func ValidateAtLeastOne(name string, values ...string) error
- func ValidateEmail(name, value string) error
- func ValidateExecutablePath(path string) error
- func ValidateOneOf(name, value string, allowed []string) error
- func ValidateRequired(name, value string) error
- func ValidateRequiredArg(args []string, name string) error
- func ValidateRequiredFlag(flagName, value string) error
- func ValidateURL(name, value string) error
- func Warn(msg string, args ...any)
- func WithClient[T any](args []string, ...) (T, error)
- func WithClientNoGrant[T any](fn func(ctx context.Context, client ports.NylasClient) (T, error)) (T, error)
- func WithRetry(ctx context.Context, config RetryConfig, fn RetryFunc) error
- func WrapCancelError(resource string, err error) error
- func WrapCreateError(resource string, err error) error
- func WrapDateParseError(flagName string, err error) error
- func WrapDecodeError(resource string, err error) error
- func WrapDeleteError(resource string, err error) error
- func WrapDownloadError(resource string, err error) error
- func WrapFetchError(resource string, err error) error
- func WrapGenerateError(resource string, err error) error
- func WrapGetError(resource string, err error) error
- func WrapListError(resource string, err error) error
- func WrapLoadError(resource string, err error) error
- func WrapMarshalError(resource string, err error) error
- func WrapRecipientError(recipientType string, err error) error
- func WrapSaveError(resource string, err error) error
- func WrapSearchError(resource string, err error) error
- func WrapSendError(resource string, err error) error
- func WrapUpdateError(resource string, err error) error
- func WrapWriteError(resource string, err error) error
- func WriteListWithColumns(cmd *cobra.Command, data any, columns []ports.Column) error
- func WriteListWithWideColumns(cmd *cobra.Command, data any, normalCols, wideCols []ports.Column) error
- type CLIError
- type Counter
- type DeleteCommandConfig
- type DeleteConfig
- type Formatter
- type ListSetup
- type LogLevel
- type OutputFormat
- type PageFetcher
- type PageResult
- type PaginatedDisplay
- type PaginationConfig
- type ProgressBar
- type ResourceArgs
- type RetryConfig
- type RetryFunc
- type RetryableError
- type ShowCommandConfig
- type Spinner
- func (s *Spinner) SetFrames(frames []string) *Spinner
- func (s *Spinner) SetWriter(w io.Writer) *Spinner
- func (s *Spinner) Start()
- func (s *Spinner) Stop()
- func (s *Spinner) StopWithError(message string)
- func (s *Spinner) StopWithMessage(message string)
- func (s *Spinner) StopWithSuccess(message string)
- type Table
- type UpdateSetup
Constants ¶
const ( ErrCodeNotConfigured = "E001" ErrCodeAuthFailed = "E002" ErrCodeNetworkError = "E003" ErrCodeNotFound = "E004" ErrCodePermissionDenied = "E005" ErrCodeInvalidInput = "E006" ErrCodeRateLimited = "E007" ErrCodeServerError = "E008" )
ErrorCode constants for common errors.
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 ¶
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.
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 ¶
AddForceFlag adds a --force/-f flag for skipping confirmations.
func AddFormatFlag ¶
AddFormatFlag adds a --format/-f flag for output format.
func AddJSONFlag ¶
AddJSONFlag adds a --json flag for JSON output.
func AddLimitFlag ¶
AddLimitFlag adds a --limit/-n flag with the given default.
func AddOutputFlags ¶
AddOutputFlags adds common output flags to a command These flags are inherited by all subcommands when added to a parent
func AddPageTokenFlag ¶
AddPageTokenFlag adds a --page-token flag for pagination.
func AddVerboseFlag ¶
AddVerboseFlag adds a --verbose/-v flag for verbose output.
func AddYesFlag ¶
AddYesFlag adds a --yes/-y flag for skipping confirmations.
func CopyToClipboard ¶
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 ¶
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 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 ¶
FindExecutableInPath finds an executable in the system PATH. Returns the full path or an error if not found.
func FormatDate ¶
FormatDate formats a time as a date string (YYYY-MM-DD).
func FormatDisplayDate ¶
FormatDisplayDate formats a time for user 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 ¶
FormatSize formats a file size in bytes to a human-readable string.
func FormatTimeAgo ¶
FormatTimeAgo formats a time as a relative string (e.g., "2 hours ago").
func GetAPIKey ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
GetOutputWriterTo creates an output writer to a specific destination
func InitLogger ¶
func InitLogger(debug, quiet bool)
InitLogger initializes the global logger with the specified options.
func IsRetryable ¶
IsRetryable checks if an error should be retried.
func IsRetryableStatusCode ¶
IsRetryableStatusCode checks if an HTTP status code should be retried.
func NewDeleteCommand ¶
func NewDeleteCommand(config DeleteCommandConfig) *cobra.Command
NewDeleteCommand creates a fully configured delete command.
func NewInputError ¶
NewInputError creates an input validation error.
func NewMutuallyExclusiveError ¶
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 ¶
NewUserError creates a user-facing error with a suggestion.
func NewUserErrorWithSuggestions ¶
NewUserErrorWithSuggestions creates a user-facing error with multiple suggestions.
func ParseDuration ¶
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 ParseTimeOfDay ¶
ParseTimeOfDay parses time strings like "9am", "14:30", "2:30pm". Uses UTC for the date component; only hour/minute are meaningful.
func ParseTimeOfDayInLocation ¶
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 PrintFormattedError ¶
func PrintFormattedError(err error)
PrintFormattedError prints a formatted error to stderr.
func PrintJSON ¶
PrintJSON writes data to stdout as pretty-printed JSON. This is a convenience function for commands that need simple JSON output.
func PrintListHeader ¶
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 ¶
PrintSuccess prints a success message.
func PrintUpdateSuccess ¶
PrintUpdateSuccess prints a standardized success message for update operations.
func PrintWarning ¶
PrintWarning prints a warning message.
func RemoveTagWithContent ¶
RemoveTagWithContent removes a tag and all its content.
func ResetCachedClient ¶
func ResetCachedClient()
ResetCachedClient clears the cached client (useful for testing).
func RunDelete ¶
func RunDelete(config DeleteConfig) error
RunDelete executes a standard delete operation with confirmation, spinner, and success message.
func RunWithSpinner ¶
RunWithSpinner executes a function while displaying a spinner. It handles spinner start/stop and error propagation.
func RunWithSpinnerResult ¶
RunWithSpinnerResult executes a function while displaying a spinner. Returns the result and any error from the function.
func SafeCommand ¶
SafeCommand creates a validated exec.Cmd for an external command. It validates the executable path and returns an error if unsafe.
func ValidateAtLeastOne ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
ValidateURL returns an error if value is not a valid URL.
Example:
if err := common.ValidateURL("webhook URL", webhookURL); err != nil {
return err
}
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 ¶
WrapCancelError wraps an error from a cancel operation.
func WrapCreateError ¶
WrapCreateError wraps an error from a create operation.
func WrapDateParseError ¶
WrapDateParseError wraps a date parsing error with context.
func WrapDecodeError ¶
WrapDecodeError wraps an error from a decode operation.
func WrapDeleteError ¶
WrapDeleteError wraps an error from a delete operation.
func WrapDownloadError ¶
WrapDownloadError wraps an error from a download operation.
func WrapFetchError ¶
WrapFetchError wraps an error from a fetch/list operation.
func WrapGenerateError ¶
WrapGenerateError wraps an error from a generate operation.
func WrapGetError ¶
WrapGetError wraps an error from a GET operation.
func WrapListError ¶
WrapListError wraps an error from a list operation.
func WrapLoadError ¶
WrapLoadError wraps an error from a load operation.
func WrapMarshalError ¶
WrapMarshalError wraps an error from a marshal/encode operation.
func WrapRecipientError ¶
WrapRecipientError wraps a recipient parsing error.
func WrapSaveError ¶
WrapSaveError wraps an error from a save operation.
func WrapSearchError ¶
WrapSearchError wraps an error from a search operation.
func WrapSendError ¶
WrapSendError wraps an error from a send operation.
func WrapUpdateError ¶
WrapUpdateError wraps an error from an update operation.
func WrapWriteError ¶
WrapWriteError wraps an error from a write operation.
func WriteListWithColumns ¶
WriteListWithColumns writes list output with appropriate columns based on flags This is a convenience function that handles the common pattern of outputting data
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.
type Counter ¶
type Counter struct {
// contains filtered or unexported fields
}
Counter provides a simple counter display.
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.
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 ¶
SetupListCommand performs standard setup for list commands: - Gets client - Gets grant ID from args - Creates context Returns ListSetup with all values populated.
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 ¶
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 ¶
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) Increment ¶
func (p *ProgressBar) Increment()
Increment increments the progress by 1.
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 RetryableError ¶
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 ¶
NewSpinner creates a new spinner with the given message.
func (*Spinner) StopWithError ¶
StopWithError stops the spinner with an error message.
func (*Spinner) StopWithMessage ¶
StopWithMessage stops the spinner and prints a final message.
func (*Spinner) StopWithSuccess ¶
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 (*Table) AlignRight ¶
AlignRight sets right alignment for a column.
func (*Table) SetMaxWidth ¶
SetMaxWidth sets the maximum width for a column (truncates with ellipsis if exceeded).
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.