File: cli.go

package info (click to toggle)
fq 0.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 106,624 kB
  • sloc: xml: 2,835; makefile: 250; sh: 241; exp: 57; ansic: 21
file content (266 lines) | stat: -rw-r--r-- 5,733 bytes parent folder | download
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
package cli

import (
	"bufio"
	"context"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"log"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"

	"github.com/wader/fq/pkg/interp"

	"github.com/wader/readline"
)

func maybeLogFile() {
	// used during dev to redirect log to file, useful when debugging repl etc
	if lf := os.Getenv("LOGFILE"); lf != "" {
		if f, err := os.Create(lf); err == nil {
			log.SetOutput(f)
		}
	}
}

// function implementing readline.AutoComplete interface
type autoCompleterFn func(line []rune, pos int) (newLine [][]rune, length int)

func (a autoCompleterFn) Do(line []rune, pos int) (newLine [][]rune, length int) {
	return a(line, pos)
}

type stdOS struct {
	rl            *readline.Instance
	historyFile   string
	closeChan     chan struct{}
	interruptChan chan struct{}
	completerFn   interp.CompleteFn
}

func newStandardOS() *stdOS {
	closeChan := make(chan struct{})
	interruptChan := make(chan struct{}, 1)

	// this more or less converts a os signal chan to just a struct{} chan that
	// ignores signals if forwarding it would block, also this makes sure interp
	// does not know about os.
	go func() {
		interruptSignalChan := make(chan os.Signal, 1)
		signal.Notify(interruptSignalChan, os.Interrupt)
		defer func() {
			signal.Stop(interruptSignalChan)
			close(interruptSignalChan)
			close(interruptChan)
		}()

		for {
			select {
			case <-interruptSignalChan:
				// ignore if interruptChan is full
				select {
				case interruptChan <- struct{}{}:
				default:
				}
			case <-closeChan:
				return
			}
		}
	}()

	return &stdOS{
		closeChan:     closeChan,
		interruptChan: interruptChan,
	}
}

func (stdOS) Platform() interp.Platform {
	return interp.Platform{
		OS:   runtime.GOOS,
		Arch: runtime.GOARCH,
	}
}

type fdTerminal uintptr

func (fd fdTerminal) Size() (int, int) {
	w, h, _ := readline.GetSize(int(fd))
	return w, h
}
func (fd fdTerminal) IsTerminal() bool {
	return readline.IsTerminal(int(fd))
}

type stdinInput struct {
	fdTerminal
	fs.File
}

func (o *stdOS) Stdin() interp.Input {
	return stdinInput{
		fdTerminal: fdTerminal(os.Stdin.Fd()),
		File: interp.FileReader{
			R: os.Stdin,
			FileInfo: interp.FixedFileInfo{
				FName: "stdin",
				FMode: fs.ModeIrregular,
			},
		},
	}
}

type stdoutOutput struct {
	fdTerminal
	os *stdOS
}

func (o stdoutOutput) Write(p []byte) (n int, err error) {
	// Let write go thru readline if it has been used. This to have ansi color emulation
	// on windows thru readlins:s stdout rewriter
	// TODO: check if tty instead? else only color when repl
	if o.os.rl != nil {
		return o.os.rl.Write(p)
	}
	return os.Stdout.Write(p)
}

func (o *stdOS) Stdout() interp.Output {
	return stdoutOutput{fdTerminal: fdTerminal(os.Stdout.Fd()), os: o}
}

type stderrOutput struct {
	fdTerminal
}

func (o stderrOutput) Write(p []byte) (n int, err error) { return os.Stderr.Write(p) }

func (o *stdOS) Stderr() interp.Output { return stderrOutput{fdTerminal: fdTerminal(os.Stderr.Fd())} }

func (o *stdOS) InterruptChan() chan struct{} { return o.interruptChan }

func (*stdOS) Args() []string { return os.Args }

func (*stdOS) Environ() []string { return os.Environ() }

func (*stdOS) ConfigDir() (string, error) {
	p, err := os.UserConfigDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(p, "fq"), nil
}

type stdOSFS struct{}

func (stdOSFS) Open(name string) (fs.File, error) { return os.Open(name) }

func (*stdOS) FS() fs.FS { return stdOSFS{} }

func (o *stdOS) Readline(opts interp.ReadlineOpts) (string, error) {
	if o.rl == nil {
		var err error

		var historyFile string
		cacheDir, err := os.UserCacheDir()
		if err != nil {
			return "", err
		}
		historyFile = filepath.Join(cacheDir, "fq/history")
		_ = os.MkdirAll(filepath.Dir(historyFile), 0700)

		cfg := &readline.Config{
			HistoryFile:       historyFile,
			HistorySearchFold: true,
		}
		cfg.AutoComplete = autoCompleterFn(func(line []rune, pos int) (newLine [][]rune, length int) {
			if o.completerFn == nil {
				return nil, 0
			}

			names, shared := o.completerFn(string(line), pos)
			var runeNames [][]rune
			for _, name := range names {
				runeNames = append(runeNames, []rune(name[shared:]))
			}

			return runeNames, shared
		})
		o.rl, err = readline.NewEx(cfg)
		if err != nil {
			return "", err
		}
		o.historyFile = historyFile
	}

	// inject completer to autocompleter
	o.completerFn = opts.CompleteFn

	o.rl.SetPrompt(opts.Prompt)
	line, err := o.rl.Readline()
	if errors.Is(err, readline.ErrInterrupt) {
		return "", interp.ErrInterrupt
	} else if errors.Is(err, io.EOF) {
		return "", interp.ErrEOF
	} else if err != nil {
		return "", err
	}

	return line, nil
}

func (o *stdOS) History() ([]string, error) {
	// TODO: refactor history handling to use internal fs?
	r, err := os.Open(o.historyFile)
	if err != nil {
		return nil, err
	}
	defer r.Close()
	var hs []string
	lineScanner := bufio.NewScanner(r)
	for lineScanner.Scan() {
		hs = append(hs, lineScanner.Text())
	}
	if err := lineScanner.Err(); err != nil {
		return nil, err
	}
	return hs, nil
}

func (o *stdOS) Close() error {
	// only close if is terminal otherwise ansi reset will write
	// to stdout and mess up raw output
	if o.rl != nil {
		o.rl.Close()
	}
	close(o.closeChan)
	return nil
}

func Main(r *interp.Registry, version string) {
	os.Exit(func() int {
		defer maybeProfile()()
		maybeLogFile()

		sos := newStandardOS()
		defer sos.Close()
		i, err := interp.New(sos, r)
		defer i.Stop()
		if err != nil {
			fmt.Fprintln(sos.Stderr(), err)
			return 1
		}

		if err := i.Main(context.Background(), sos.Stdout(), version); err != nil {
			if ex, ok := err.(interp.Exiter); ok { //nolint:errorlint
				return ex.ExitCode()
			}
			return 1
		}

		return 0
	}())
}