-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcommand.go
More file actions
343 lines (293 loc) · 9.37 KB
/
command.go
File metadata and controls
343 lines (293 loc) · 9.37 KB
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
package main
// Module: command.go
// Purpose: Command prompt functionality for executing shell commands
// Responsibilities:
// - Execute shell commands in the current directory context
// - Handle command completion and results
// - Manage command history (optional)
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
tea "github.com/charmbracelet/bubbletea"
)
// commandFinishedMsg is sent when a command execution completes
type commandFinishedMsg struct {
err error
}
// runCommand executes a shell command in the specified directory
// It suspends the TFE UI, runs the command, then resumes
// Similar to Midnight Commander's "pause after run" feature:
// 1. Echo the command that was typed
// 2. Execute the command and show output
// 3. Show exit code and wait for user to press a key before returning
//
// For long-running TUI apps (like claude, lazygit), use ! prefix to exit TFE: :!command
func runCommand(command, dir string) tea.Cmd {
return func() tea.Msg {
// Execute command - runs in current directory
// Commands are executed in a safe wrapper that shows output and waits for keypress
script := fmt.Sprintf(`
echo "$ %s"
cd %s || exit 1
%s
exitCode=$?
echo ""
echo "Exit code: $exitCode"
echo "Press any key to continue..."
read -n 1 -s -r
exit $exitCode
`, shellQuote(command), shellQuote(dir), command)
c := exec.Command("bash", "-c", script)
c.Dir = dir
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
// Execute the command and restore the terminal
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return commandFinishedMsg{err: err}
}),
)()
}
}
// runCommandAndExit executes a shell command and exits TFE
// Used when command is prefixed with ! (e.g., ":!claude --yolo")
// This is useful for launching long-running TUI apps that need to take over the terminal
// The command will run and when it exits, TFE will quit (not resume)
func runCommandAndExit(command, dir string) tea.Cmd {
return func() tea.Msg {
// Build a shell script that changes to directory and runs command
script := fmt.Sprintf(`
cd %s || exit 1
exec %s
`, shellQuote(dir), command)
// Create the command
c := exec.Command("bash", "-c", script)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
// Execute command and exit TFE immediately
// The command will take over the terminal
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
// After command exits, quit TFE
return tea.Quit()
}),
)()
}
}
// addToHistory adds a command to the current directory's history, avoiding duplicates
// Commands are stored per-directory for context-specific recall
func (m *model) addToHistory(command string) {
if command == "" {
return
}
// Get current directory history
dirHistory := m.commandHistoryByDir[m.currentPath]
// Remove duplicate if it exists in directory history
for i, cmd := range dirHistory {
if cmd == command {
dirHistory = append(dirHistory[:i], dirHistory[i+1:]...)
break
}
}
// Add to end of directory history
dirHistory = append(dirHistory, command)
// Limit directory history to 50 commands
if len(dirHistory) > 50 {
dirHistory = dirHistory[1:]
}
// Save back to map
m.commandHistoryByDir[m.currentPath] = dirHistory
// Rebuild combined history (directory + global)
m.rebuildCombinedHistory()
// Reset history position
m.historyPos = len(m.commandHistory)
// Save to disk after adding
m.saveCommandHistory()
}
// rebuildCombinedHistory creates a combined history list from current directory + global
// Directory-specific commands appear first (most relevant), then global commands
// Duplicates are removed (directory version takes precedence)
func (m *model) rebuildCombinedHistory() {
seen := make(map[string]bool)
combined := []string{}
// Add directory-specific commands first (most relevant)
if dirHistory, exists := m.commandHistoryByDir[m.currentPath]; exists {
for _, cmd := range dirHistory {
if !seen[cmd] {
combined = append(combined, cmd)
seen[cmd] = true
}
}
}
// Add global commands (if not already in directory history)
for _, cmd := range m.commandHistoryGlobal {
if !seen[cmd] {
combined = append(combined, cmd)
seen[cmd] = true
}
}
m.commandHistory = combined
m.historyPos = len(m.commandHistory)
}
// getPreviousCommand navigates backward in command history
func (m *model) getPreviousCommand() string {
if len(m.commandHistory) == 0 {
return m.commandInput
}
if m.historyPos > 0 {
m.historyPos--
}
if m.historyPos < len(m.commandHistory) {
return m.commandHistory[m.historyPos]
}
return ""
}
// getNextCommand navigates forward in command history
func (m *model) getNextCommand() string {
if len(m.commandHistory) == 0 {
return ""
}
if m.historyPos < len(m.commandHistory)-1 {
m.historyPos++
return m.commandHistory[m.historyPos]
}
// At the end of history, return empty string
m.historyPos = len(m.commandHistory)
return ""
}
// runScript executes a script file safely without command injection
// Similar to runCommand but for executing script files directly
func runScript(scriptPath string) tea.Cmd {
return func() tea.Msg {
// Create a wrapper script that:
// 1. Shows the script being executed
// 2. Runs the script
// 3. Pauses for user input
wrapperScript := `
echo "$ bash $0"
echo ""
bash "$0"
exitCode=$?
echo ""
echo "Exit code: $exitCode"
echo "Press any key to continue..."
read -n 1 -s -r
exit $exitCode
`
// Execute bash with the wrapper script and pass scriptPath as $0
c := exec.Command("bash", "-c", wrapperScript, scriptPath)
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
// Execute the command and restore the terminal
return tea.Sequence(
tea.ClearScreen,
tea.ExecProcess(c, func(err error) tea.Msg {
return commandFinishedMsg{err: err}
}),
)()
}
}
// termuxNewSession launches a command in a new Termux terminal session
// This is useful when TFE is launched from a widget (no parent shell)
// For Quick CD: command is "exec bash" to get an interactive shell in the target dir
// For Claude: command is "claude" to launch Claude Code
// Requires allow-external-apps = true in ~/.termux/termux.properties
func termuxNewSession(command string, workDir string) tea.Cmd {
return func() tea.Msg {
amCmd := termuxNewSessionCmd(command, workDir)
c := exec.Command("bash", "-c", amCmd)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
err := c.Run()
if err != nil {
// Return error message that can be displayed
return commandFinishedMsg{err: fmt.Errorf("failed to start Termux session: %v (ensure allow-external-apps=true in ~/.termux/termux.properties)", err)}
}
// After launching the new session, quit TFE
return tea.Quit()
}
}
// shellQuote quotes a string for safe use in shell commands
// Simple version that escapes single quotes
func shellQuote(s string) string {
// Replace single quotes with '\'' (end quote, escaped quote, start quote)
s = strings.ReplaceAll(s, "'", "'\\''")
return "'" + s + "'"
}
// loadCommandHistory reads command history from disk
// Returns directory-specific map and global slice
// Handles backwards compatibility with old format
func loadCommandHistory() (map[string][]string, []string) {
homeDir, err := os.UserHomeDir()
if err != nil {
return make(map[string][]string), []string{}
}
historyPath := filepath.Join(homeDir, ".config", "tfe", "command_history.json")
data, err := os.ReadFile(historyPath)
if err != nil {
return make(map[string][]string), []string{} // File doesn't exist yet, start fresh
}
// Try new format first
var newFormat struct {
Version int `json:"version"`
Directories map[string][]string `json:"directories"`
Global []string `json:"global"`
}
if err := json.Unmarshal(data, &newFormat); err == nil && newFormat.Version == 2 {
// New format loaded successfully
if newFormat.Directories == nil {
newFormat.Directories = make(map[string][]string)
}
if newFormat.Global == nil {
newFormat.Global = []string{}
}
return newFormat.Directories, newFormat.Global
}
// Try old format for backwards compatibility
var oldFormat struct {
Commands []string `json:"commands"`
}
if err := json.Unmarshal(data, &oldFormat); err == nil && len(oldFormat.Commands) > 0 {
// Old format - migrate to global history
return make(map[string][]string), oldFormat.Commands
}
// Failed to parse either format
return make(map[string][]string), []string{}
}
// saveCommandHistory writes command history to disk
// Creates the config directory if it doesn't exist
// Saves in version 2 format with per-directory and global history
func (m *model) saveCommandHistory() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
configDir := filepath.Join(homeDir, ".config", "tfe")
os.MkdirAll(configDir, 0755) // Create directory if it doesn't exist
historyPath := filepath.Join(configDir, "command_history.json")
history := struct {
Version int `json:"version"`
MaxSize int `json:"maxSize"`
Directories map[string][]string `json:"directories"`
Global []string `json:"global"`
}{
Version: 2,
MaxSize: 100,
Directories: m.commandHistoryByDir,
Global: m.commandHistoryGlobal,
}
data, err := json.MarshalIndent(history, "", " ")
if err != nil {
return err
}
return os.WriteFile(historyPath, data, 0644)
}