util.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Package util provides utility functions for UI message handling.
  2. package util
  3. import (
  4. "context"
  5. "errors"
  6. "os/exec"
  7. "time"
  8. tea "charm.land/bubbletea/v2"
  9. "mvdan.cc/sh/v3/shell"
  10. )
  11. type Cursor interface {
  12. Cursor() *tea.Cursor
  13. }
  14. func CmdHandler(msg tea.Msg) tea.Cmd {
  15. return func() tea.Msg {
  16. return msg
  17. }
  18. }
  19. func ReportError(err error) tea.Cmd {
  20. return CmdHandler(NewErrorMsg(err))
  21. }
  22. type InfoType int
  23. const (
  24. InfoTypeInfo InfoType = iota
  25. InfoTypeSuccess
  26. InfoTypeWarn
  27. InfoTypeError
  28. InfoTypeUpdate
  29. )
  30. func NewInfoMsg(info string) InfoMsg {
  31. return InfoMsg{
  32. Type: InfoTypeInfo,
  33. Msg: info,
  34. }
  35. }
  36. func NewWarnMsg(warn string) InfoMsg {
  37. return InfoMsg{
  38. Type: InfoTypeWarn,
  39. Msg: warn,
  40. }
  41. }
  42. func NewErrorMsg(err error) InfoMsg {
  43. return InfoMsg{
  44. Type: InfoTypeError,
  45. Msg: err.Error(),
  46. }
  47. }
  48. func ReportInfo(info string) tea.Cmd {
  49. return CmdHandler(NewInfoMsg(info))
  50. }
  51. func ReportWarn(warn string) tea.Cmd {
  52. return CmdHandler(NewWarnMsg(warn))
  53. }
  54. type (
  55. InfoMsg struct {
  56. Type InfoType
  57. Msg string
  58. TTL time.Duration
  59. }
  60. ClearStatusMsg struct{}
  61. )
  62. // IsEmpty checks if the [InfoMsg] is empty.
  63. func (m InfoMsg) IsEmpty() bool {
  64. var zero InfoMsg
  65. return m == zero
  66. }
  67. // ExecShell parses a shell command string and executes it with exec.Command.
  68. // Uses shell.Fields for proper handling of shell syntax like quotes and
  69. // arguments while preserving TTY handling for terminal editors.
  70. func ExecShell(ctx context.Context, cmdStr string, callback tea.ExecCallback) tea.Cmd {
  71. fields, err := shell.Fields(cmdStr, nil)
  72. if err != nil {
  73. return ReportError(err)
  74. }
  75. if len(fields) == 0 {
  76. return ReportError(errors.New("empty command"))
  77. }
  78. cmd := exec.CommandContext(ctx, fields[0], fields[1:]...)
  79. return tea.ExecProcess(cmd, callback)
  80. }