captureInput opens a temporary file in a text editor and returns the written bytes on success or an error on failure. It handles deletion of the temporary file behind the scenes. If given default contents, it will write that to the file before popping open the editor.
(contents []byte, pattern string, infoFn func(), fileCreatedFn func(string))
| 75 | // If given default contents, it will write that to the file before popping |
| 76 | // open the editor. |
| 77 | func (p *editorPrompt) captureInput(contents []byte, pattern string, infoFn func(), fileCreatedFn func(string)) ([]byte, error) { |
| 78 | dir, err := os.MkdirTemp("", pattern) |
| 79 | if err != nil { |
| 80 | return []byte{}, err |
| 81 | } |
| 82 | defer func() { |
| 83 | _ = os.Remove(dir) |
| 84 | }() |
| 85 | |
| 86 | file, err := os.CreateTemp(dir, pattern) |
| 87 | if err != nil { |
| 88 | return []byte{}, err |
| 89 | } |
| 90 | |
| 91 | filename := file.Name() |
| 92 | |
| 93 | if fileCreatedFn != nil { |
| 94 | go fileCreatedFn(filename) |
| 95 | } |
| 96 | |
| 97 | // Defer removal of the temporary file in case any of the next steps fail. |
| 98 | defer func() { |
| 99 | _ = os.Remove(filename) |
| 100 | }() |
| 101 | |
| 102 | // Write utf8 BOM header |
| 103 | // The reason why we do this is because notepad.exe on Windows determines the |
| 104 | // encoding of an "empty" text file by the locale, for example, GBK in China, |
| 105 | // while golang string only handles utf8 well. However, a text file with utf8 |
| 106 | // BOM header is not considered "empty" on Windows, and the encoding will then |
| 107 | // be determined utf8 by notepad.exe, instead of GBK or other encodings. |
| 108 | if _, err := file.Write(bom); err != nil { |
| 109 | return nil, err |
| 110 | } |
| 111 | |
| 112 | if len(contents) > 0 { |
| 113 | if _, err := file.Write(contents); err != nil { |
| 114 | return nil, fmt.Errorf("failed to write to file: %w", err) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | if err = file.Close(); err != nil { |
| 119 | return nil, err |
| 120 | } |
| 121 | |
| 122 | if err = p.openFile(filename, infoFn); err != nil { |
| 123 | return nil, err |
| 124 | } |
| 125 | |
| 126 | raw, err := os.ReadFile(filename) |
| 127 | if err != nil { |
| 128 | return []byte{}, err |
| 129 | } |
| 130 | |
| 131 | // Strip BOM header. |
| 132 | return bytes.TrimPrefix(raw, bom), nil |
| 133 | } |
| 134 |
no test coverage detected