config

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package config handles application configuration for grut. It loads embedded defaults, merges user overrides from the XDG config path, validates all values, and expands tildes in path fields.

Index

Constants

View Source
const AppName = "grut"

AppName is the canonical application name (constant).

Variables

View Source
var AppVersion = "dev"

AppVersion is the application version, overridden at build time via ldflags:

-X github.com/jongio/grut/internal/config.AppVersion=x.y.z

Functions

func ConfigDir

func ConfigDir() string

ConfigDir returns the XDG config directory for grut.

func DataDir

func DataDir() string

DataDir returns the XDG data directory for grut.

func ResetAllActionConfirmations

func ResetAllActionConfirmations() error

ResetAllActionConfirmations sets all confirmed flags to false by iterating every registered item type.

func ResolveIconMode

func ResolveIconMode(mode string) string

ResolveIconMode resolves the "auto" icon_mode to either "nerd" or "ascii" by inspecting environment variables. If the mode is already "nerd" or "ascii" it is returned unchanged.

Detection order:

  1. GRUT_NERD_FONT=1 → "nerd" (explicit opt-in)
  2. GRUT_NERD_FONT=0 → "ascii" (explicit opt-out)
  3. TERM_PROGRAM matches a known nerd-font terminal → "nerd"
  4. WT_SESSION is set (Windows Terminal) → "nerd"
  5. Otherwise → "ascii" (safe default)

func SaveDoubleClickChoice

func SaveDoubleClickChoice(cfg *ActionsConfig, itemType, actionID string)

SaveDoubleClickChoice persists the user's double-click action choice and updates the in-memory config so subsequent double-clicks use it immediately.

func SaveUserSetting

func SaveUserSetting(key, value string) error

SaveUserSetting updates a single dotted key (e.g. "preview.position") in the user's config file (~/.config/grut/config.toml).

If the file does not exist it is created with just the changed setting. The write is atomic: data is written to a temporary file in the same directory and then renamed over the target.

func SaveUserSettingBool

func SaveUserSettingBool(key string, value bool) error

SaveUserSettingBool updates a single dotted key with a boolean value. It behaves identically to SaveUserSetting but stores a native TOML boolean so that toml.Unmarshal decodes it correctly into Go bool fields.

func SetActionConfirmed

func SetActionConfirmed(itemType string) error

SetActionConfirmed persists the "always perform" flag for an item type.

func SetDoubleClickAction

func SetDoubleClickAction(itemType, action string) error

SetDoubleClickAction persists a double-click action override for an item type.

func SetRightClickAction

func SetRightClickAction(it actions.ItemType, action actions.ActionID) error

SetRightClickAction persists a right-click action override for an item type.

func Validate

func Validate(cfg *Config) error

Validate checks every field in cfg and returns all problems joined into a single error. Returns nil when the config is valid.

Types

type AIConfig

type AIConfig struct {
	ContextMode      string      `toml:"context_mode"`
	TokenModel       string      `toml:"token_model"`
	MCP              AIMCPConfig `toml:"mcp"`
	Provider         string      `toml:"provider"`          // "copilot" | "claude" | "none"
	FallbackProvider string      `toml:"fallback_provider"` // same enum or ""
	// Sub-feature configuration.
	Copilot          CopilotConfig     `toml:"copilot"`
	Review           ReviewConfig      `toml:"review"`
	Chat             ChatConfig        `toml:"chat"`
	Changelog        ChangelogConfig   `toml:"changelog"`
	RedactPatterns   []string          `toml:"redact_patterns"`
	Claude           ClaudeConfig      `toml:"claude"`
	Conflict         ConflictConfig    `toml:"conflict"`
	Temperature      float64           `toml:"temperature"`
	MaxContextFiles  int               `toml:"max_context_files"`
	MaxContextTokens int               `toml:"max_context_tokens"`
	CommitSplit      CommitSplitConfig `toml:"commit_split"`
	// Existing fields.
	AutoInstallDeps bool `toml:"auto_install_deps"`
	// Feature flags and provider selection.
	Enabled        bool `toml:"enabled"`
	AutoCommitMsg  bool `toml:"auto_commit_message"`
	AutoReviewDiff bool `toml:"auto_review_diff"`
}

AIConfig holds AI/LLM integration settings.

type AIMCPConfig

type AIMCPConfig struct {
	SocketPath string `toml:"socket_path"`
}

AIMCPConfig holds AI-specific MCP socket settings.

type ActionsConfig

type ActionsConfig struct {
	DoubleClick map[string]string `toml:"double_click"`
	RightClick  map[string]string `toml:"right_click"`
	Confirmed   map[string]bool   `toml:"confirmed"`
}

ActionsConfig controls double-click action overrides and first-use confirmations. Users can override the default double-click action for any item type and mark item types as "always confirmed" to skip the first-use prompt.

func (*ActionsConfig) GetDoubleClickAction

func (c *ActionsConfig) GetDoubleClickAction(itemType string) string

GetDoubleClickAction returns the configured double-click action for an item type, falling back to the registry default if no override is set.

func (*ActionsConfig) GetRightClickAction

func (c *ActionsConfig) GetRightClickAction(it actions.ItemType) actions.ActionID

GetRightClickAction returns the configured right-click action for an item type, falling back to the registry default if no override is set.

func (*ActionsConfig) IsConfirmed

func (c *ActionsConfig) IsConfirmed(itemType string) bool

IsConfirmed returns true if the user has confirmed (chosen "Always") for the given item type, meaning the first-use prompt should be skipped.

type BookmarksConfig

type BookmarksConfig struct {
	Paths         []string `toml:"paths"`
	ShowInSidebar bool     `toml:"show_in_sidebar"`
}

BookmarksConfig holds user-defined bookmark paths.

type ChangelogConfig

type ChangelogConfig struct {
	Format     string   `toml:"format"` // "keepachangelog"
	Categories []string `toml:"categories"`
}

ChangelogConfig controls AI-generated changelogs.

type ChatConfig

type ChatConfig struct {
	SystemPrompt    string `toml:"system_prompt"` // custom override
	CollapsedHeight int    `toml:"collapsed_height"`
	ExpandedHeight  int    `toml:"expanded_height"`
	Enabled         bool   `toml:"enabled"`
	RenderMarkdown  bool   `toml:"render_markdown"`
}

ChatConfig controls the embedded AI chat panel.

type ClaudeConfig

type ClaudeConfig struct {
	Model     string `toml:"model"`
	MaxTokens int    `toml:"max_tokens"`
}

ClaudeConfig holds Anthropic Claude model settings.

type CommitSplitConfig

type CommitSplitConfig struct {
	Threshold int `toml:"threshold"`
}

CommitSplitConfig controls automatic commit splitting.

type Config

type Config struct {
	Actions    ActionsConfig    `toml:"actions"`
	Terminal   TerminalConfig   `toml:"terminal"`
	Theme      ThemeConfig      `toml:"theme"`
	AI         AIConfig         `toml:"ai"`
	General    GeneralConfig    `toml:"general"`
	Shortcuts  ShortcutsConfig  `toml:"shortcuts"`
	MCP        MCPConfig        `toml:"mcp"`
	GitHub     GitHubConfig     `toml:"github"`
	Preview    PreviewConfig    `toml:"preview"`
	Logging    LoggingConfig    `toml:"logging"`
	FileTree   FileTreeConfig   `toml:"file_tree"`
	Bookmarks  BookmarksConfig  `toml:"bookmarks"`
	Extensions ExtensionsConfig `toml:"extensions"`
	Git        GitConfig        `toml:"git"`
	Session    SessionConfig    `toml:"session"`
}

Config is the top-level configuration for grut.

func Load

func Load() (*Config, error)

Load reads the embedded defaults, overlays the user config file (if it exists), validates the result, and returns the final Config.

func LoadDefaults

func LoadDefaults() (*Config, error)

LoadDefaults returns a Config built solely from the embedded defaults (defaults.toml), without reading any user config file. This is safe to call from multiple goroutines and does not touch the filesystem, making it ideal for test helpers that need a valid baseline config.

type ConflictConfig

type ConflictConfig struct {
	DefaultMode               string `toml:"default_mode"` // "auto" | "interactive"
	IncludeSurroundingContext int    `toml:"include_surrounding_context"`
	AutoAcceptHighConfidence  bool   `toml:"auto_accept_high_confidence"`
}

ConflictConfig controls AI-assisted merge-conflict resolution.

type CopilotConfig

type CopilotConfig struct {
	Model string `toml:"model"` // optional override
}

CopilotConfig holds GitHub Copilot model settings.

type CustomShortcut

type CustomShortcut struct {
	Name        string   `toml:"name"`
	Description string   `toml:"description"`
	Steps       []string `toml:"steps"`
}

CustomShortcut defines a user-created shortcut in the config file.

type Duration

type Duration struct {
	time.Duration
}

Duration wraps time.Duration with TOML string unmarshalling.

func (Duration) MarshalText

func (d Duration) MarshalText() ([]byte, error)

MarshalText serialises the duration back to a string.

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(text []byte) error

UnmarshalText parses a duration string like "2s" or "5m".

type ExtensionsConfig

type ExtensionsConfig struct {
	InstallDir      string `toml:"install_dir"`
	RegistryURL     string `toml:"registry_url"`
	LuaTimeoutMs    int    `toml:"lua_timeout_ms"`
	WasmMemoryLimit int    `toml:"wasm_memory_limit"`
	Enabled         bool   `toml:"enabled"`
	AutoUpdate      bool   `toml:"auto_update"`
}

ExtensionsConfig controls the extension/plugin system.

type FileTreeConfig

type FileTreeConfig struct {
	IconMode             string `toml:"icon_mode"`
	MaxDepth             int    `toml:"max_depth"`
	ShowHidden           bool   `toml:"show_hidden"`
	ShowIcons            bool   `toml:"show_icons"`
	SortDirectoriesFirst bool   `toml:"sort_directories_first"`
	GitStatusMarkers     bool   `toml:"git_status_markers"`
	FollowSymlinks       bool   `toml:"follow_symlinks"`
}

FileTreeConfig controls the file explorer pane.

type GeneralConfig

type GeneralConfig struct {
	KeybindingScheme string `toml:"keybinding_scheme"`
	DefaultLayout    string `toml:"default_layout"`
	AutoSaveSession  bool   `toml:"auto_save_session"`
	ShowFirstRunHelp bool   `toml:"show_first_run_help"`
}

GeneralConfig holds top-level UI and session preferences.

type GitConfig

type GitConfig struct {
	RefreshMethod           string   `toml:"refresh_method"`
	DefaultBranch           string   `toml:"default_branch"`
	WorktreeMergeMethod     string   `toml:"worktree_merge_method"`
	WorktreeOpenMode        string   `toml:"worktree_open_mode"`
	RefreshFallbackInterval Duration `toml:"refresh_fallback_interval"`
	AutoFetchInterval       Duration `toml:"auto_fetch_interval"`
	MaxLogEntries           int      `toml:"max_log_entries"`
	WorktreeFirst           bool     `toml:"worktree_first"`
	ShowCommitGraph         bool     `toml:"show_commit_graph"`
	SignCommits             bool     `toml:"sign_commits"`
}

GitConfig holds git integration settings.

type GitHubConfig

type GitHubConfig struct {
	Owner                  string `toml:"owner"`
	Repo                   string `toml:"repo"`
	DefaultIssueFilter     string `toml:"default_issue_filter"`
	DefaultPRFilter        string `toml:"default_pr_filter"`
	PollInterval           int    `toml:"poll_interval"`
	ReviewDiffContextLines int    `toml:"review_diff_context_lines"`
	AutoCheckoutPRBranch   bool   `toml:"auto_checkout_pr_branch"`
}

GitHubConfig holds GitHub integration settings.

func (*GitHubConfig) ResolveGitHubRepo

func (c *GitHubConfig) ResolveGitHubRepo(ctx context.Context, repoRoot string) (owner, repo string)

ResolveGitHubRepo returns the owner and repo for GitHub API calls. If config values are set, those are used. Otherwise, auto-detects from the git remote origin URL.

type LoggingConfig

type LoggingConfig struct {
	Level      string `toml:"level"`
	File       string `toml:"file"`
	MaxSizeMB  int    `toml:"max_size_mb"`
	MaxBackups int    `toml:"max_backups"`
}

LoggingConfig controls log output.

type MCPConfig

type MCPConfig struct {
	Security MCPSecurityConfig `toml:"security"`
}

MCPConfig holds MCP server security settings.

type MCPSecurityConfig

type MCPSecurityConfig struct {
	AuditLogPath        string   `toml:"audit_log_path"`
	AllowedCommands     []string `toml:"allowed_commands"`
	AllowedWritePaths   []string `toml:"allowed_write_paths"`
	RateLimitRead       int      `toml:"rate_limit_read"`
	RateLimitWrite      int      `toml:"rate_limit_write"`
	MaxAgentProcesses   int      `toml:"max_agent_processes"`
	AgentTimeout        int      `toml:"agent_timeout"`
	RequireConfirmation bool     `toml:"require_confirmation"`
	SocketAuth          bool     `toml:"socket_auth"`
	FollowSymlinks      bool     `toml:"follow_symlinks"`
	AuditLog            bool     `toml:"audit_log"`
}

MCPSecurityConfig controls MCP server security policies.

type PreviewConfig

type PreviewConfig struct {
	Position           string `toml:"position"`
	Theme              string `toml:"theme"`
	Width              int    `toml:"width"`
	MaxFileSize        int    `toml:"max_file_size"`
	Enabled            bool   `toml:"enabled"`
	SyntaxHighlighting bool   `toml:"syntax_highlighting"`
	LineNumbers        bool   `toml:"line_numbers"`
	WordWrap           bool   `toml:"word_wrap"`
	RenderMarkdown     bool   `toml:"render_markdown"`
}

PreviewConfig controls the file preview pane.

type ReviewConfig

type ReviewConfig struct {
	SeverityThreshold string   `toml:"severity_threshold"`
	Categories        []string `toml:"categories"`
	AutoReviewOnPush  bool     `toml:"auto_review_on_push"`
}

ReviewConfig controls AI-powered code review behaviour.

type SessionConfig

type SessionConfig struct {
	Enabled bool `toml:"enabled"`
	MaxAge  int  `toml:"max_age"` // days to keep sessions
}

SessionConfig controls session save/restore behaviour.

type ShortcutsConfig

type ShortcutsConfig struct {
	Overrides          map[string]bool  `toml:"overrides"`
	Custom             []CustomShortcut `toml:"custom"`
	Enabled            bool             `toml:"enabled"`
	AutoExecute        bool             `toml:"auto_execute"`
	InteractivePrompts bool             `toml:"interactive_prompts"`
}

ShortcutsConfig controls AI-powered git workflow shortcuts.

type TerminalConfig

type TerminalConfig struct {
	Shell      string `toml:"shell"`
	PrefixKey  string `toml:"prefix_key"`
	Scrollback int    `toml:"scrollback"`
	RenderFPS  int    `toml:"render_fps"`
}

TerminalConfig holds embedded terminal settings.

type ThemeConfig

type ThemeConfig struct {
	Name string `toml:"name"`
}

ThemeConfig holds UI theme selection.

Jump to

Keyboard shortcuts

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