| 41 | } |
| 42 | |
| 43 | func edit(editorCommand, fn, initialValue string, stdin io.Reader, stdout io.Writer, stderr io.Writer, cursor showable, lookPath func(string) ([]string, []string, error)) (string, error) { |
| 44 | // prepare the temp file |
| 45 | pattern := fn |
| 46 | if pattern == "" { |
| 47 | pattern = "survey*.txt" |
| 48 | } |
| 49 | f, err := os.CreateTemp("", pattern) |
| 50 | if err != nil { |
| 51 | return "", err |
| 52 | } |
| 53 | defer os.Remove(f.Name()) |
| 54 | |
| 55 | // write utf8 BOM header if necessary for the current platform and/or locale |
| 56 | if needsBom() { |
| 57 | if _, err := f.Write(bom); err != nil { |
| 58 | return "", err |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // write initial value |
| 63 | if _, err := f.WriteString(initialValue); err != nil { |
| 64 | return "", err |
| 65 | } |
| 66 | |
| 67 | // close the fd to prevent the editor unable to save file |
| 68 | if err := f.Close(); err != nil { |
| 69 | return "", err |
| 70 | } |
| 71 | |
| 72 | if editorCommand == "" { |
| 73 | editorCommand = defaultEditor |
| 74 | } |
| 75 | args, err := shellquote.Split(editorCommand) |
| 76 | if err != nil { |
| 77 | return "", err |
| 78 | } |
| 79 | args = append(args, f.Name()) |
| 80 | |
| 81 | editorExe, env, err := lookPath(args[0]) |
| 82 | if err != nil { |
| 83 | return "", err |
| 84 | } |
| 85 | args = append(editorExe, args[1:]...) |
| 86 | |
| 87 | cmd := exec.Command(args[0], args[1:]...) |
| 88 | cmd.Env = env |
| 89 | cmd.Stdin = stdin |
| 90 | cmd.Stdout = stdout |
| 91 | cmd.Stderr = stderr |
| 92 | |
| 93 | if cursor != nil { |
| 94 | _ = cursor.Show() |
| 95 | } |
| 96 | |
| 97 | // open the editor |
| 98 | if err := cmd.Run(); err != nil { |
| 99 | return "", err |
| 100 | } |