feat: toml config support (#9)

## What's new
- TOML config support 
- add config init command to justfile
https://github.com/versenilvis/IRIS/pull/9/commits/a5bb6c23d74ca73385b3590d2eb275ce6429906b
- add copy binary file to local bin on reload
https://github.com/versenilvis/IRIS/pull/9/commits/4da3acdbc58c28f20fa0021d15fec82823ba392b
- init config on setup
https://github.com/versenilvis/IRIS/pull/9/commits/fb48b6bb832f38e24fab9211d92858bab9a58a07

## Fix
- add lsof to support macos because /proc filesystem is Linux-specific
and does not exist on macOS 0439d829573864fcf902fc4127f7d45384bfab01
- git push doesnt suggest current branch, fix
https://github.com/versenilvis/IRIS/pull/9/commits/b498532b401b764a4a1a2c70b3cb44b7caf72320
- use timeout context for lsof command in reload handler
https://github.com/versenilvis/IRIS/pull/9/commits/1a2baee951e6538a729da12aedfe53960e51102d
This commit is contained in:
VERSE
2026-05-30 22:05:06 +07:00
committed by GitHub
parent 8556fa626a
commit 3d76a3ee88
21 changed files with 1064 additions and 160 deletions
+104
View File
@@ -0,0 +1,104 @@
package root
import (
"fmt"
"os"
"path/filepath"
"github.com/BurntSushi/toml"
"github.com/spf13/cobra"
"github.com/versenilvis/iris/config"
)
var ConfigCmd = &cobra.Command{
Use: "config",
Short: "manage iris configuration",
}
var ConfigInitCmd = &cobra.Command{
Use: "init",
Short: "initialize default configuration file with comments",
Run: func(cmd *cobra.Command, args []string) {
path, err := config.ConfigPath()
if err != nil {
fmt.Printf("failed to get config path: %v\n", err)
return
}
if _, statErr := os.Stat(path); statErr == nil {
fmt.Printf("config file already exists at %s\n", path)
return
}
_ = os.MkdirAll(filepath.Dir(path), 0755)
defaultContent := `# ~/.config/iris/config.toml
# iris configuration file
[core]
# schema version
# do not edit this field manually
version = 1
# override shell: "bash", "zsh", "fish", keep empty for auto detection
shell = ""
# startup mode: "last", "spec", "history"
# "last" = remember last mode used
mode = "last"
# enable debug logging
debug = false
[ui]
# enable inline ghost text
ghost-text = true
# maximum suggestions to display
max-suggestions = 100
# maximum height of the overlay
max-height = 15
[git]
# hide current branch in checkout/switch list
filter-active-branch = true
# merge remote and local branches with same name
deduplicate-branches = true
[updater]
# check for updates on startup
check-on-startup = true
# update channel: "stable", "nightly"
channel = "stable"
# interval between update checks, e.g. "24h", "6h", "30m"
check-interval = "24h"
`
err = os.WriteFile(path, []byte(defaultContent), 0644)
if err != nil {
fmt.Printf("failed to write config file: %v\n", err)
return
}
fmt.Printf("initialized config file at %s\n", path)
},
}
var ConfigShowCmd = &cobra.Command{
Use: "show",
Short: "show the resolved configuration",
Run: func(cmd *cobra.Command, args []string) {
enc := toml.NewEncoder(cmd.OutOrStdout())
if err := enc.Encode(config.Get()); err != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "failed to encode config: %v\n", err)
}
},
}
func init() {
ConfigCmd.AddCommand(ConfigInitCmd)
ConfigCmd.AddCommand(ConfigShowCmd)
rootCmd.AddCommand(ConfigCmd)
}
+43 -19
View File
@@ -11,6 +11,7 @@ import (
"time"
"github.com/spf13/cobra"
"github.com/versenilvis/iris/config"
)
// startRescueShell starts a fallback shell if the application crashes to keep the terminal open
@@ -29,11 +30,10 @@ var (
// writeCrashLog writes the crash info and stack trace to a new log file
func WriteCrashLog(err any) {
home, errDir := os.UserHomeDir()
dir, errDir := config.CrashDir()
if errDir != nil {
return
}
dir := filepath.Join(home, ".iris", "crashes")
_ = os.MkdirAll(dir, 0755)
logFile := filepath.Join(dir, fmt.Sprintf("crash_%s.log", time.Now().Format("20060102_150405")))
@@ -66,16 +66,36 @@ func WriteCrashLog(err any) {
// getLatestCrashLog returns the path to the newest crash log file
func getLatestCrashLog() string {
home, err := os.UserHomeDir()
if err != nil {
dir, errDir := config.CrashDir()
if errDir != nil {
return ""
}
dir := filepath.Join(home, ".iris", "crashes")
files, err := os.ReadDir(dir)
if err != nil || len(files) == 0 {
oldLog := filepath.Join(home, ".iris", "crash.log")
if _, err := os.Stat(oldLog); err == nil {
return oldLog
home, errHome := os.UserHomeDir()
if errHome == nil {
oldLog := filepath.Join(home, ".iris", "crash.log")
if _, err := os.Stat(oldLog); err == nil {
return oldLog
}
oldCrashes := filepath.Join(home, ".iris", "crashes")
if oldFiles, errOld := os.ReadDir(oldCrashes); errOld == nil && len(oldFiles) > 0 {
var latestOld string
for _, f := range oldFiles {
if f.IsDir() {
continue
}
name := f.Name()
if strings.HasPrefix(name, "crash_") && strings.HasSuffix(name, ".log") {
if name > latestOld {
latestOld = name
}
}
}
if latestOld != "" {
return filepath.Join(oldCrashes, latestOld)
}
}
}
return ""
}
@@ -93,9 +113,12 @@ func getLatestCrashLog() string {
}
}
if latest == "" {
oldLog := filepath.Join(home, ".iris", "crash.log")
if _, err := os.Stat(oldLog); err == nil {
return oldLog
home, errHome := os.UserHomeDir()
if errHome == nil {
oldLog := filepath.Join(home, ".iris", "crash.log")
if _, err := os.Stat(oldLog); err == nil {
return oldLog
}
}
return ""
}
@@ -119,15 +142,16 @@ var (
Use: "crash-log",
Short: "manage iris crash logs",
Run: func(cmd *cobra.Command, args []string) {
home, err := os.UserHomeDir()
if err != nil {
cmd.Printf("failed to get home directory: %v\n", err)
return
}
if ClearLog {
_ = os.RemoveAll(filepath.Join(home, ".iris", "crashes"))
_ = os.Remove(filepath.Join(home, ".iris", "crash.log"))
dir, errDir := config.CrashDir()
if errDir == nil {
_ = os.RemoveAll(dir)
}
home, errHome := os.UserHomeDir()
if errHome == nil {
_ = os.RemoveAll(filepath.Join(home, ".iris", "crashes"))
_ = os.Remove(filepath.Join(home, ".iris", "crash.log"))
}
cmd.Println("crash log cleared")
return
}
+56
View File
@@ -7,6 +7,7 @@ import (
"strings"
"github.com/spf13/cobra"
"github.com/versenilvis/iris/config"
)
var initCmd = &cobra.Command{
@@ -120,6 +121,61 @@ var setupCmd = &cobra.Command{
fmt.Printf("✓ Added iris integration to %s\n", configFile)
}
// initialize default config file if it does not exist
if path, err := config.ConfigPath(); err == nil {
if _, statErr := os.Stat(path); os.IsNotExist(statErr) {
_ = os.MkdirAll(filepath.Dir(path), 0755)
defaultContent := `# ~/.config/iris/config.toml
# iris configuration file
[core]
# schema version
# do not edit this field manually
version = 1
# override shell: "bash", "zsh", "fish", keep empty for auto detection
shell = ""
# startup mode: "last", "spec", "history"
# "last" = remember last mode used
mode = "last"
# enable debug logging
debug = false
[ui]
# enable inline ghost text
ghost-text = true
# maximum suggestions to display
max-suggestions = 100
# maximum height of the overlay
max-height = 15
[git]
# hide current branch in checkout/switch list
filter-active-branch = true
# merge remote and local branches with same name
deduplicate-branches = true
[updater]
# check for updates on startup
check-on-startup = true
# update channel: "stable", "nightly"
channel = "stable"
# interval between update checks, e.g. "24h", "6h", "30m"
check-interval = "24h"
`
if errWrite := os.WriteFile(path, []byte(defaultContent), 0644); errWrite == nil {
fmt.Printf("✓ Initialized default config file at %s\n", path)
}
}
}
fmt.Println("\nSetup complete! Please restart your terminal or run:")
fmt.Printf(" source %s\n", configFile)
},
+28 -6
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"syscall"
@@ -18,6 +19,7 @@ import (
_ "github.com/versenilvis/iris/commands/runner"
_ "github.com/versenilvis/iris/commands/search"
_ "github.com/versenilvis/iris/commands/view"
"github.com/versenilvis/iris/config"
"golang.org/x/term"
)
@@ -44,12 +46,6 @@ It works exactly like coding editor suggestion menu drop down.`,
return
}
}
if debugMode {
f, _ := os.OpenFile("iris.log", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
debugLogger = f
core.DebugWriter = f
_, _ = fmt.Fprintf(debugLogger, "--- IRIS DEBUG LOG ---\n")
}
runWrapper()
},
}
@@ -61,6 +57,25 @@ It works exactly like coding editor suggestion menu drop down.`,
func init() {
rootCmd.PersistentFlags().StringVarP(&shellFlag, "shell", "s", "", "shell to use (bash, zsh, fish)")
rootCmd.PersistentFlags().BoolVarP(&debugMode, "debug", "d", false, "enable debug logging to iris.log")
rootCmd.PersistentPreRun = func(cmd *cobra.Command, args []string) {
if shellFlag != "" {
config.Get().Core.Shell = shellFlag
}
if debugMode {
config.Get().Core.Debug = true
}
if config.Get().Core.Debug {
logDir, err := config.CachePath()
if err == nil {
_ = os.MkdirAll(logDir, 0755)
f, _ := os.OpenFile(filepath.Join(logDir, "iris.log"), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
debugLogger = f
core.DebugWriter = f
_, _ = fmt.Fprintf(debugLogger, "--- IRIS DEBUG LOG ---\n")
}
}
}
}
func debugLog(format string, a ...any) {
@@ -186,6 +201,13 @@ func runOriginal() {
}
func Execute() {
_ = config.MigrateFromLegacyJSON()
cfg, err := config.Load()
if err != nil {
fmt.Fprintf(os.Stderr, "[IRIS] config error: %v\n", err)
}
config.Init(cfg)
if os.Getenv("IRIS_IS_CHILD") != "true" {
runWatchdog()
return
+5 -3
View File
@@ -5,6 +5,7 @@ import (
"strings"
"github.com/versenilvis/iris/commands/core"
"github.com/versenilvis/iris/config"
"github.com/versenilvis/iris/integration"
)
@@ -16,6 +17,7 @@ func MergeResults(query string, mode string) []core.Suggestion {
return nil
}
maxSugg := config.Get().UI.MaxSuggestions
normalizedQuery := strings.TrimSpace(query)
seen := make(map[string]bool)
deduped := []core.Suggestion{}
@@ -33,7 +35,7 @@ func MergeResults(query string, mode string) []core.Suggestion {
Desc: " history",
Icon: fmt.Sprintf("%d", h.ID),
})
if len(deduped) >= 100 {
if len(deduped) >= maxSugg {
break
}
}
@@ -57,8 +59,8 @@ func MergeResults(query string, mode string) []core.Suggestion {
deduped = append(deduped, s)
}
}
if len(deduped) > 100 {
deduped = deduped[:100]
if len(deduped) > maxSugg {
deduped = deduped[:maxSugg]
}
return deduped
}
+41 -63
View File
@@ -7,23 +7,14 @@ import (
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/versenilvis/iris/config"
)
// updateState holds the persistent update notification state on disk
type updateState struct {
// seenVersion is the last version the user was notified about.
// when a newer release than this is found, we show the message again
SeenVersion string `json:"seen_version"`
// lastCheck is unix timestamp of the last network check
LastCheck int64 `json:"last_check"`
}
// updateResult is passed from the async checker to the main loop
type updateResult struct {
latestVersion string
@@ -33,49 +24,18 @@ type updateResult struct {
// pendingUpdate is set by the background goroutine and consumed once after the first IRIS_CMD_STOP
var pendingUpdate chan updateResult
func getUpdateStateFile() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".iris", "update_state.json")
}
func LoadUpdateState() updateState {
file := getUpdateStateFile()
if file == "" {
return updateState{}
}
data, err := os.ReadFile(file)
if err != nil {
return updateState{}
}
var s updateState
if err := json.Unmarshal(data, &s); err != nil {
return updateState{}
}
return s
}
func SaveUpdateState(s updateState) {
file := getUpdateStateFile()
if file == "" {
return
}
data, _ := json.MarshalIndent(s, "", " ")
_ = os.MkdirAll(filepath.Dir(file), 0755)
_ = os.WriteFile(file, data, 0644)
}
// FetchLatestVersion hits the GitHub Releases API and returns the latest tag name
func FetchLatestVersion() (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// allow overriding the version endpoint for testing without a real release
endpoint := os.Getenv("IRIS_UPDATE_URL")
if endpoint == "" {
endpoint = "https://api.github.com/repos/versenilvis/iris/releases/latest"
if config.Get().Updater.Channel == "nightly" {
endpoint = "https://api.github.com/repos/versenilvis/iris/releases"
} else {
endpoint = "https://api.github.com/repos/versenilvis/iris/releases/latest"
}
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
@@ -99,6 +59,19 @@ func FetchLatestVersion() (string, error) {
return "", err
}
if config.Get().Updater.Channel == "nightly" && os.Getenv("IRIS_UPDATE_URL") == "" {
var releases []struct {
TagName string `json:"tag_name"`
}
if err := json.Unmarshal(body, &releases); err != nil {
return "", err
}
if len(releases) == 0 {
return "", fmt.Errorf("no releases found")
}
return releases[0].TagName, nil
}
var result struct {
TagName string `json:"tag_name"`
}
@@ -123,7 +96,7 @@ func IsNewer(current, latest string) bool {
}
// nightly builds are never shown as stable update targets
if strings.Contains(l, "-nightly.") {
if config.Get().Updater.Channel != "nightly" && strings.Contains(l, "-nightly.") {
return false
}
@@ -161,6 +134,11 @@ func IsNewer(current, latest string) bool {
func startBackgroundUpdateCheck() chan updateResult {
ch := make(chan updateResult, 1)
if !config.Get().Updater.CheckOnStartup {
close(ch)
return ch
}
go func() {
defer func() {
if r := recover(); r != nil {
@@ -181,13 +159,13 @@ func startBackgroundUpdateCheck() chan updateResult {
return
}
state := LoadUpdateState()
state := config.LoadState()
// only check once every 6 hours to avoid hammering the API
if time.Since(time.Unix(state.LastCheck, 0)) < 6*time.Hour {
// only check once every configured check-interval to avoid hammering the API
if time.Since(state.Updater.LastCheckTime) < time.Duration(config.Get().Updater.CheckInterval) {
// already checked recently; still notify if we have a cached pending update
if state.SeenVersion != "" && IsNewer(Version, state.SeenVersion) {
ch <- updateResult{latestVersion: state.SeenVersion, hasUpdate: true}
if state.Updater.SeenVersion != "" && IsNewer(Version, state.Updater.SeenVersion) {
ch <- updateResult{latestVersion: state.Updater.SeenVersion, hasUpdate: true}
}
return
}
@@ -199,22 +177,22 @@ func startBackgroundUpdateCheck() chan updateResult {
}
// update the last check time regardless of result
state.LastCheck = time.Now().Unix()
state.Updater.LastCheckTime = time.Now()
if IsNewer(Version, latest) {
// only notify if user hasn't already seen this specific version notification
if state.SeenVersion != latest {
if state.Updater.SeenVersion != latest {
ch <- updateResult{latestVersion: latest, hasUpdate: true}
}
// save the latest as seen_version so future sessions don't re-notify
// unless a NEWER version comes out (different tag)
state.SeenVersion = latest
state.Updater.SeenVersion = latest
} else {
// up to date: clear the seen_version flag so the next update triggers a fresh notification
state.SeenVersion = ""
state.Updater.SeenVersion = ""
}
SaveUpdateState(state)
_ = config.SaveState(state)
}()
return ch
@@ -256,9 +234,9 @@ var updateCmd = &cobra.Command{
if !IsNewer(Version, latest) {
fmt.Printf("\033[32m[IRIS] already up to date (%s)\033[0m\n", Version)
// clear seen_version so the notification doesn't show again
state := LoadUpdateState()
state.SeenVersion = ""
SaveUpdateState(state)
state := config.LoadState()
state.Updater.SeenVersion = ""
_ = config.SaveState(state)
return
}
@@ -269,9 +247,9 @@ var updateCmd = &cobra.Command{
fmt.Printf("running: curl -sS %s | sh\n\n", installScript)
// after a successful update, mark as seen so no more notifications
state := LoadUpdateState()
state.SeenVersion = ""
SaveUpdateState(state)
state := config.LoadState()
state.Updater.SeenVersion = ""
_ = config.SaveState(state)
fmt.Printf("\n\033[32m[IRIS] restart your terminal to use the new version\033[0m\n")
},
+30 -35
View File
@@ -4,13 +4,11 @@ import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"sync"
"sync/atomic"
@@ -19,51 +17,32 @@ import (
"github.com/creack/pty"
"github.com/versenilvis/iris/commands/core"
"github.com/versenilvis/iris/config"
"github.com/versenilvis/iris/integration"
"github.com/versenilvis/iris/integration/shell"
"golang.org/x/sys/unix"
"golang.org/x/term"
)
type State struct {
Mode string `json:"mode"`
}
func getStateFile() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
dir := filepath.Join(home, ".iris")
_ = os.MkdirAll(dir, 0755)
return filepath.Join(dir, "state.json")
}
func loadMode() string {
file := getStateFile()
if file != "" {
data, err := os.ReadFile(file)
if err == nil {
var state State
if err := json.Unmarshal(data, &state); err == nil {
if state.Mode == "history" || state.Mode == "spec" {
return state.Mode
}
}
mode := config.Get().Core.Mode
if mode == "last" {
state := config.LoadState()
if state.LastMode == "history" || state.LastMode == "spec" {
return state.LastMode
}
return "spec"
}
if mode == "history" || mode == "spec" {
return mode
}
return "spec"
}
func saveMode(mode string) {
file := getStateFile()
if file != "" {
state := State{Mode: mode}
data, err := json.MarshalIndent(state, "", " ")
if err == nil {
_ = os.WriteFile(file, data, 0644)
}
}
state := config.LoadState()
state.LastMode = mode
_ = config.SaveState(state)
}
var (
@@ -160,7 +139,22 @@ func runWrapper() {
}
if c.Process != nil {
if cwd, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", c.Process.Pid)); err == nil {
cwd, err := os.Readlink(fmt.Sprintf("/proc/%d/cwd", c.Process.Pid))
if err != nil {
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
out, errCmd := exec.CommandContext(ctx, "lsof", "-p", fmt.Sprintf("%d", c.Process.Pid), "-a", "-d", "cwd", "-F", "n").Output()
cancel()
if errCmd == nil {
for _, line := range strings.Split(string(out), "\n") {
if strings.HasPrefix(line, "n") {
cwd = strings.TrimSpace(line[1:])
err = nil
break
}
}
}
}
if err == nil {
_ = os.Chdir(cwd)
}
_ = syscall.Kill(c.Process.Pid, syscall.SIGKILL)
@@ -205,6 +199,7 @@ func runWrapper() {
}()
var disableGhostText atomic.Bool
disableGhostText.Store(!config.Get().UI.GhostText)
var userNavigated bool
var renderOverlay func()