本文整理汇总了Golang中github.com/bobappleyard/readline.AddHistory函数的典型用法代码示例。如果您正苦于以下问题:Golang AddHistory函数的具体用法?Golang AddHistory怎么用?Golang AddHistory使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了AddHistory函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
}
}
示例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++
}
}
示例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")
}
示例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
}
示例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 <- ""
}
示例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
}
示例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
}
示例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)
}
}
}
示例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
}
示例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.
`)
}
示例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{}
}
}
}
}
示例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
}
示例13: addHistory
func addHistory(line string) {
readline.AddHistory(line)
}
示例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)
}
}
示例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
}