Files
pipelines/internal/tui/create.go
T

188 lines
5.3 KiB
Go

package tui
import (
"context"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/charmbracelet/bubbles/key"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"git.a-wan.net/alan/pipelines/internal/client"
"git.a-wan.net/alan/pipelines/internal/draft"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
type editedMsg struct {
name, path, source string
err error
confirm bool
unchanged bool
createOnly bool
baseVersion int
}
func (m Model) formView(height int) string {
label := map[int]string{1: "Pipeline name", 2: "Stage names (comma-separated)", 3: "Connect stages linearly? (y/n)"}[m.formStep]
width := min(54, max(1, m.width-8))
field := m.field
field.Width = max(1, width-2)
lines := []string{
lipgloss.NewStyle().Bold(true).Render(fmt.Sprintf("New pipeline · %d/3", m.formStep)),
"", label, "", field.View(),
}
if m.formError != "" {
lines = append(lines, "", lipgloss.NewStyle().Foreground(themeError).Render(m.formError))
}
for i := range lines {
lines[i] = ansi.Truncate(lines[i], width, "…")
}
dialog := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).BorderForeground(themeAccent).
Padding(1, 2).Width(width + 4).Render(strings.Join(lines, "\n"))
// Tiny terminals use a compact form rather than clipping away the input.
if lipgloss.Width(dialog) > m.width || lipgloss.Height(dialog) > height {
lines = []string{label, field.View(), m.formError}
if len(lines) > height {
lines = lines[:height]
}
for i := range lines {
lines[i] = ansi.Truncate(lines[i], m.width, "…")
}
dialog = strings.Join(lines, "\n")
}
return lipgloss.Place(m.width, height, lipgloss.Center, lipgloss.Center, dialog)
}
func (m Model) send(request protocol.Message) tea.Cmd {
return func() tea.Msg {
ctx, cancel := context.WithTimeout(m.ctx, 10*time.Second)
defer cancel()
if err := client.Send(ctx, m.conn, request); err != nil {
return errorMsg{err: err, conn: m.conn}
}
return sentMsg{request.ID}
}
}
func (m Model) updateForm(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
if msg.String() == "ctrl+c" {
return m, tea.Quit
}
if key.Matches(msg, m.keys.cancel) {
m.formStep = 0
m.keys.form = false
return m, nil
}
if !key.Matches(msg, m.keys.enter) {
var cmd tea.Cmd
m.field, cmd = m.field.Update(msg)
return m, cmd
}
value := strings.TrimSpace(m.field.Value())
m.formError = ""
switch m.formStep {
case 1:
if value == "" {
m.formError = "Name is required"
return m, nil
}
m.draftName = value
m.formStep = 2
m.field.CharLimit = 4096
m.field.Placeholder = "implementer, reviewer"
case 2:
names, err := pipeline.StageNames(value)
if err != nil {
m.formError = err.Error()
return m, nil
}
m.draftStages = names
m.formStep = 3
m.field.Placeholder = "y or n"
case 3:
if value != "y" && value != "n" {
m.formError = "Enter y or n"
return m, nil
}
m.formStep = 0
m.keys.form = false
return m, editDraftMode(m.draftName, pipeline.Template(m.draftStages, value == "y"), true, true, draft.Draft{Server: m.url})
}
m.field.SetValue("")
return m, nil
}
func editDraft(name, source string, confirm ...bool) tea.Cmd {
needsConfirm := len(confirm) > 0 && confirm[0]
return editDraftMode(name, source, needsConfirm, false)
}
func editDraftMode(name, source string, needsConfirm, fresh bool, metadata ...draft.Draft) tea.Cmd {
editor, args, err := draftEditor()
if err != nil {
return func() tea.Msg { return editedMsg{name: name, err: err} }
}
var meta draft.Draft
if len(metadata) > 0 {
meta = metadata[0]
}
d, err := draft.Create(name, source, meta.Server, fresh, meta.BaseVersion)
path := d.Path
if err != nil {
return func() tea.Msg { return editedMsg{name: name, path: path, err: err} }
}
return tea.ExecProcess(exec.Command(editor, append(args, path)...), func(err error) tea.Msg {
result := readEditedDraft(name, path, source, needsConfirm, err)
result.baseVersion = meta.BaseVersion
if fresh {
result.unchanged = false
result.createOnly = true
}
return result
})
}
func draftEditor() (string, []string, error) {
for _, name := range []string{"VISUAL", "EDITOR"} {
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
shell, err := exec.LookPath("sh")
return shell, []string{"-c", value + ` "$1"`, "pipelines-editor"}, err
}
}
for _, name := range []string{"nvim", "vim", "vi", "nano"} {
if path, err := exec.LookPath(name); err == nil {
return path, nil, nil
}
}
return "", nil, fmt.Errorf("no editor found; set VISUAL or EDITOR, or install vim/nano")
}
func readEditedDraft(name, path, original string, confirm bool, editorErr error) editedMsg {
result := editedMsg{name: name, path: path, err: editorErr, confirm: confirm}
if editorErr != nil {
return result
}
info, err := os.Stat(path)
if err != nil {
result.err = err
return result
}
if info.Size() > 1<<20 {
result.err = fmt.Errorf("file exceeds 1 MiB")
return result
}
data, err := os.ReadFile(path)
result.source, result.err = string(data), err
// A new pipeline still needs its initial submission even if its template
// was left untouched. Existing edits require actual byte-for-byte changes.
result.unchanged = err == nil && confirm && result.source == original
return result
}