summaryrefslogtreecommitdiff
path: root/internal/askcli/command_edit.go
blob: 27c9106764758fd08e19be92210f602725d8506c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package askcli

import (
	"bytes"
	"context"
	"io"

	"codeberg.org/snonux/hexai/internal/editor"
)

// captureFromEditor opens the user's editor on a temporary file pre-filled with
// the given initial content and returns its trimmed contents after the editor
// exits. It is a variable so tests can stub it.
var captureFromEditor = func(initial []byte) (string, error) {
	return editor.OpenTempAndEdit(initial)
}

// handleEdit opens the configured editor on a temporary file. With no selector
// it creates a new task from the resulting content. With a task ID/UUID selector
// it pre-fills the editor with the task's current description and updates it.
func (d *Dispatcher) handleEdit(ctx context.Context, args []string, stdout, stderr io.Writer) (int, error) {
	if len(args) >= 2 {
		return d.editTaskDescription(ctx, args[1], stdout, stderr)
	}
	description, err := captureFromEditor(nil)
	if err != nil {
		writeInfoError(stderr, err)
		return 1, nil
	}
	if description == "" {
		_, _ = io.WriteString(stderr, "error: ask edit aborted: empty description\n")
		return 1, nil
	}
	return d.createTask(ctx, nil, description, nil, stdout, stderr)
}

// editTaskDescription resolves a task selector, opens the editor pre-filled with
// the task's current description, and modifies the task with the new content.
func (d *Dispatcher) editTaskDescription(ctx context.Context, selector string, stdout, stderr io.Writer) (int, error) {
	resolved, tasks, code, err := d.resolveTaskSelector(ctx, selector, stderr)
	if err != nil {
		writeInfoError(stderr, err)
		return code, nil
	}

	description, err := captureFromEditor([]byte(tasks[0].Description))
	if err != nil {
		writeInfoError(stderr, err)
		return 1, nil
	}
	if description == "" {
		_, _ = io.WriteString(stderr, "error: ask edit aborted: empty description\n")
		return 1, nil
	}

	var outBuf bytes.Buffer
	code, err = d.runner.Run(ctx, []string{"uuid:" + resolved.UUID, "modify", description}, nil, &outBuf, io.Discard)
	if code != 0 {
		return code, err
	}
	_, _ = io.WriteString(stdout, FormatSuccess(displayResolvedTaskID(resolved)))
	return 0, nil
}