當前位置: 首頁>>代碼示例>>Golang>>正文


Golang readline.NewEx函數代碼示例

本文整理匯總了Golang中github.com/chzyer/readline.NewEx函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewEx函數的具體用法?Golang NewEx怎麽用?Golang NewEx使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewEx函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: internalRun

func (a *App) internalRun() error {
	if a.commandTitle == "" {
		a.commandTitle = ">"
	}
	var historyFile string
	usr, err := user.Current()
	// Only load history if we can get the user
	if err == nil {
		historyFile = filepath.Join(usr.HomeDir, ".command_history")
	}

	l, err := readline.NewEx(&readline.Config{
		Prompt:       a.commandTitle,
		HistoryFile:  historyFile,
		AutoComplete: readline.NewPrefixCompleter(a.completeOptions...),
	})
	if err != nil {
		return err
	}
	a.line = l
	log.SetOutput(l.Stderr())

	for {
		l, e := a.line.Readline()
		if e != nil {
			return e
		}
		if !a.parseCommand(l) {
			break // exit main loop
		}
	}

	return nil
}
開發者ID:jhalickman,項目名稱:linecommand,代碼行數:34,代碼來源:linecommand.go

示例2: main

func main() {
	rl, err := readline.NewEx(&readline.Config{
		Prompt:                 "> ",
		HistoryFile:            "/tmp/readline-multiline",
		DisableAutoSaveHistory: true,
	})
	if err != nil {
		panic(err)
	}
	defer rl.Close()

	var cmds []string
	for {
		line, err := rl.Readline()
		if err != nil {
			break
		}
		line = strings.TrimSpace(line)
		if len(line) == 0 {
			continue
		}
		cmds = append(cmds, line)
		if !strings.Contains(line, ";") {
			rl.SetPrompt(">>> ")
			continue
		}
		cmd := strings.Join(cmds, " ")
		cmds = cmds[:0]
		rl.SetPrompt("> ")
		rl.SaveHistory(cmd)
		println(cmd)
	}
}
開發者ID:youtube,項目名稱:doorman,代碼行數:33,代碼來源:readline-multiline.go

示例3: main

func main() {
	l, err := readline.NewEx(&readline.Config{
		Prompt:      "\033[31m»\033[0m ",
		HistoryFile: "/tmp/readline.tmp",
	})
	if err != nil {
		panic(err)
	}
	defer l.Close()

	log.SetOutput(l.Stderr())
	for {
		line, err := l.Readline()
		if err != nil {
			break
		}
		switch line {
		case "help":
			usage(l.Stderr())
		case "sayhello":
			go func() {
				for _ = range time.Tick(time.Second) {
					log.Println("hello")
				}
			}()
		case "bye":
			goto exit
		case "":
		default:
			log.Println("you said:", strconv.Quote(line))
		}
	}
exit:
}
開發者ID:Blogoslov,項目名稱:readline,代碼行數:34,代碼來源:main.go

示例4: runInteractive

// runInteractive runs the SQL client interactively, presenting
// a prompt to the user for each statement.
func runInteractive(conn *sqlConn, config *readline.Config) (exitErr error) {
	c := cliState{conn: conn}

	state := cliStart
	for {
		if state == cliStop {
			break
		}
		switch state {
		case cliStart:
			// The readline initialization is not placed in
			// the doStart() method because of the defer.
			c.ins, c.exitErr = readline.NewEx(config)
			if c.exitErr != nil {
				return c.exitErr
			}
			defer func() { _ = c.ins.Close() }()

			state = c.doStart(cliQuerySyntax)

		case cliQuerySyntax:
			state = c.doQuerySyntax(cliStartLine)

		case cliStartLine:
			state = c.doStartLine(cliReadLine)

		case cliContinueLine:
			state = c.doContinueLine(cliReadLine)

		case cliReadLine:
			state = c.doReadLine(cliDecidePath)

		case cliDecidePath:
			state = c.doDecidePath()

		case cliProcessFirstLine:
			state = c.doProcessFirstLine(cliReadLine, cliHandleCliCmd)

		case cliHandleCliCmd:
			state = c.doHandleCliCmd(cliReadLine, cliPrepareStatementLine)

		case cliPrepareStatementLine:
			state = c.doPrepareStatementLine(
				cliStartLine, cliContinueLine, cliCheckStatement, cliRunStatement,
			)

		case cliCheckStatement:
			state = c.doCheckStatement(cliStartLine, cliContinueLine, cliRunStatement)

		case cliRunStatement:
			state = c.doRunStatement(cliQuerySyntax)

		default:
			panic(fmt.Sprintf("unknown state: %d", state))
		}
	}

	return c.exitErr
}
開發者ID:veteranlu,項目名稱:cockroach,代碼行數:61,代碼來源:sql.go

示例5: Interactive

func (app *App) Interactive() {
	rl, err := readline.NewEx(&readline.Config{
		Prompt:      color.BlueString("say » "),
		HistoryFile: app.Config.HistoryFile,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer rl.Close()
	app.Log.SetOutput(rl.Stderr())
	log.SetOutput(rl.Stderr())
	color.Output = ansicolor.NewAnsiColorWriter(rl.Stderr())

	pings := make(map[string]time.Time)

	// Subscribe to all replies and print them to stdout
	app.Client.Subscribe("", "self", func(msg sarif.Message) {
		text := msg.Text
		if text == "" {
			text = msg.Action + " from " + msg.Source
		}
		if msg.IsAction("err") {
			text = color.RedString(text)
		}

		if sent, ok := pings[msg.CorrId]; ok {
			text += color.YellowString("[%.1fms]", time.Since(sent).Seconds()*1e3)
		}
		log.Println(color.GreenString(" « ") + strings.Replace(text, "\n", "\n   ", -1))
	})

	// Interactive mode sends all lines from stdin.
	for {
		line, err := rl.Readline()
		if err != nil {
			if err == io.EOF {
				return
			}
			log.Fatal(err)
		}
		if len(line) == 0 {
			continue
		}

		// Publish natural message
		msg := sarif.Message{
			Id:     sarif.GenerateId(),
			Action: "natural/handle",
			Text:   line,
		}
		if *profile {
			pings[msg.Id] = time.Now()
		}
		app.Client.Publish(msg)
	}
}
開發者ID:sarifsystems,項目名稱:sarif,代碼行數:56,代碼來源:cmd_interactive.go

示例6: GetInput

// GetInput input terminal
func GetInput(addr string) (string, error) {
	prpt := fmt.Sprintf("(%s) > ", addr)
	rl, err := readline.NewEx(&readline.Config{Prompt: prpt, HistoryFile: "/tmp/mem_cli_history.tmp"})
	defer rl.Close()
	if err != nil {
		return "", err
	}
	line, _ := rl.Readline()
	return line, nil
}
開發者ID:cntoby,項目名稱:memcache_client,代碼行數:11,代碼來源:main.go

示例7: main

func main() {
	//Initialize Config
	GetConfig()
	CheckState()
	Clear()
	Msg(HeaderMsg, "discord-cli - version: %s\n\n", Version)

	//NewSession
	Session = DiscordState.NewSession(Config.Username, Config.Password) //Please don't abuse
	err := Session.Start()
	if err != nil {
		log.Println("Session Failed")
		log.Fatalln(err)
	}

	//Attach New Window
	InitWindow()

	//Attach Even Handlers
	State.Session.DiscordGo.AddHandler(newMessage)

	//Setup Readline
	rl, err := readline.NewEx(&readline.Config{
		Prompt:         "> ",
		UniqueEditLine: true,
	})

	defer rl.Close()
	log.SetOutput(rl.Stderr()) // let "log" write to l.Stderr instead of os.Stderr

	//Start Listening
	for {
		line, _ := rl.Readline()

		//QUIT
		if line == ":q" {
			break
		}

		//Parse Commands
		line = ParseForCommands(line)

		line = ParseForMentions(line)

		if line != "" {
			State.Session.DiscordGo.ChannelMessageSend(State.Channel.ID, line)
		}
	}

	return
}
開發者ID:Rivalo,項目名稱:discord-cli,代碼行數:51,代碼來源:main.go

示例8: main

func main() {
	rl, err := readline.NewEx(&readline.Config{
		UniqueEditLine: true,
	})
	if err != nil {
		panic(err)
	}
	defer rl.Close()

	rl.SetPrompt("username: ")
	username, err := rl.Readline()
	if err != nil {
		return
	}
	rl.ResetHistory()
	log.SetOutput(rl.Stderr())

	fmt.Fprintln(rl, "Hi,", username+"! My name is Dave.")
	rl.SetPrompt(username + "> ")

	done := make(chan struct{})
	go func() {
		rand.Seed(time.Now().Unix())
	loop:
		for {
			select {
			case <-time.After(time.Duration(rand.Intn(20)) * 100 * time.Millisecond):
			case <-done:
				break loop
			}
			log.Println("Dave:", "hello")
		}
		log.Println("Dave:", "bye")
		done <- struct{}{}
	}()

	for {
		ln := rl.Line()
		if ln.CanContinue() {
			continue
		} else if ln.CanBreak() {
			break
		}
		log.Println(username+":", ln.Line)
	}
	rl.Clean()
	done <- struct{}{}
	<-done
}
開發者ID:chzyer,項目名稱:readline,代碼行數:49,代碼來源:readline-im.go

示例9: startLocal

func startLocal() {
	rl, err := readline.NewEx(
		&readline.Config{
			Prompt: "> ",
		},
	)

	if err != nil {
		panic(err)
	}

	g := NewLocalGame(rl)
	g.play()

}
開發者ID:hopkinsth,項目名稱:rv-text-adventure,代碼行數:15,代碼來源:main.go

示例10: main

func main() {
	l, err := readline.NewEx(&readline.Config{
		Prompt:       "\033[31m»\033[0m ",
		HistoryFile:  "/tmp/readline.tmp",
		AutoComplete: completer,
	})
	if err != nil {
		panic(err)
	}
	defer l.Close()

	log.SetOutput(l.Stderr())
	for {
		line, err := l.Readline()
		if err != nil {
			break
		}

		switch {
		case line == "help":
			usage(l.Stderr())
		case strings.HasPrefix(line, "setprompt"):
			prompt := line[10:]
			if prompt == "" {
				log.Println("setprompt <prompt>")
				break
			}
			l.SetPrompt(prompt)
		case strings.HasPrefix(line, "say"):
			line := strings.TrimSpace(line[3:])
			if len(line) == 0 {
				log.Println("say what?")
				break
			}
			go func() {
				for _ = range time.Tick(time.Second) {
					log.Println(line)
				}
			}()
		case line == "bye":
			goto exit
		case line == "":
		default:
			log.Println("you said:", strconv.Quote(line))
		}
	}
exit:
}
開發者ID:sscherbinski,項目名稱:readline,代碼行數:48,代碼來源:main.go

示例11: NewShell

// NewShell creates a new shell with default settings. Uses standard output and default prompt ">>".
func NewShell(completer *readline.PrefixCompleter) *Shell {
	shell := &Shell{
		prompt:     defaultPrompt,
		showPrompt: true,
		functions:  make(map[string]CmdFunc),
		reader: &shellReader{
			scanner: bufio.NewReader(os.Stdin),
		},
		writer:   os.Stdout,
		haltChan: make(chan struct{}),
	}
	rl, err := readline.NewEx(&readline.Config{Prompt: shell.prompt, AutoComplete: completer})
	if err != nil {
		panic(err)
	}
	shell.rl = rl
	addDefaultFuncs(shell)
	return shell
}
開發者ID:jheroy,項目名稱:ishell,代碼行數:20,代碼來源:ishell.go

示例12: modeInteractive

func (c *ConsoleCommand) modeInteractive(session *repl.Session, ui cli.Ui) int {
	// Configure input
	l, err := readline.NewEx(wrappedreadline.Override(&readline.Config{
		Prompt:            "> ",
		InterruptPrompt:   "^C",
		EOFPrompt:         "exit",
		HistorySearchFold: true,
	}))
	if err != nil {
		c.Ui.Error(fmt.Sprintf(
			"Error initializing console: %s",
			err))
		return 1
	}
	defer l.Close()

	for {
		// Read a line
		line, err := l.Readline()
		if err == readline.ErrInterrupt {
			if len(line) == 0 {
				break
			} else {
				continue
			}
		} else if err == io.EOF {
			break
		}

		out, err := session.Handle(line)
		if err == repl.ErrSessionExit {
			break
		}
		if err != nil {
			ui.Error(err.Error())
			continue
		}

		ui.Output(out)
	}

	return 0
}
開發者ID:ryane,項目名稱:terraform,代碼行數:43,代碼來源:console_interactive.go

示例13: main

func main() {
	rl, err := readline.NewEx(&readline.Config{
		Prompt:      "> ",
		HistoryFile: "/tmp/flagly-shell.readline",
	})
	if err != nil {
		println(err.Error())
		os.Exit(1)
	}
	defer rl.Close()

	var p Program
	fset, err := flagly.Compile("", &p)
	if err != nil {
		println(err.Error())
		os.Exit(1)
	}
	rl.Config.AutoComplete = &readline.SegmentComplete{fset.Completer()}

	for {
		line, err := rl.Readline()
		if err != nil {
			break
		}
		if line == "" {
			continue
		}
		command, err := shlex.Split(line)
		if err != nil {
			println("error: " + err.Error())
			continue
		}
		if err := fset.Run(command); err != nil {
			println(err.Error())
		}
	}
}
開發者ID:chzyer,項目名稱:flagly,代碼行數:37,代碼來源:flagly-shell.go

示例14: main

func main() {
	l, err := readline.NewEx(&readline.Config{
		Prompt:          "\033[31m»\033[0m ",
		HistoryFile:     "/tmp/readline.tmp",
		AutoComplete:    completer,
		InterruptPrompt: "^C",
		EOFPrompt:       "exit",

		HistorySearchFold: true,
	})
	if err != nil {
		panic(err)
	}
	defer l.Close()

	setPasswordCfg := l.GenPasswordConfig()
	setPasswordCfg.SetListener(func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool) {
		l.SetPrompt(fmt.Sprintf("Enter password(%v): ", len(line)))
		l.Refresh()
		return nil, 0, false
	})

	log.SetOutput(l.Stderr())
	for {
		line, err := l.Readline()
		if err == readline.ErrInterrupt {
			if len(line) == 0 {
				break
			} else {
				continue
			}
		} else if err == io.EOF {
			break
		}

		line = strings.TrimSpace(line)
		switch {
		case strings.HasPrefix(line, "mode "):
			switch line[5:] {
			case "vi":
				l.SetVimMode(true)
			case "emacs":
				l.SetVimMode(false)
			default:
				println("invalid mode:", line[5:])
			}
		case line == "mode":
			if l.IsVimMode() {
				println("current mode: vim")
			} else {
				println("current mode: emacs")
			}
		case line == "login":
			pswd, err := l.ReadPassword("please enter your password: ")
			if err != nil {
				break
			}
			println("you enter:", strconv.Quote(string(pswd)))
		case line == "help":
			usage(l.Stderr())
		case line == "setpassword":
			pswd, err := l.ReadPasswordWithConfig(setPasswordCfg)
			if err == nil {
				println("you set:", strconv.Quote(string(pswd)))
			}
		case strings.HasPrefix(line, "setprompt"):
			if len(line) <= 10 {
				log.Println("setprompt <prompt>")
				break
			}
			l.SetPrompt(line[10:])
		case strings.HasPrefix(line, "say"):
			line := strings.TrimSpace(line[3:])
			if len(line) == 0 {
				log.Println("say what?")
				break
			}
			go func() {
				for range time.Tick(time.Second) {
					log.Println(line)
				}
			}()
		case line == "bye":
			goto exit
		case line == "sleep":
			log.Println("sleep 4 second")
			time.Sleep(4 * time.Second)
		case line == "":
		default:
			log.Println("you said:", strconv.Quote(line))
		}
	}
exit:
}
開發者ID:chzyer,項目名稱:readline,代碼行數:94,代碼來源:readline-demo.go

示例15: main

func main() {
	kingpin.Parse()

	var conn net.Conn
	var err error
	if *rawtls {
		conn, err = tls.Dial("tcp", *address, &tls.Config{
			InsecureSkipVerify: true,
		})
		if err != nil {
			fmt.Fprintf(os.Stderr, "Connect failed: %v\n", err)
			return
		}
	} else {
		conn, err = net.Dial("tcp", *address)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Connect failed: %v\n", err)
			return
		}
	}

	c := client.New(conn)
	go func() {
		err := c.Serve()
		if err != nil {
			fmt.Fprintf(os.Stderr, "\nConnection lost: %v\n", err)
			os.Exit(-1)
		}
	}()

	_, _, err = c.Version(1024*1024, qp.Version)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Version failed: %v\n", err)
		return
	}

	root, _, err := c.Attach(nil, *user, *service)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Attach failed: %v\n", err)
		return
	}

	cwd := root

	confirmation, err = readline.New("")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Could not make confirmation readline instance: %v\n", err)
		return
	}

	if len(*command) > 0 {
		args := ""
		for i := 1; i < len(*command); i++ {
			if i != 1 {
				args += " "
			}
			args += (*command)[i]
		}

		f, ok := cmds[(*command)[0]]
		if !ok {
			fmt.Fprintf(os.Stderr, "no such command: [%s]\n", *command)
			return
		}
		cwd, err = f(root, cwd, args)
		if err != nil {
			fmt.Fprintf(os.Stderr, "\ncommand %s failed: %v\n", *command, err)
		}
		return
	}

	completer := readline.NewPrefixCompleter()
	for k := range cmds {
		completer.Children = append(completer.Children, readline.PcItem(k))
	}

	rl, err := readline.NewEx(&readline.Config{
		Prompt:       "9p> ",
		AutoComplete: completer,
	})

	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create readline: %v\n", err)
		return
	}

	defer rl.Close()

	fmt.Fprintf(os.Stderr, "Welcome to the qptools 9P cli.\nPress tab to see available commands.\n")

	for {
		line, err := rl.Readline()
		if err != nil { // io.EOF
			break
		}

		idx := strings.Index(line, " ")
		var cmd, args string
		if idx != -1 {
			cmd = line[:idx]
//.........這裏部分代碼省略.........
開發者ID:joushou,項目名稱:qptools,代碼行數:101,代碼來源:main.go


注:本文中的github.com/chzyer/readline.NewEx函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。