turbo-editors/turbo-corepublic Fork 0
v1.0.1
Commits
Clone
git clone https://git.rickub.com/turbo-editors/turbo-core.git
git clone ssh://git@rickub.com/turbo-editors/turbo-core.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

📦 Turbo Core f3ade8d · on v1.0.1 · k33g · 10h ago
toolchain.go · 398 lines · 13.2 KBGo Blame HistoryRaw
  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
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// The toolchain menu: the commands a project runs on itself — format, lint,
// build, test, run — read from a TOML file and each shown where it asks for.
//
// The menu is named by the profile: "Go" in Turbo Go, "Rust" in Turbo Rust.

package app

import (
	"fmt"
	"os"
	"strconv"
	"strings"

	"rickub.com/turbo-editors/turbo-core/buffer"

	"rickub.com/turbo-editors/turbo-core/terminal"
	"rickub.com/turbo-editors/turbo-core/tools"
	"rickub.com/turbo-editors/turbo-core/ui"
)

// createToolsLabel is the item that writes a starter file, kept at the bottom
// of the menu so the commands above it read as the content.
const createToolsLabel = "~C~reate tools file"

// openToolsLabel is its partner. Exactly one of the two is ever available: you
// can create the file you have not got, and open the one you have.
const openToolsLabel = "~O~pen tools file"

// toolchainMenu returns the editor's own toolchain menu.
//
// Its items come from OnOpen for the same reason the Snippets menu's do: they
// are read from a file that changes while the editor runs, so there is nothing
// to decide at start-up.
//
// The menu is always on the bar, even with no tools file, or the item that
// creates one would be unreachable.
func (a *App) toolchainMenu() *ui.Menu {
	menu := &ui.Menu{Label: a.profile.ToolsMenu}
	menu.OnOpen = func() { menu.Items = a.toolItems() }
	return menu
}

// toolsMenuName is the plain name of that menu, which is what a tools file
// writes in its menu key.
func (a *App) toolsMenuName() string { return tools.DefaultMenuName(a.profile) }

// toolItems builds the menu's contents: the project's commands, then the item
// that writes a starter file.
func (a *App) toolItems() []*ui.MenuItem {
	items := a.commandItems(a.toolsMenuName())
	if len(items) > 0 {
		items = append(items, &ui.MenuItem{Separator: true})
	}
	return append(items,
		&ui.MenuItem{Label: createToolsLabel, Action: a.CreateTools, Enabled: not(a.HasProjectTools)},
		&ui.MenuItem{Label: openToolsLabel, Action: a.OpenTools, Enabled: a.HasProjectTools},
	)
}

// commandItems turns one menu's tools into menu lines.
//
// A file that cannot be read gives one disabled line saying so, rather than an
// empty menu: a typo should be visible where the commands were expected.
func (a *App) commandItems(menu string) []*ui.MenuItem {
	list, err := a.loadTools()
	if err != nil {
		return []*ui.MenuItem{{Label: "Cannot read tools", Enabled: func() bool { return false }}}
	}

	chosen := list.In(menu)
	items := make([]*ui.MenuItem, 0, len(chosen))
	for _, tool := range chosen {
		chosen := tool // captured per iteration, not read back from the loop
		items = append(items, &ui.MenuItem{
			Label:  tool.Name,
			Action: func() { a.RunTool(chosen) },
		})
	}
	return items
}

// loadTools reads the project's tools file.
func (a *App) loadTools() (tools.List, error) {
	working, err := os.Getwd()
	if err != nil {
		return tools.List{}, err
	}
	return tools.Load(a.profile, working)
}

// RunTool runs a command and shows its output where the tool asked for.
//
// A command with a `{{label}}` in it asks for that value first, in a dialog,
// and does not run until the dialog is answered. Escape or Cancel means it does
// not run at all.
//
//	a.RunTool(tools.Tool{Name: "Test", Command: "go test ./...", Output: tools.OutputPopup})
func (a *App) RunTool(tool tools.Tool) {
	placeholders := tool.Placeholders()
	if len(placeholders) == 0 {
		a.runFilledTool(tool, tool.Command)
		return
	}
	a.askForParameters(tool, placeholders)
}

// askForParameters opens the box, and runs the command once it is answered.
//
// The values are remembered for the rest of the session, per tool, so running
// the same parameterised command twice does not mean typing the same thing
// twice. Nothing is written to disk: the project's own directory is for what
// the project decided, not for what somebody typed into a box this afternoon.
func (a *App) askForParameters(tool tools.Tool, placeholders []tools.Placeholder) {
	screen := a.screenRect()
	if fits := MaxParameterFields(screen.H); len(placeholders) > fits {
		a.ShowMessage(a.toolsMenuName(), fmt.Sprintf(
			"%s asks for %d values, and only %d fit on a screen this tall.\n\nMake the terminal taller, or split the command into two tools.",
			ui.PlainLabel(tool.Name), len(placeholders), fits))
		return
	}

	labels := make([]string, len(placeholders))
	for i, placeholder := range placeholders {
		labels[i] = placeholder.Label
	}

	box := NewParametersDialog(ui.PlainLabel(tool.Name), labels, a.toolValues[tool.Name], screen)
	a.pushModal(box.Dialog(), func(result ui.Result) {
		if result != ui.ResultOK {
			return
		}
		values := box.Values()
		a.rememberToolValues(tool.Name, values)
		a.runFilledTool(tool, tool.Fill(values))
	})
}

// rememberToolValues keeps what was typed for the rest of the session.
func (a *App) rememberToolValues(tool string, values map[string]string) {
	if a.toolValues == nil {
		a.toolValues = map[string]map[string]string{}
	}
	a.toolValues[tool] = values
}

// runFilledTool runs a command whose placeholders, if it had any, are already
// substituted, and shows its output where the tool asked for.
func (a *App) runFilledTool(tool tools.Tool, command string) {
	working, err := os.Getwd()
	if err != nil {
		a.ShowMessage(a.toolsMenuName(), "Cannot tell which directory this is:\n"+err.Error())
		return
	}

	switch tool.Where() {
	case tools.OutputTerminal:
		a.runInTerminal(command, working)
	default:
		a.runCaptured(tool, command, working)
	}
}

// runInTerminal runs a command in a terminal window of its own.
//
// A window rather than a captured pane is what a program that reads the
// keyboard needs, and what lets Ctrl-C stop one that is taking too long. The
// window stays after the command exits, so its output can be read.
func (a *App) runInTerminal(command, dir string) {
	view, err := terminal.NewView(terminal.ViewOptions{
		// The same shell the popup uses, told to run one command line and
		// exit; tools knows which shell that is on this platform.
		Options: terminal.Options{
			Shell: tools.Shell(),
			Args:  tools.ShellArgs(command),
			Dir:   dir,
		},
		Name:     command,
		OnChange: a.wake,
		// A command that has finished may have rewritten the files on disk,
		// which is what Format does every time. The wake is what gets the
		// reload onto the main goroutine, where touching buffers is safe.
		OnExit: func() { a.toolFinished(); a.wake() },
	})
	if err != nil {
		a.reportTerminalFailure(err)
		return
	}

	window := ui.NewWindow(view.Title(), view)
	window.SetBounds(a.newWindowBounds())
	window.OnClose = func() bool { a.closeTerminal(window, view); return true }

	a.desktop.Add(window)
	a.windowsOpened++
	a.terminals[window] = view
	a.Message("Running " + command)
}

// runCaptured runs a command with its output collected, and shows it in a
// dialog that fills in as it goes.
//
// The dialog opens straight away rather than when the command ends. A popup
// appearing unbidden a few seconds later would swallow whatever was being
// typed at that moment, and watching a build's output arrive is most of what
// makes waiting for it bearable.
func (a *App) runCaptured(tool tools.Tool, command, dir string) {
	run, err := tools.Start(command, dir, a.wake)
	if err != nil {
		a.ShowMessage(a.toolsMenuName(), err.Error())
		return
	}

	dialog, list := NewOutputDialog(runningTitle(command), nil, a.screenRect())
	a.running = &toolRun{run: run, dialog: dialog, list: list, editor: tool.Where() == tools.OutputEditor}

	// Closing the dialog stops the command: there is no other way to interrupt
	// one whose output is not in a terminal, and leaving it running with
	// nowhere to show itself would be worse than stopping it.
	a.pushModal(dialog, func(ui.Result) { a.finishRun() })
}

// toolRun is the command whose output is showing, and where it goes.
type toolRun struct {
	run    *tools.Run
	dialog *ui.Dialog
	list   *ui.ListBox
	editor bool
}

// refreshRunningTool copies what a command has printed into its dialog.
//
// It runs at the top of the event loop rather than from the reading goroutine,
// which may not touch a dialog. The goroutine only wakes the loop — and if that
// wake is dropped, the next keystroke brings the output in, which is late
// rather than lost.
func (a *App) refreshRunningTool() {
	if a.running == nil {
		return
	}

	lines := a.running.run.Lines()
	if dropped := a.running.run.Dropped(); dropped > 0 {
		lines = append([]string{fmt.Sprintf("… %d earlier lines dropped …", dropped)}, lines...)
	}

	atEnd := a.running.list.Selected() >= len(a.running.list.Items())-1
	a.running.list.SetItems(lines)
	if atEnd {
		// Following the output is what a reader wants until they scroll back.
		a.running.list.Select(len(lines) - 1)
	}

	finished, code := a.running.run.Done()
	if !finished {
		return
	}

	// A command that succeeded silently — `go build ./...` — would otherwise
	// leave a blank dialog, which reads as "nothing happened" rather than as
	// "it worked". While it is still running, blank is the honest picture.
	if len(lines) == 0 {
		a.running.list.SetItems([]string{noOutputLine})
	}
	a.running.dialog.SetTitle(finishedTitle(a.running.run.Command(), code))
	a.toolFinished()
}

// noOutputLine is what a finished command that printed nothing shows.
const noOutputLine = "(no output)"

// finishRun clears the running command away once its dialog has been closed,
// stopping it if it has not ended, and putting its output in a window when the
// tool asked for one.
func (a *App) finishRun() {
	running := a.running
	a.running = nil
	if running == nil {
		return
	}

	running.run.Stop()
	if running.editor {
		a.openOutputInEditor(running.run)
	}
	a.toolFinished()
}

// openOutputInEditor puts a command's output in an editing window.
//
// It is filled in once the command has ended rather than as it goes: this is
// the mode for searching output with Ctrl-F, and a buffer growing under the
// cursor while you search it would be the opposite of that.
func (a *App) openOutputInEditor(run *tools.Run) {
	buf := buffer.New()
	buf.SetText(strings.Join(run.Lines(), "\n"))
	buf.SetCursor(buffer.Position{})
	a.openBuffer(buf)

	if window := a.desktop.Active(); window != nil {
		window.SetTitle(run.Command())
	}
}

// runningTitle and finishedTitle are what a command's dialog is called.
//
// The exit code is always shown, because a command that succeeded silently
// would otherwise give a dialog with nothing in it and no way to tell that from
// one that had not started.
func runningTitle(command string) string { return command + " — running" }

func finishedTitle(command string, exit int) string {
	if exit == 0 {
		return command + " — ok"
	}
	return fmt.Sprintf("%s — exit %d", command, exit)
}

// toolFinished notes that a command has ended, so the next turn of the event
// loop picks the change up.
//
// It is called from the reading goroutine, so it may not touch a buffer or the
// desktop; setting a flag is all it does.
func (a *App) toolFinished() { a.toolsRan.Store(true) }

// reloadAfterTools re-reads the files a finished command may have rewritten.
//
// It runs at the top of the event loop, like the other state-driven work, and
// only when a command has actually ended.
//
// **Only unmodified buffers are reloaded.** One with unsaved changes has
// something to lose, so it is left alone and named on the status bar — which
// is the honest outcome: a formatter and an unsaved edit genuinely conflict,
// and the editor is not the one that should decide which wins.
func (a *App) reloadAfterTools() {
	if !a.toolsRan.Swap(false) {
		return
	}

	reloaded, skipped := a.reloadUnmodifiedBuffers()
	a.refreshTree()

	switch {
	case skipped > 0:
		a.Message(reloadReport(reloaded) + "; " + plural(skipped, "file") + " with unsaved changes left alone")
	case reloaded > 0:
		a.Message(reloadReport(reloaded))
	}
}

// reloadUnmodifiedBuffers re-reads every open file that has no unsaved
// changes, and reports how many actually changed and how many were skipped.
func (a *App) reloadUnmodifiedBuffers() (reloaded, skipped int) {
	for _, window := range a.desktop.Windows() {
		view, ok := editorViewOf(window)
		if !ok || view.Buffer().Path() == "" {
			continue
		}
		if view.Buffer().Modified() {
			skipped++
			continue
		}

		changed, err := view.Buffer().Reload()
		if err != nil || !changed {
			continue // a file that has gone, or one nothing touched
		}
		view.RefreshSyntax()
		window.SetTitle(windowTitle(view.Buffer()))
		reloaded++
	}
	return reloaded, skipped
}

// reloadReport says how many files were re-read.
func reloadReport(reloaded int) string {
	if reloaded == 0 {
		return "Command finished"
	}
	return "Reloaded " + plural(reloaded, "file")
}

// plural renders a count with its noun, pluralised the simple way.
func plural(count int, noun string) string {
	if count == 1 {
		return "1 " + noun
	}
	return strconv.Itoa(count) + " " + noun + "s"
}

// CreateTools writes a starter tools file for the project and opens it.
//
// The file is opened rather than merely written because the commands in it are
// how the format is learnt, and changing one is the first thing anybody does.
// A project that already has one is opened unchanged.
func (a *App) CreateTools() {
	create := func(project string) (string, error) { return tools.Create(a.profile, project) }
	a.createProjectFile(a.toolsMenuName(), create, tools.ErrExists)
}