util.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package util
  2. import (
  3. "log/slog"
  4. "os"
  5. "os/exec"
  6. "runtime"
  7. "strings"
  8. "time"
  9. tea "github.com/charmbracelet/bubbletea/v2"
  10. )
  11. func CmdHandler(msg tea.Msg) tea.Cmd {
  12. return func() tea.Msg {
  13. return msg
  14. }
  15. }
  16. func Clamp(v, low, high int) int {
  17. // Swap if needed to ensure low <= high
  18. if high < low {
  19. low, high = high, low
  20. }
  21. return min(high, max(low, v))
  22. }
  23. func IsWsl() bool {
  24. // Check for WSL environment variables
  25. if os.Getenv("WSL_DISTRO_NAME") != "" {
  26. return true
  27. }
  28. // Check /proc/version for WSL signature
  29. if data, err := os.ReadFile("/proc/version"); err == nil {
  30. version := strings.ToLower(string(data))
  31. return strings.Contains(version, "microsoft") || strings.Contains(version, "wsl")
  32. }
  33. return false
  34. }
  35. func Measure(tag string) func(...any) {
  36. startTime := time.Now()
  37. return func(args ...any) {
  38. args = append(args, []any{"timeTakenMs", time.Since(startTime).Milliseconds()}...)
  39. slog.Debug(tag, args...)
  40. }
  41. }
  42. func GetEditor() string {
  43. if editor := os.Getenv("VISUAL"); editor != "" {
  44. return editor
  45. }
  46. if editor := os.Getenv("EDITOR"); editor != "" {
  47. return editor
  48. }
  49. commonEditors := []string{"vim", "nvim", "zed", "code", "cursor", "vi", "nano"}
  50. if runtime.GOOS == "windows" {
  51. commonEditors = []string{"vim", "nvim", "zed", "code.cmd", "cursor.cmd", "notepad.exe", "vi", "nano"}
  52. }
  53. for _, editor := range commonEditors {
  54. if _, err := exec.LookPath(editor); err == nil {
  55. return editor
  56. }
  57. }
  58. return ""
  59. }