run.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package at
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "os"
  8. "kitty/tools/tty"
  9. )
  10. var _ = fmt.Print
  11. type run_response_data struct {
  12. Stdout string `json:"stdout"`
  13. Stderr string `json:"stderr"`
  14. Exit_code int `json:"exit_code"`
  15. Exit_status int `json:"exit_status"`
  16. }
  17. func run_handle_response(data []byte) error {
  18. var r run_response_data
  19. if err := json.Unmarshal(data, &r); err != nil {
  20. return err
  21. }
  22. if stdout, err := base64.StdEncoding.DecodeString(r.Stdout); err == nil {
  23. _, _ = os.Stdout.Write(stdout)
  24. } else {
  25. return err
  26. }
  27. if stderr, err := base64.StdEncoding.DecodeString(r.Stderr); err == nil {
  28. _, _ = os.Stderr.Write(stderr)
  29. } else {
  30. return err
  31. }
  32. if r.Exit_code != 0 {
  33. return &exit_error{r.Exit_code}
  34. }
  35. return nil
  36. }
  37. func read_run_data(io_data *rc_io_data, args []string, payload *run_json_type) (func(io_data *rc_io_data) (bool, error), error) {
  38. is_first_call := true
  39. is_tty := tty.IsTerminal(os.Stdin.Fd())
  40. buf := make([]byte, 4096)
  41. cmdline := make([]escaped_string, len(args))
  42. for i, s := range args {
  43. cmdline[i] = escaped_string(s)
  44. }
  45. payload.Cmdline = cmdline
  46. io_data.handle_response = run_handle_response
  47. return func(io_data *rc_io_data) (bool, error) {
  48. if is_first_call {
  49. is_first_call = false
  50. } else {
  51. io_data.rc.Stream = false
  52. }
  53. buf = buf[:cap(buf)]
  54. var n int
  55. var err error
  56. if is_tty {
  57. buf = buf[:0]
  58. err = io.EOF
  59. } else {
  60. n, err = os.Stdin.Read(buf)
  61. if err != nil && err != io.EOF {
  62. return false, err
  63. }
  64. buf = buf[:n]
  65. }
  66. set_payload_data(io_data, base64.StdEncoding.EncodeToString(buf))
  67. if err == io.EOF {
  68. return true, nil
  69. }
  70. return false, nil
  71. }, nil
  72. }