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
|
package eventstream
import (
"encoding/csv"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
// shellSplit tokenizes s using POSIX-like shell quoting rules so that paths
// containing spaces (e.g. EDITOR='/My Editor/hx') are preserved as a single
// token. It supports:
// - single-quoted strings : no escape processing inside ' … '
// - double-quoted strings : \" and \\ are recognised; other backslashes
// are kept verbatim
// - unquoted tokens : backslash escapes the next character
//
// Unterminated quotes are treated as if the closing delimiter is implicit at
// end-of-string, matching common shell lenient behaviour.
func shellSplit(s string) []string {
var tokens []string
var current strings.Builder
inToken := false
i := 0
for i < len(s) {
ch := s[i]
switch {
case ch == '\'':
// Single-quote: copy until the matching closing quote verbatim.
inToken = true
i++
for i < len(s) && s[i] != '\'' {
current.WriteByte(s[i])
i++
}
// Skip closing quote if present; if missing we just fall through.
if i < len(s) {
i++ // consume the closing '
}
case ch == '"':
// Double-quote: process backslash escapes for \" and \\.
inToken = true
i++
for i < len(s) && s[i] != '"' {
if s[i] == '\\' && i+1 < len(s) {
next := s[i+1]
if next == '"' || next == '\\' {
current.WriteByte(next)
i += 2
continue
}
}
current.WriteByte(s[i])
i++
}
if i < len(s) {
i++ // consume the closing "
}
case ch == '\\':
// Backslash outside quotes: escape the next character.
inToken = true
if i+1 < len(s) {
current.WriteByte(s[i+1])
i += 2
} else {
// Trailing backslash: keep it.
current.WriteByte('\\')
i++
}
case ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r':
// Whitespace: flush current token if any.
if inToken {
tokens = append(tokens, current.String())
current.Reset()
inToken = false
}
i++
default:
inToken = true
current.WriteByte(ch)
i++
}
}
if inToken {
tokens = append(tokens, current.String())
}
return tokens
}
func defaultStreamExportFilename() string {
return fmt.Sprintf("ior-stream-%s.csv", time.Now().Format("20060102-150405"))
}
func exportSnapshotToCSV(source Source, filter Filter, exportDir, filename string) (string, error) {
name := strings.TrimSpace(filename)
if name == "" {
name = defaultStreamExportFilename()
}
rows := make([]StreamEvent, 0)
if source != nil {
snapshot := source.Snapshot()
rows = make([]StreamEvent, 0, len(snapshot))
for i := range snapshot {
ev := snapshot[i]
if filter.Matches(&ev) {
rows = append(rows, ev)
}
}
}
return exportRowsToCSV(rows, exportDir, name)
}
func exportRowsToCSV(rows []StreamEvent, exportDir, filename string) (string, error) {
name, err := ensureCSVFilename(filename)
if err != nil {
return "", err
}
path := name
if exportDir != "" {
path = filepath.Join(exportDir, name)
}
f, err := os.Create(path)
if err != nil {
return "", err
}
closed := false
closeFile := func() error {
if closed {
return nil
}
closed = true
return f.Close()
}
fail := func(baseErr error) (string, error) {
if closeErr := closeFile(); closeErr != nil {
return "", errors.Join(baseErr, closeErr)
}
return "", baseErr
}
w := csv.NewWriter(f)
header := []string{"seq", "time_ns", "gap_ns", "latency_ns", "comm", "pid", "tid", "syscall", "fd", "ret", "bytes", "file", "error"}
if err := w.Write(header); err != nil {
return fail(err)
}
for i := range rows {
ev := rows[i]
record := []string{
fmt.Sprintf("%d", ev.Seq),
fmt.Sprintf("%d", ev.TimeNs),
fmt.Sprintf("%d", ev.GapNs),
fmt.Sprintf("%d", ev.DurationNs),
ev.Comm,
fmt.Sprintf("%d", ev.PID),
fmt.Sprintf("%d", ev.TID),
ev.Syscall,
fmt.Sprintf("%d", ev.FD),
fmt.Sprintf("%d", ev.RetVal),
fmt.Sprintf("%d", ev.Bytes),
ev.FileName,
fmt.Sprintf("%t", ev.IsError),
}
if err := w.Write(record); err != nil {
return fail(err)
}
}
w.Flush()
if err := w.Error(); err != nil {
return fail(err)
}
if err := closeFile(); err != nil {
return "", err
}
absPath, err := filepath.Abs(path)
if err != nil {
return path, nil
}
return absPath, nil
}
// ensureCSVFilename validates and normalises a user-supplied export filename.
// It strips any directory components (preventing path traversal outside
// exportDir) and rejects names that resolve to "." or "..". A ".csv"
// extension is appended when the caller omits it.
func ensureCSVFilename(name string) (string, error) {
clean := strings.TrimSpace(name)
if clean == "" {
return "", errors.New("filename cannot be empty")
}
// Strip all directory components so that inputs such as
// "../../etc/passwd" or "/absolute/path.csv" cannot escape exportDir.
base := filepath.Base(clean)
// filepath.Base returns "." for empty/dot inputs and ".." for a raw ".."
// component — both are unusable as a plain filename.
if base == "." || base == ".." {
return "", errors.New("filename must not be a directory reference")
}
if strings.HasSuffix(strings.ToLower(base), ".csv") {
return base, nil
}
return base + ".csv", nil
}
// ExportSnapshotToCSV exports a fresh filtered snapshot from the current source
// without mutating the model's paused/live view state.
func (m Model) ExportSnapshotToCSV(filename string) (string, error) {
return exportSnapshotToCSV(m.source, m.filter, m.exportDir, filename)
}
func (m *Model) exportFilteredToCSV(filename string) (string, error) {
return exportRowsToCSV(m.filtered, m.exportDir, filename)
}
// EditorCommandForPath builds an editor command for the given path.
func EditorCommandForPath(path string) (*exec.Cmd, error) {
parts, _, err := resolveEditorCommand()
if err != nil {
return nil, err
}
args := append(parts[1:], path)
return exec.Command(parts[0], args...), nil
}
func resolveEditorCommand() ([]string, string, error) {
candidates := []string{"EDITOR", "VISUAL", "SUDO_EDITOR"}
for _, key := range candidates {
value := strings.TrimSpace(os.Getenv(key))
if value == "" {
continue
}
// Use shellSplit instead of strings.Fields so that quoted paths with
// spaces (e.g. EDITOR='/My Editor/hx') are not broken into multiple
// tokens.
parts := shellSplit(value)
if len(parts) == 0 {
continue
}
return parts, key, nil
}
return []string{fallbackEditor()}, "fallback", nil
}
func fallbackEditor() string {
if _, err := exec.LookPath("hx"); err == nil {
return "hx"
}
return "vi"
}
|