summaryrefslogtreecommitdiff
path: root/src/remembering.go
blob: f802ffcf7978f4c949f62f3be74bfecf697812a9 (plain) (blame)
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
package remembering

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"io"
	"io/fs"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"syscall"

	"gobang"
)



type envT struct {
	allArgs []string
	in      io.Reader
	out     io.Writer
	err     io.Writer
}

// entryT is one line of a profile file.  Its on-disk form is
// "COUNT profile TEXT", and TEXT runs to the end of the line, so
// anything a menu can show --- spaces, UTF-8, leading blanks ---
// round-trips byte-for-byte.
type entryT struct {
	count int
	text  string
}



// splitLines turns raw input into menu lines: the final newline
// doesn't open a last empty line, but blank lines in the middle
// are kept, since a menu tool would show them.
func splitLines(data string) []string {
	if data == "" {
		return []string{}
	}
	return strings.Split(strings.TrimSuffix(data, "\n"), "\n")
}

// parseProfile reads the on-disk "COUNT profile TEXT" lines.
// TEXT is recovered positionally, like the original awk substr()
// did, so blanks inside it survive.  Lines without the "profile"
// tag are dropped; a non-numeric count reads as 0.
func parseProfile(content string) []entryT {
	entries := []entryT{}
	for _, line := range splitLines(content) {
		fields := strings.Fields(line)
		if len(fields) < 2 || fields[1] != "profile" {
			continue
		}
		count, _ := strconv.Atoi(fields[0])
		idx := len(fields[0]) + len(fields[1]) + 2
		text := ""
		if idx <= len(line) {
			text = line[idx:]
		}
		entries = append(entries, entryT{count, text})
	}
	return entries
}

func serializeProfile(entries []entryT) string {
	str := strings.Builder{}
	for _, entry := range entries {
		fmt.Fprintf(
			&str, "%d profile %s\n",
			entry.count, entry.text,
		)
	}
	return str.String()
}

// menuFor ranks the stdin lines: most-picked first, ties in byte
// order, never-picked entries at the bottom.  Counts of duplicate
// profile lines for the same text are summed.  Only stdin defines
// what is offered --- profile entries absent from stdin are
// remembered, not shown.
func menuFor(profile []entryT, lines []string) []entryT {
	counts := map[string]int{}
	for _, entry := range profile {
		counts[entry.text] += entry.count
	}

	menu := make([]entryT, 0, len(lines))
	for _, line := range lines {
		menu = append(menu, entryT{counts[line], line})
	}
	sort.SliceStable(menu, func(i int, j int) bool {
		if menu[i].count != menu[j].count {
			return menu[i].count > menu[j].count
		}
		return menu[i].text < menu[j].text
	})
	return menu
}

func menuText(menu []entryT) string {
	str := strings.Builder{}
	for _, entry := range menu {
		str.WriteString(entry.text)
		str.WriteByte('\n')
	}
	return str.String()
}

// nextProfile is the profile after choice was picked: the union
// of what the profile knew and what stdin offered, in byte order,
// with the pick's count bumped.  A pick the profile has never
// seen is appended at the end, starting at 1; texts offered but
// never picked enter at 0, so the profile accumulates the
// universe of choices it has seen.  Duplicate profile lines for
// the same text collapse to the highest count.
func nextProfile(
	profile []entryT,
	lines []string,
	choice string,
) []entryT {
	counts := map[string]int{}
	for _, entry := range profile {
		prev, seen := counts[entry.text]
		if !seen || entry.count > prev {
			counts[entry.text] = entry.count
		}
	}
	for _, line := range lines {
		_, seen := counts[line]
		if !seen {
			counts[line] = 0
		}
	}

	texts := make([]string, 0, len(counts))
	for text := range counts {
		texts = append(texts, text)
	}
	sort.Strings(texts)

	next := make([]entryT, 0, len(texts)+1)
	found := false
	for _, text := range texts {
		count := counts[text]
		if text == choice {
			count++
			found = true
		}
		next = append(next, entryT{count, text})
	}
	if !found {
		next = append(next, entryT{1, choice})
	}
	return next
}



// profilePath is where a profile lives:
// $XDG_DATA_HOME/remembering/NAME, honouring the XDG default of
// ~/.local/share.  The default profile name is the current
// directory with slashes turned into "!", so each directory gets
// its own ranking without any setup.
func profilePath(name string) (string, error) {
	if name == "" {
		cwd, err := os.Getwd()
		if err != nil {
			return "", err
		}
		name = strings.ReplaceAll(cwd, "/", "!")
	}
	data := os.Getenv("XDG_DATA_HOME")
	if data == "" {
		data = filepath.Join(
			os.Getenv("HOME"), ".local", "share",
		)
	}
	return filepath.Join(data, Name, name), nil
}

func exists(path string) bool {
	_, err := os.Stat(path)
	return err == nil
}

// loadProfile reads the profile, creating an empty one (and its
// directory) on first use, so the file is in place even when this
// run ends up picking nothing.
func loadProfile(path string) ([]entryT, error) {
	if !exists(path) {
		err := os.MkdirAll(filepath.Dir(path), 0755)
		if err != nil {
			return nil, err
		}
		err = os.WriteFile(path, []byte{}, 0644)
		if err != nil {
			return nil, err
		}
	}
	content, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	return parseProfile(string(content)), nil
}

// saveProfile writes the new ranking atomically --- a sibling
// .tmp plus rename --- so a crash never leaves a half-written
// profile behind.
func saveProfile(path string, entries []entryT) error {
	tmp := path + ".tmp"
	err := os.WriteFile(
		tmp, []byte(serializeProfile(entries)), 0644,
	)
	if err != nil {
		return err
	}
	return os.Rename(tmp, path)
}

// forwardedStatus mirrors how sh(1) reports a child: its exit
// status as-is, or 128 plus the signal number when it was killed.
func forwardedStatus(err *exec.ExitError) int {
	status, ok := err.Sys().(syscall.WaitStatus)
	if ok && status.Signaled() {
		return 128 + int(status.Signal())
	}
	return err.ExitCode()
}



func usage(w io.Writer) {
	fmt.Fprintf(
		w,
		"Usage:\n  %s [-p PROFILE] -- COMMAND...\n",
		Name,
	)
}

func run(env envT) int {
	flags := flag.NewFlagSet("", flag.ContinueOnError)
	flags.Usage = func() {}
	flags.SetOutput(env.err)
	profileName := flags.String("p", "", "")

	argv := gobang.ExpandBundles("p:", env.allArgs[1:])
	if flags.Parse(argv) != nil {
		usage(env.err)
		return 2
	}

	command := flags.Args()
	if len(command) == 0 {
		fmt.Fprintf(env.err, "Missing \"-- COMMAND\"\n")
		usage(env.err)
		return 2
	}

	path, err := profilePath(*profileName)
	if err != nil {
		fmt.Fprintf(env.err, "%s: %v\n", Name, err)
		return 1
	}
	profile, err := loadProfile(path)
	if err != nil {
		fmt.Fprintf(env.err, "%s: %v\n", Name, err)
		return 1
	}

	stdin, err := io.ReadAll(env.in)
	if err != nil {
		fmt.Fprintf(env.err, "%s: %v\n", Name, err)
		return 1
	}
	lines := splitLines(string(stdin))

	// the command is transparent in pipelines: its stderr is
	// passed through (that's where dmenu and fzf draw), its
	// stdout is the pick, and a nonzero exit --- a cancelled
	// menu --- aborts the run with the same status, leaving the
	// profile untouched
	cmd := exec.Command(command[0], command[1:]...)
	cmd.Stdin = strings.NewReader(
		menuText(menuFor(profile, lines)),
	)
	picked := bytes.Buffer{}
	cmd.Stdout = &picked
	cmd.Stderr = env.err
	err = cmd.Run()
	if err != nil {
		exitErr := (*exec.ExitError)(nil)
		if errors.As(err, &exitErr) {
			return forwardedStatus(exitErr)
		}
		fmt.Fprintf(env.err, "%s: %v\n", Name, err)
		if errors.Is(err, fs.ErrPermission) {
			return 126
		}
		return 127
	}

	choice := strings.TrimRight(picked.String(), "\n")
	if choice == "" {
		return 0
	}

	err = saveProfile(path, nextProfile(profile, lines, choice))
	if err != nil {
		fmt.Fprintf(env.err, "%s: %v\n", Name, err)
		return 1
	}
	fmt.Fprintf(env.out, "%s\n", choice)
	return 0
}



func Main() {
	os.Exit(run(envT{
		allArgs: os.Args,
		in:      os.Stdin,
		out:     os.Stdout,
		err:     os.Stderr,
	}))
}