OpenEditor opens an editor, and returns the content (not path) of the modified yaml. OpenEditor returns nil when the file was saved as an empty file, optionally with whitespaces.
(ctx context.Context, content []byte, hdr string)
| 58 | // |
| 59 | // OpenEditor returns nil when the file was saved as an empty file, optionally with whitespaces. |
| 60 | func OpenEditor(ctx context.Context, content []byte, hdr string) ([]byte, error) { |
| 61 | editor := editorcmd.Detect() |
| 62 | if editor == "" { |
| 63 | return nil, errors.New("could not detect a text editor binary, try setting $EDITOR") |
| 64 | } |
| 65 | tmpYAMLFile, err := os.CreateTemp("", "lima-editor-") |
| 66 | if err != nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | tmpYAMLPath := tmpYAMLFile.Name() |
| 70 | defer os.RemoveAll(tmpYAMLPath) |
| 71 | if _, err := tmpYAMLFile.Write(append([]byte(hdr), content...)); err != nil { |
| 72 | tmpYAMLFile.Close() |
| 73 | return nil, err |
| 74 | } |
| 75 | if err := tmpYAMLFile.Close(); err != nil { |
| 76 | return nil, err |
| 77 | } |
| 78 | |
| 79 | editorCmd := exec.CommandContext(ctx, editor, tmpYAMLPath) |
| 80 | editorCmd.Env = os.Environ() |
| 81 | editorCmd.Stdin = os.Stdin |
| 82 | editorCmd.Stdout = os.Stdout |
| 83 | editorCmd.Stderr = os.Stderr |
| 84 | logrus.Debugf("opening editor %#q for a file %#q", editor, tmpYAMLPath) |
| 85 | if err := editorCmd.Run(); err != nil { |
| 86 | return nil, fmt.Errorf("could not execute editor %#q for a file %#q: %w", editor, tmpYAMLPath, err) |
| 87 | } |
| 88 | b, err := os.ReadFile(tmpYAMLPath) |
| 89 | if err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 | modifiedInclHdr := string(b) |
| 93 | modifiedExclHdr := strings.TrimPrefix(modifiedInclHdr, hdr) |
| 94 | if strings.TrimSpace(modifiedExclHdr) == "" { |
| 95 | return nil, nil |
| 96 | } |
| 97 | return []byte(modifiedExclHdr), nil |
| 98 | } |