github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/command/console_interactive.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  //go:build !solaris
     5  // +build !solaris
     6  
     7  // The readline library we use doesn't currently support solaris so
     8  // we just build tag it off.
     9  
    10  package command
    11  
    12  import (
    13  	"fmt"
    14  	"io"
    15  	"os"
    16  
    17  	"github.com/terramate-io/tf/repl"
    18  
    19  	"github.com/chzyer/readline"
    20  	"github.com/mitchellh/cli"
    21  )
    22  
    23  func (c *ConsoleCommand) modeInteractive(session *repl.Session, ui cli.Ui) int {
    24  	// Configure input
    25  	l, err := readline.NewEx(&readline.Config{
    26  		Prompt:            "> ",
    27  		InterruptPrompt:   "^C",
    28  		EOFPrompt:         "exit",
    29  		HistorySearchFold: true,
    30  		Stdin:             os.Stdin,
    31  		Stdout:            os.Stdout,
    32  		Stderr:            os.Stderr,
    33  	})
    34  	if err != nil {
    35  		c.Ui.Error(fmt.Sprintf(
    36  			"Error initializing console: %s",
    37  			err))
    38  		return 1
    39  	}
    40  	defer l.Close()
    41  
    42  	for {
    43  		// Read a line
    44  		line, err := l.Readline()
    45  		if err == readline.ErrInterrupt {
    46  			if len(line) == 0 {
    47  				break
    48  			} else {
    49  				continue
    50  			}
    51  		} else if err == io.EOF {
    52  			break
    53  		}
    54  
    55  		out, exit, diags := session.Handle(line)
    56  		if diags.HasErrors() {
    57  			c.showDiagnostics(diags)
    58  		}
    59  		if exit {
    60  			break
    61  		}
    62  
    63  		ui.Output(out)
    64  	}
    65  
    66  	return 0
    67  }