• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang readline.AddHistory函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/bobappleyard/readline.AddHistory函数的典型用法代码示例。如果您正苦于以下问题:Golang AddHistory函数的具体用法?Golang AddHistory怎么用?Golang AddHistory使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了AddHistory函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	env := evaluator.BuildEnvironment()

	for {
		l, err := readline.String("> ")
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			break
		}

		f, err := parser.Parse(strings.NewReader(l))
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			readline.AddHistory(l)
		}

		r, err := evaluator.Eval(env, f)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
		} else {
			fmt.Println(r)
		}
		readline.AddHistory(l)
	}
}
开发者ID:alanthird,项目名称:gscheme,代码行数:28,代码来源:main.go


示例2: replCLI

func replCLI(env *Env) {
	defer fmt.Println("\nbye!")
	counter := readline.HistorySize()
	for {
		buf := bytes.Buffer{}
		prompt := fmt.Sprintf("[%d]-> ", counter)
		for {
			l, err := readline.String(prompt)
			if err == io.EOF {
				return
			}
			buf.WriteString(l)
			if validSexp(buf.String()) {
				break
			}
			buf.WriteString("\n")
			prompt = ": "
		}
		result, err := repl(buf.String(), env)
		if err != nil && err != ErrorEOF {
			fmt.Println("Error:", err)
		} else {
			fmt.Println(result)
		}
		readline.AddHistory(buf.String())
		counter++

	}
}
开发者ID:rread,项目名称:rsi,代码行数:29,代码来源:main.go


示例3: main

/*
func main() {
	flag.Parse()
	go sigHandler()

	rl, err := readline.New("> ")
	if err != nil {
		panic(err)
	}
	defer rl.Close()

	for {
		line, err := rl.Readline()
		if err != nil {
			break
		}
		args := strings.Fields(line)
		if len(args) == 0 {
			continue
		}
		f, ok := cmd[args[0]]
		if ok {
			err := f(args[1:])
			if err != nil {
				log.Println(line, err)
			}
		} else {
			log.Println("Not found:", line)
		}
		stop = false
	}
	fmt.Println("Exiting")
}
*/
func main() {
	flag.Parse()
	go sigHandler()

	for {
		line, err := readline.String("% ")
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Println("error:", err)
			break
		}
		args := strings.Fields(line)
		if len(args) == 0 {
			continue
		}
		f, ok := cmd[args[0]]
		if ok {
			err := f(args[1:])
			if err != nil {
				log.Println(line, err)
			}
		} else {
			log.Println("Not found:", line)
		}
		stop = false
		readline.AddHistory(line)
	}
	fmt.Println("Exiting")
}
开发者ID:taysom,项目名称:va,代码行数:65,代码来源:main.go


示例4: Start

// Starts the controller.
func (c *Controller) Start() int {
	c.welcome()
	c.ChangeWorkingDir("/")

	readline.Completer = c.filenameCompleter
	buffer := bytes.NewBufferString("")
	prompt := ""

	for {
		if buffer.Len() == 0 {
			prompt = c.ps1()
		} else {
			prompt = c.ps2()
		}

		line, err := readline.String(prompt)
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}

		line = strings.TrimSpace(line)
		if strings.ToLower(line) == "q" || strings.ToLower(line) == "exit" {
			return 0
		}
		if strings.HasSuffix(line, "\\") {
			buffer.WriteString(strings.TrimSuffix(line, "\\") + "\n")
		} else {
			if buffer.Len() > 0 {
				buffer.WriteString(line)
				line = buffer.String()
				buffer.Reset()
			}

			parts, err := shlex.Split(line)
			if err != nil {
				panic(err)
			}
			readline.AddHistory(line)

			in := NewInput(parts[0])
			if len(parts) > 1 {
				in.Args = parts[1:]
			}
			c.handleInput(in)
		}
	}

	return 0
}
开发者ID:headzoo,项目名称:etcdsh,代码行数:53,代码来源:controller.go


示例5: interact

// Gets additional suppression patterns, etc. from the user.
func interact(done chan<- string) {
	const prompt = "prolix> "
L:
	for {
		cmd, _ := readline.String(prompt)
		if cmd == "" {
			break L
		}
		readline.AddHistory(cmd)
		unary := unaryRe.FindStringSubmatch(cmd)
		if unary == nil {
			trimmed := strings.TrimSpace(cmd)
			switch trimmed {
			case "quit":
				done <- "quit"
				return
			case "pats":
				printPats()
			case "help":
				printInteractiveHelp()
			default:
				fmt.Println("Unknown command. Try 'help'.")
			}
		} else {
			switch strings.Replace(unary[1], "_", "-", -1) {
			case "ignore-re":
				if importIgnoreRE(unary[2:3]) {
					ignoreRe = append(ignoreRe, unary[2])
				}
			case "ignore-line":
				ignoreLine = append(ignoreLine, unary[2])
			case "ignore-substring":
				ignoreSubstring = append(ignoreSubstring, unary[2])
			case "snippet":
				if importSnippet(unary[2:3]) {
					snippet = append(snippet, unary[2])
				}
			default:
				fmt.Println("Unknown unary command. Try 'help'.")
			}
		}
	}
	done <- ""
}
开发者ID:gaal,项目名称:prolix-go,代码行数:45,代码来源:prolix.go


示例6: CommandParser

func CommandParser() <-chan Command {
	commands := make(chan Command, 1)

	go func() {
		for {
			in, err := readline.String("")
			if err == io.EOF { // Ctrl+D
				commands <- Exit
				break
			} else if err != nil {
				log.Fatal(err)
			}

			commands <- NormalizeCommand(in)
			readline.AddHistory(in)
		}
	}()

	return commands
}
开发者ID:rschmukler,项目名称:looper,代码行数:20,代码来源:input.go


示例7: promptLoop

func promptLoop(prompt string, process func(string) error) (err error) {

	errStr := "Error - %s.\n"
	for moreCommands := true; moreCommands; {
		line, err := readline.String(prompt)
		if err == io.EOF {
			moreCommands = false
		} else if err != nil {
			fmt.Printf(errStr, err)
		} else {
			readline.AddHistory(line)
			err = process(line)
			if err == io.EOF {
				moreCommands = false
			} else if err != nil {
				fmt.Printf(errStr, err)
			}
		}
	}
	return nil
}
开发者ID:jdrivas,项目名称:spur,代码行数:21,代码来源:helper.go


示例8: doPrompt

func doPrompt(s *KinesisStream) {

	moreToRead := true
	for moreToRead {
		line, err := readline.String("Send to Kinesis, <crtl-d> to end: ")
		if err == io.EOF {
			moreToRead = false
		} else if err != nil {
			log.Fatal(err)
		} else {
			resp, err := s.PutLogLine(strings.TrimRight(line, "\n"))
			if err != nil {
				log.Fatal(err)
			}
			if verbose {
				fmt.Println("Response:", awsutil.StringValue(resp))
			}
			readline.AddHistory(line)
		}
	}
}
开发者ID:jdrivas,项目名称:spur,代码行数:21,代码来源:spur.go


示例9: actionLauncher


//.........这里部分代码省略.........
				a.ExpireAfter = a.ValidFrom.Add(period)
				a.ExpireAfter = a.ExpireAfter.Add(60 * time.Second).UTC()
				hasTimes = true
			}
			if !hasSignatures {
				pgpsig, err := computeSignature(a, ctx)
				if err != nil {
					panic(err)
				}
				a.PGPSignatures = append(a.PGPSignatures, pgpsig)
				hasSignatures = true
			}
			a, err = postAction(a, follow, ctx)
			if err != nil {
				panic(err)
			}
			fmt.Println("")
			_ = actionReader(fmt.Sprintf("action %.0f", a.ID), ctx)
			goto exit
		case "load":
			if len(orders) != 2 {
				fmt.Println("Wrong arguments. Expects 'load <path_to_file>'")
				break
			}
			a, err = mig.ActionFromFile(orders[1])
			if err != nil {
				panic(err)
			}
			fmt.Printf("Loaded action '%s' from %s\n", a.Name, orders[1])
		case "sign":
			if !hasTimes {
				fmt.Println("Times must be set prior to signing")
				break
			}
			pgpsig, err := computeSignature(a, ctx)
			if err != nil {
				panic(err)
			}
			a.PGPSignatures = append(a.PGPSignatures, pgpsig)
			hasSignatures = true
		case "setname":
			if len(orders) < 2 {
				fmt.Println("Wrong arguments. Must be 'setname <some_name>'")
				break
			}
			a.Name = strings.Join(orders[1:], " ")
		case "settarget":
			if len(orders) < 2 {
				fmt.Println("Wrong arguments. Must be 'settarget <some_target_string>'")
				break
			}
			a.Target = strings.Join(orders[1:], " ")
		case "settimes":
			// set the dates
			if len(orders) != 3 {
				fmt.Println(`Invalid times. Expects settimes <start> <stop.)
examples:
settimes 2014-06-30T12:00:00.0Z 2014-06-30T14:00:00.0Z
settimes now +60m
`)
				break
			}
			if orders[1] == "now" {
				// for immediate execution, set validity one minute in the past
				a.ValidFrom = time.Now().Add(-60 * time.Second).UTC()
				period, err := time.ParseDuration(orders[2])
				if err != nil {
					fmt.Println("Failed to parse duration '%s': %v", orders[2], err)
					break
				}
				a.ExpireAfter = a.ValidFrom.Add(period)
				a.ExpireAfter = a.ExpireAfter.Add(60 * time.Second).UTC()
			} else {
				a.ValidFrom, err = time.Parse("2014-01-01T00:00:00.0Z", orders[1])
				if err != nil {
					fmt.Println("Failed to parse time '%s': %v", orders[1], err)
					break
				}
				a.ExpireAfter, err = time.Parse("2014-01-01T00:00:00.0Z", orders[2])
				if err != nil {
					fmt.Println("Failed to parse time '%s': %v", orders[2], err)
					break
				}
			}
			hasTimes = true
		case "times":
			fmt.Printf("Valid from   '%s' until '%s'\nStarted on   '%s'\n"+
				"Last updated '%s'\nFinished on  '%s'\n",
				a.ValidFrom, a.ExpireAfter, a.StartTime, a.LastUpdateTime, a.FinishTime)
		case "":
			break
		default:
			fmt.Printf("Unknown order '%s'. You are in action launcher mode. Try `help`.\n", orders[0])
		}
		readline.AddHistory(input)
	}
exit:
	fmt.Printf("\n")
	return
}
开发者ID:netantho,项目名称:mig,代码行数:101,代码来源:action_launcher.go


示例10: main


//.........这里部分代码省略.........
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("\nConnected to %s. Exit with \x1b[32;1mctrl+d\x1b[0m. Type \x1b[32;1mhelp\x1b[0m for help.\n", ctx.API.URL)
	for {
		// completion
		var symbols = []string{"action", "agent", "command", "help", "exit", "showcfg", "status",
			"search", "where", "and"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String("\x1b[32;1mmig>\x1b[0m ")
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "action":
			if len(orders) == 2 {
				if orders[1] == "new" {
					var a mig.Action
					err = actionLauncher(a, ctx)
				} else {
					err = actionReader(input, ctx)
				}
				if err != nil {
					log.Println(err)
				}
			} else {
				fmt.Println("error: 'action' order takes one argument; " +
					"either 'new' to enter launcher mode, or an action ID to enter reader mode.")
			}
		case "agent":
			err = agentReader(input, ctx)
			if err != nil {
				log.Println(err)
			}
		case "command":
			err = commandReader(input, ctx)
			if err != nil {
				log.Println(err)
			}
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "help":
			fmt.Printf(`The following orders are available:
action <id|new>	enter action mode. if <id> is given, go to reader mode. if "new" is given, enter launcher mode.
command <id>	enter command reader mode for command <id>
help		show this help
exit		leave
search		perform a search. see "search help" for more information.
showcfg		display running configuration
status		display platform status: connected agents and latest actions
`)
		case "search":
			err = search(input, ctx)
			if err != nil {
				log.Println(err)
			}
		case "showcfg":
			fmt.Printf("homedir = %s\n[api]\n    url = %s\n[gpg]\n    home = %s\n    keyid = %s\n",
				ctx.API.URL, ctx.Homedir, ctx.GPG.Home, ctx.GPG.KeyID)
		case "status":
			err = printStatus(ctx)
			if err != nil {
				log.Println(err)
			}
		case "":
			break
		default:
			fmt.Printf("Unknown order '%s'\n", orders[0])
		}
		readline.AddHistory(input)
	}
exit:
	fmt.Printf(`
            .-._   _ _ _ _ _ _ _ _
 .-''-.__.-'Oo  '-' ' ' ' ' ' ' ' '-.
'.___ '    .   .--_'-' '-' '-' _'-' '._
 V: V 'vv-'   '_   '.       .'  _..' '.'.
   '=.____.=_.--'   :_.__.__:_   '.   : :
           (((____.-'        '-.  /   : :
                             (((-'\ .' /
                           _____..'  .'
                          '-._____.-'
              Gators are going back underwater.
`)
}
开发者ID:netantho,项目名称:mig,代码行数:101,代码来源:console.go


示例11: REPL

func REPL(c Context) (Context, error) {
	tokens := []string{}
	leftCount := 0
	rightCount := 0

	for {
		prompt := mainPrompt
		if len(tokens) > 0 {
			prompt = incompletePrompt
		}

		line, err := readline.String(prompt)
		if err != nil {
			return nil, err
		}

		if line != "" {
			line = strings.TrimRight(line, "\r\n ")
			readline.AddHistory(line)

			if line == "quit" {
				return c, nil
			}

			temp := Tokenize(line)
			for _, t := range temp {
				if t == "(" || t == "'(" {
					leftCount += 1
				} else if t == ")" {
					rightCount += 1
				}
			}

			tokens = append(tokens, temp...)

			if leftCount == rightCount {
				nodes, err := Parse(tokens)
				if err != nil {
					fmt.Println("error: ", err)
				} else {
					for _, n := range nodes {
						r := n.Eval(c)

						if r.Type() == "error" {
							fmt.Println("error:", r.Value().(string))
							break
						}

						if r != NIL {
							fmt.Println(r)
						}
					}
				}

				leftCount = 0
				rightCount = 0
				tokens = []string{}
			}
		}
	}
}
开发者ID:ktravis,项目名称:sigmo,代码行数:61,代码来源:repl.go


示例12: commandReader

// commandReader retrieves an command from the API using its numerical ID
// and enters prompt mode to analyze it
func commandReader(input string, cli client.Client) (err error) {
	defer func() {
		if e := recover(); e != nil {
			err = fmt.Errorf("commandReader() -> %v", e)
		}
	}()
	inputArr := strings.Split(input, " ")
	if len(inputArr) < 2 {
		panic("wrong order format. must be 'command <commandid>'")
	}
	cmdid, err := strconv.ParseFloat(inputArr[1], 64)
	if err != nil {
		panic(err)
	}
	cmd, err := cli.GetCommand(cmdid)
	if err != nil {
		panic(err)
	}

	fmt.Println("Entering command reader mode. Type \x1b[32;1mexit\x1b[0m or press \x1b[32;1mctrl+d\x1b[0m to leave. \x1b[32;1mhelp\x1b[0m may help.")
	fmt.Printf("Command %.0f ran on agent '%s' based on action '%s'\n",
		cmd.ID, cmd.Agent.Name, cmd.Action.Name)
	prompt := fmt.Sprintf("\x1b[36;1mcommand %d>\x1b[0m ", uint64(cmdid)%1000)
	for {
		// completion
		var symbols = []string{"exit", "help", "json", "found", "pretty", "r", "results"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String(prompt)
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "help":
			fmt.Printf(`The following orders are available:
exit		exit this mode
help		show this help
json		show the json of the command
r		refresh the command (get latest version from upstream)
results <found>	print the results. if "found" is set, only print results that have at least one found
`)
		case "json":
			var cjson []byte
			cjson, err = json.MarshalIndent(cmd, "", "  ")
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s\n", cjson)
		case "r":
			cmd, err = cli.GetCommand(cmdid)
			if err != nil {
				panic(err)
			}
			fmt.Println("Reload succeeded")
		case "results":
			found := false
			if len(orders) > 1 {
				if orders[1] == "found" {
					found = true
				} else {
					fmt.Printf("Unknown option '%s'\n", orders[1])
				}
			}
			err = client.PrintCommandResults(cmd, found, false)
			if err != nil {
				panic(err)
			}
		case "":
			break
		default:
			fmt.Printf("Unknown order '%s'. You are in command reader mode. Try `help`.\n", orders[0])
		}
		readline.AddHistory(input)
	}
exit:
	fmt.Printf("\n")
	return
}
开发者ID:Novemburr,项目名称:mig,代码行数:96,代码来源:command_reader.go


示例13: addHistory

func addHistory(line string) {
	readline.AddHistory(line)
}
开发者ID:sneakyweasel,项目名称:algernon,代码行数:3,代码来源:input_unix.go


示例14: main


//.........这里部分代码省略.........
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "action":
			if len(orders) == 2 {
				err = actionReader(input, cli)
				if err != nil {
					log.Println(err)
				}
			} else {
				fmt.Println("error: missing action id in 'action <id>'")
			}
		case "agent":
			err = agentReader(input, cli)
			if err != nil {
				log.Println(err)
			}
		case "create":
			if len(orders) == 2 {
				switch orders[1] {
				case "action":
					var a mig.Action
					err = actionLauncher(a, cli)
				case "investigator":
					err = investigatorCreator(cli)
				default:
					fmt.Printf("unknown order 'create %s'\n", orders[1])
				}
				if err != nil {
					log.Println(err)
				}
			} else {
				fmt.Println("error: missing order, must be 'create <action|investigator>'")
			}
		case "command":
			err = commandReader(input, cli)
			if err != nil {
				log.Println(err)
			}
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "help":
			fmt.Printf(`The following orders are available:
action <id>		enter interactive action reader mode for action <id>
agent <id>		enter interactive agent reader mode for agent <id>
create action		create a new action
create investigator	create a new investigator, will prompt for name and public key
command <id>		enter command reader mode for command <id>
exit			leave
help			show this help
history <count>		print last <count> entries in history. count=10 by default.
investigator <id>	enter interactive investigator management mode for investigator <id>
search			perform a search. see "search help" for more information.
showcfg			display running configuration
status			display platform status: connected agents, latest actions, ...
`)
		case "history":
			var count int64 = 10
			if len(orders) > 1 {
				count, err = strconv.ParseInt(orders[1], 10, 64)
				if err != nil {
					log.Println(err)
					break
				}
			}
			for i := readline.HistorySize(); i > 0 && count > 0; i, count = i-1, count-1 {
				fmt.Println(readline.GetHistory(i - 1))
			}
		case "investigator":
			err = investigatorReader(input, cli)
			if err != nil {
				log.Println(err)
			}
		case "search":
			err = search(input, cli)
			if err != nil {
				log.Println(err)
			}
		case "showcfg":
			fmt.Printf("homedir = %s\n[api]\n    url = %s\n[gpg]\n    home = %s\n    keyid = %s\n",
				cli.Conf.API.URL, cli.Conf.Homedir, cli.Conf.GPG.Home, cli.Conf.GPG.KeyID)
		case "status":
			err = printStatus(cli)
			if err != nil {
				log.Println(err)
			}
		case "":
			break
		default:
			fmt.Printf("Unknown order '%s'\n", orders[0])
		}
		readline.AddHistory(input)
	}
exit:
	fmt.Fprintf(out, footer)
	err = readline.SaveHistory(historyfile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to save history to %s\n", historyfile)
	}
}
开发者ID:Novemburr,项目名称:mig,代码行数:101,代码来源:console.go


示例15: loaderReader


//.........这里部分代码省略.........
		reloadfunc := func() {
			le, err = cli.GetLoaderEntry(lid)
			if err != nil {
				panic(err)
			}
			fmt.Println("reloaded")
		}
		var symbols = []string{"disable", "enable", "exit", "help", "json", "key", "r"}
		readline.Completer = func(query, ctx string) []string {
			var res []string
			for _, sym := range symbols {
				if strings.HasPrefix(sym, query) {
					res = append(res, sym)
				}
			}
			return res
		}

		input, err := readline.String(prompt)
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "disable":
			err = cli.LoaderEntryStatus(le, false)
			if err != nil {
				panic(err)
			}
			fmt.Println("Loader has been disabled")
			reloadfunc()
		case "enable":
			err = cli.LoaderEntryStatus(le, true)
			if err != nil {
				panic(err)
			}
			fmt.Println("Loader has been enabled")
			reloadfunc()
		case "help":
			fmt.Printf(`The following orders are avialable:
disable         disable loader entry

enable          enable loader entry

help            show this help

exit            exit this mode (also works with ctrl+d)

json            show json of loader entry stored in database

key             change loader key

r               refresh the loader entry (get latest version from database)
`)
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "json":
			jsonle, err := json.MarshalIndent(le, "", "  ")
			if err != nil {
				panic(err)
			}
			fmt.Printf("%v\n", string(jsonle))
		case "key":
			fmt.Printf("New key component must be %v alphanumeric characters long, or type 'generate' to generate one\n", mig.LoaderKeyLength)
			lkey, err := readline.String("New key for loader> ")
			if err != nil {
				panic(err)
			}
			if lkey == "" {
				panic("invalid key specified")
			}
			if lkey == "generate" {
				lkey = mig.GenerateLoaderKey()
				fmt.Printf("New key will be set to %v\n", lkey)
			}
			fmt.Printf("New key including prefix to supply to client will be %q\n", le.Prefix+lkey)
			err = cli.LoaderEntryKey(le, lkey)
			if err != nil {
				panic(err)
			}
			fmt.Println("Loader key changed")
		case "r":
			reloadfunc()
		case "":
			break
		default:
			fmt.Printf("Unknown order '%s'. You are in loader reader mode. Try `help`.\n", orders[0])
		}
		readline.AddHistory(input)
	}

exit:
	fmt.Printf("\n")
	return
}
开发者ID:ZhuHangpeng,项目名称:mig,代码行数:101,代码来源:loader.go


示例16: readCommand

func readCommand() {
	// Reset the color on defer.
	defer fmt.Print(colorReset)

	// Read the input line.
	line, err := gnureadline.String(prompt)
	if err == io.EOF {
		// Print a new line.
		fmt.Println("")
		return
	} else if err != nil {
		fmt.Printf("%serror: %v\n", colorError, err)
		return
	}

	// Set to output color.
	fmt.Print(colorOutput)

	// Trim all spaces.
	line = strings.TrimSpace(line)

	// Split the input line.
	args := strings.Fields(line)

	// Skip if empty.
	if len(args) == 0 {
		return
	}

	// Get the command key.
	key := args[0]

	// Remove the first command key from the slice.
	args = args[1:]

	// Try to find the command in the commands map.
	cmd, ok := commands[key]
	if !ok {
		fmt.Printf("%serror: invalid command\n", colorError)
		return
	}

	// Add the command to the history.
	gnureadline.AddHistory(line)

	// Run the command.
	err = cmd.Run(args)
	if err != nil {
		fmt.Printf("%serror: %v\n", colorError, err)

		// Print the usage if this is an invalid usage error.
		if err == errInvalidUsage {
			// Set to output color.
			fmt.Print(colorReset, colorOutput, "\n")

			cmd.PrintUsage()
		}

		return
	}
}
开发者ID:gitter-badger,项目名称:turtle,代码行数:61,代码来源:client.go


示例17: main

func main() {
	host := flag.String("host", "http://localhost:8000", "hostname")
	flag.Parse()

	var client wpmutils.JobqueueHTTPClient

	msg, err := client.Open(*host)
	if err != nil {
		fmt.Println("Invalid address " + (*host) + ":" + err.Error())
		os.Exit(-1)
	}
	fmt.Println(msg)

	//autocomplete = wpmutils.ListTaskNames(*taskdir)
	//readline.Completer = readline.FilenameCompleter

	autocomplete = append(client.ListAsList(), getKeywords()...)
	readline.Completer = taskNameCompleter

	// loop until ReadLine returns nil (signalling EOF)
Loop:
	for {
		rl, err := readline.String("> ")
		if err == io.EOF {
			break Loop
		}
		if err != nil {
			fmt.Println("Error: ", err)
			break Loop
		}
		if "" == rl {
			// ignore blank lines
			continue Loop
		}

		// allow user to recall this line
		readline.AddHistory(rl)

		// split the main command from its (optional) parameters
		command, parameters := parseReadline(rl)

		var msg string

		switch command {
		case "quit", "exit":
			fmt.Println()
			break Loop //exit loop
		case "ls", "list":
			msg, err = client.List()
		case "lw", "listworkers":
			msg, err = client.ListWorkers(parameters)
		case "set":
			taskname, p, v := parseParams(parameters)
			msg, err = client.Set(taskname, p, v)
		case "start":
			msg, err = client.Start(parameters)
		case "stop":
			msg, err = client.Stop(parameters)
		case "st", "status":
			msg, err = client.Status(parameters)
		case "connect", "open":
			msg, err = client.Open(parameters)
			if err == nil {
				// refresh auto-complete list
				autocomplete = append(client.ListAsList(), getKeywords()...)
			}
		case "help", "h":
			msg = getHelp()
		default:
			msg = "ERROR: Command not recognised: " + command
		}

		if err != nil {
			msg = "ERROR: " + err.Error()
		}
		fmt.Println(msg)
	}
	fmt.Println("") // newline before exit
}
开发者ID:mahasak,项目名称:workerpoolmanager,代码行数:79,代码来源:wpconsole.go


示例18: printContext

func printContext(lines []string, line, contextCount int) {
	line-- // token.Position.Line starts at 1.
	fmt.Println()
	for i := line - contextCount; i <= line+contextCount; i++ {
		prefix := "    "
		if i == line {
			prefix = "--> "
		}
		if i >= 0 && i < len(lines) {
			line := strings.TrimRightFunc(prefix+lines[i], unicode.IsSpace)
			fmt.Println(line)
		}
	}
	fmt.Println()
}

var input = bufio.NewScanner(os.Stdin)

// This gets overridden when running in a browser.
var promptUser = func() (response string, ok bool) {
	l, err := readline.String("(godebug) ")
	if err != nil {
		return "", false
	}
	if l != "" {
		readline.AddHistory(l)
	}
	return l, true
}
开发者ID:willf,项目名称:godebug,代码行数:29,代码来源:debug.go


示例19: actionReader


//.........这里部分代码省略.........
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("error: ", err)
			break
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "command":
			err = commandReader(input, ctx)
			if err != nil {
				panic(err)
			}
		case "copy":
			err = actionLauncher(a, ctx)
			if err != nil {
				panic(err)
			}
			goto exit
		case "counters":
			fmt.Printf("Sent:\t\t%d\nReturned:\t%d\nDone:\t\t%d\n"+
				"Cancelled:\t%d\nFailed:\t\t%d\nTimeout:\t%d\n",
				a.Counters.Sent, a.Counters.Returned, a.Counters.Done,
				a.Counters.Cancelled, a.Counters.Failed, a.Counters.TimeOut)
		case "details":
			actionPrintDetails(a)
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "foundsomething":
			err = searchFoundAnything(a, true, ctx)
			if err != nil {
				panic(err)
			}
		case "foundnothing":
			err = searchFoundAnything(a, false, ctx)
			if err != nil {
				panic(err)
			}
		case "help":
			fmt.Printf(`The following orders are available:
command <id>	jump to command reader mode for command <id>
copy		enter action launcher mode using current action as template
counters	display the counters of the action
exit		exit this mode
foundsomething	list commands and agents that have found something
foundnothing	list commands and agents that have found nothing
help		show this help
investigators   print the list of investigators that signed the action
json         	show the json of the action
ls <filter>	returns the list of commands with their status
		'filter' is a pipe separated string of filter:
		ex: ls | grep server1.(dom1|dom2) | grep -v example.net
details		display the details of the action, including status & times
r		refresh the action (get latest version from upstream)
times		show the various timestamps of the action
`)
		case "investigators":
			for _, i := range a.Investigators {
				fmt.Println(i.Name, "- Key ID:", i.PGPFingerprint)
			}
		case "json":
			var ajson []byte
			ajson, err = json.MarshalIndent(a, "", "  ")
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s\n", ajson)
		case "ls":
			err = actionPrintLinks(links, orders)
			if err != nil {
				panic(err)
			}
		case "r":
			a, links, err = getAction(aid, ctx)
			if err != nil {
				panic(err)
			}
			fmt.Println("Reload succeeded")
		case "results":
			err = actionPrintResults(a, links, orders)
			if err != nil {
				panic(err)
			}
		case "times":
			fmt.Printf("Valid from   '%s' until '%s'\nStarted on   '%s'\n"+
				"Last updated '%s'\nFinished on  '%s'\n",
				a.ValidFrom, a.ExpireAfter, a.StartTime, a.LastUpdateTime, a.FinishTime)
		case "":
			break
		default:
			fmt.Printf("Unknown order '%s'. You are in action reader mode. Try `help`.\n", orders[0])
		}
		readline.AddHistory(input)
	}
exit:
	fmt.Printf("\n")
	return
}
开发者ID:netantho,项目名称:mig,代码行数:101,代码来源:action_reader.go


示例20: manifestReader


//.........这里部分代码省略.........
		}
		orders := strings.Split(strings.TrimSpace(input), " ")
		switch orders[0] {
		case "disable":
			err = cli.ManifestRecordStatus(mr, "disabled")
			if err != nil {
				panic(err)
			}
			fmt.Println("Manifest record has been disabled")
		case "entry":
			mre, err := mr.ManifestResponse()
			if err != nil {
				panic(err)
			}
			buf, err := json.MarshalIndent(mre, "", "  ")
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s\n", buf)
		case "help":
			fmt.Printf(`The following orders are avialable:
disable         disables manifest and prevents future use

entry           show the manifest for this record as would be sent to a loader

help            show this help

exit            exit this mode (also works with ctrl+d)

json            show json of manifest record stored in database

loaders         show known loader entries that will match this manifest

r               refresh the manifest (get latest version from database)

reset           reset manifest status (marks manifest as staged, removes signatures)

sign            add a signature to the manifest record
`)
		case "exit":
			fmt.Printf("exit\n")
			goto exit
		case "json":
			tmpmr := mr
			if len(tmpmr.Content) > 0 {
				tmpmr.Content = "..."
			} else {
				tmpmr.Content = "None"
			}
			jsonmr, err := json.MarshalIndent(tmpmr, "", "  ")
			if err != nil {
				panic(err)
			}
			fmt.Printf("%s\n", jsonmr)
		case "loaders":
			ldrs, err := cli.GetManifestLoaders(mid)
			if err != nil {
				panic(err)
			}
			for _, x := range ldrs {
				buf, err := json.Marshal(x)
				if err != nil {
					panic(err)
				}
				fmt.Printf("%v\n", string(buf))
			}
		case "r":
			mr, err = cli.GetManifestRecord(mid)
			if err != nil {
				panic(err)
			}
			fmt.Println("reloaded")
		case "reset":
			err = cli.ManifestRecordStatus(mr, "staged")
			if err != nil {
				panic(err)
			}
			fmt.Println("Manifest record has been reset")
		case "sign":
			sig, err := cli.SignManifest(mr)
			if err != nil {
				panic(err)
			}
			err = cli.PostManifestSignature(mr, sig)
			if err != nil {
				panic(err)
			}
			fmt.Println("Manifest signature has been accepted")
		case "":
			break
		default:
			fmt.Printf("Unknown order '%s'. You are in manifest reader mode. Try `help`.\n", orders[0])
		}
		readline.AddHistory(input)
	}

exit:
	fmt.Printf("\n")
	return
}
开发者ID:saakaifoundry,项目名称:mig,代码行数:101,代码来源:manifest.go



注:本文中的github.com/bobappleyard/readline.AddHistory函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang readline.String函数代码示例发布时间:2022-05-24
下一篇:
Golang crash.Info类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap