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
|
// Top-level handler for a REPL session, including setup/construction, and
// ingesting command-lines. Command-line strings are triaged and send off to
// the appropriate handlers: DSL parse/execute if the command is a DSL statement
// (like '$z = $x + $y'); REPL-command-line parse/execute otherwise (like
// ':open foo.dat' or ':help').
//
// No command-line-history-editing feature is built in but
//
// rlwrap mlr repl
//
// is a delight. :)
//
package repl
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"os/signal"
"strings"
"syscall"
"github.com/johnkerl/miller/v6/pkg/cli"
"github.com/johnkerl/miller/v6/pkg/dsl/cst"
"github.com/johnkerl/miller/v6/pkg/input"
"github.com/johnkerl/miller/v6/pkg/lib"
"github.com/johnkerl/miller/v6/pkg/mlrval"
"github.com/johnkerl/miller/v6/pkg/output"
"github.com/johnkerl/miller/v6/pkg/runtime"
"github.com/johnkerl/miller/v6/pkg/types"
)
func NewRepl(
exeName string,
replName string,
showStartupBanner bool,
showPrompts bool,
astPrintMode ASTPrintMode,
doWarnings bool,
strictMode bool,
options *cli.TOptions,
recordOutputFileName string,
recordOutputStream *os.File,
) (*Repl, error) {
recordReader, err := input.Create(&options.ReaderOptions, 1) // recordsPerBatch
if err != nil {
return nil, err
}
recordWriter, err := output.Create(&options.WriterOptions)
if err != nil {
return nil, err
}
// $* is the empty map {} until/unless the user opens a file and reads records from it.
inrec := mlrval.NewMlrmapAsRecord()
// NR is 0, etc until/unless the user opens a file and reads records from it.
context := types.NewContext()
runtimeState := runtime.NewEmptyState(options, strictMode)
runtimeState.NoExitOnFunctionNotFound = true
runtimeState.Update(inrec, context)
// The filter expression for the main Miller DSL is any non-assignment
// statement like 'true' or '$x > 0.5' etc. For the REPL, we re-use this for
// interactive expressions to be printed to the terminal. For the main DSL,
// the default is mlrval.FromTrue(); for the REPL, the default is
// mlrval.NULL.
runtimeState.FilterExpression = mlrval.NULL
// For control-C handling
sysToSignalHandlerChannel := make(chan os.Signal, 1) // Our signal handler reads system notification here
appSignalNotificationChannel := make(chan bool, 1) // Our signal handler writes this for our app to poll
signal.Notify(sysToSignalHandlerChannel, os.Interrupt, syscall.SIGTERM)
go controlCHandler(sysToSignalHandlerChannel, appSignalNotificationChannel)
cstRootNode := cst.NewEmptyRoot(
&options.WriterOptions, cst.DSLInstanceTypeREPL,
).WithRedefinableUDFUDS().WithStrictMode(strictMode)
// TODO
// If there was a --load/--mload on the command line, load those DSL strings here (e.g.
// someone's local function library).
dslStrings := []string{}
for _, filename := range options.DSLPreloadFileNames {
theseDSLStrings, err := lib.LoadStringsFromFileOrDir(filename, ".mlr")
if err != nil {
fmt.Fprintf(os.Stderr, "%s %s: cannot load DSL expression from \"%s\": ",
exeName, replName, filename)
return nil, err
}
dslStrings = append(dslStrings, theseDSLStrings...)
}
repl := &Repl{
exeName: exeName,
replName: replName,
inputIsTerminal: getInputIsTerminal(),
showStartupBanner: showStartupBanner,
showPrompts: showPrompts,
prompt1: getPrompt1(),
prompt2: getPrompt2(),
astPrintMode: astPrintMode,
doWarnings: doWarnings,
cstRootNode: cstRootNode,
options: options,
readerChannel: nil,
errorChannel: nil,
recordReader: recordReader,
recordWriter: recordWriter,
runtimeState: runtimeState,
sysToSignalHandlerChannel: sysToSignalHandlerChannel,
appSignalNotificationChannel: appSignalNotificationChannel,
}
repl.setBufferedOutputStream(recordOutputFileName, recordOutputStream)
for _, dslString := range dslStrings {
err := repl.handleDSLStringBulk(dslString, doWarnings)
if err != nil {
// Error message already printed out
return nil, err
}
}
return repl, nil
}
// When the user types control-C, immediately print something to the screen,
// then also write to a channel while long-running things like :skip and
// :process can check it.
func controlCHandler(sysToSignalHandlerChannel chan os.Signal, appSignalNotificationChannel chan bool) {
for {
<-sysToSignalHandlerChannel // Block until control-C notification is sent by system
fmt.Println("^C") // Acknowledge for user reassurance
appSignalNotificationChannel <- true // Let our app poll this
}
}
func (repl *Repl) handleSession(istream *os.File) error {
if repl.showStartupBanner {
repl.printStartupBanner()
}
lineReader := bufio.NewReader(istream)
for {
repl.printPrompt1()
// Read in a goroutine so we can select on Control-C and exit cleanly at the prompt.
type readResult struct {
line string
err error
}
readDone := make(chan readResult, 1)
go func() {
line, err := lineReader.ReadString('\n')
readDone <- readResult{line, err}
}()
var line string
var err error
select {
case <-repl.appSignalNotificationChannel:
// Control-C at prompt: exit cleanly (controlCHandler already printed ^C)
return nil
case result := <-readDone:
line, err = result.line, result.err
}
if err == io.EOF {
if repl.inputIsTerminal {
fmt.Println()
}
break
}
if err != nil {
return err
}
// Drain any additional control-C's that may have been typed (e.g. to cancel
// partial input). Ignore the line if so.
drainLoop:
for {
select {
case <-repl.appSignalNotificationChannel:
line = ""
default:
break drainLoop
}
}
// This trims the trailing newline, as well as leading/trailing whitespace:
trimmedLine := strings.TrimSpace(line)
if trimmedLine == "<" {
err = repl.handleMultiLine(lineReader, ">", true) // multi-line immediate
if err != nil {
return err
}
} else if trimmedLine == "<<" {
err = repl.handleMultiLine(lineReader, ">>", false) // multi-line non-immediate
if err != nil {
return err
}
} else if trimmedLine == ":quit" || trimmedLine == ":q" {
break
} else if repl.handleNonDSLLine(trimmedLine) {
// Handled in that method.
} else {
// We need the non-trimmed line here since the DSL syntax for comments is '#.*\n'.
err = repl.handleDSLStringImmediate(line, repl.doWarnings)
if err != nil {
fmt.Fprintf(os.Stderr, "mlr: %v\n", err)
}
}
}
return nil
}
// Context: the "<" or "<<" has already been seen. we read until ">" or ">>".
func (repl *Repl) handleMultiLine(
lineReader *bufio.Reader,
terminator string,
doImmediate bool,
) error {
var buffer bytes.Buffer
for {
repl.printPrompt2()
line, err := lineReader.ReadString('\n')
if err == io.EOF {
break
}
if err != nil {
return err
}
if strings.TrimSpace(line) == terminator {
break
}
buffer.WriteString(line)
}
dslString := buffer.String()
var err error
if doImmediate {
err = repl.handleDSLStringImmediate(dslString, repl.doWarnings)
} else {
err = repl.handleDSLStringBulk(dslString, repl.doWarnings)
}
if err != nil {
fmt.Fprintf(os.Stderr, "mlr: %v\n", err)
}
return nil
}
func (repl *Repl) setBufferedOutputStream(
recordOutputFileName string,
recordOutputStream *os.File,
) {
repl.recordOutputFileName = recordOutputFileName
repl.recordOutputStream = recordOutputStream
repl.bufferedRecordOutputStream = bufio.NewWriter(recordOutputStream)
}
func (repl *Repl) closeBufferedOutputStream() error {
if repl.recordOutputStream != os.Stdout {
err := repl.recordOutputStream.Close()
if err != nil {
return fmt.Errorf("mlr repl: error on redirect close of %s: %v",
repl.recordOutputFileName, err,
)
}
}
return nil
}
|