// NewICli creates a new ICli object and initializes it. func NewICli(name, prompt, version, history, desc string) (*ICli, error) { // Initialize the clif interfaces //clif.DefaultStyles = clif.SunburnStyles icli := &ICli{ Cli: clif.New(name, version, desc), term: liner.NewLiner(), prompt: prompt, history: history, optionSet: make(map[string]string), } f, err := os.Open(history) if err != nil { f, err = os.Create(history) if err != nil { return nil, fmt.Errorf("could not open or create history file %s :: %v", history, err) } } defer f.Close() _, err = icli.term.ReadHistory(f) if err != nil { return nil, fmt.Errorf("could not read history file %s :: %v", history, err) } // set ctrl-c to abort the input. icli.term.SetCtrlCAborts(true) return icli, nil }
func NewShell() *Shell { sh := &Shell{ shell: liner.NewLiner(), prompt: "mbus> ", hist: filepath.Join(".", ".fcs_lpc_motor_history"), motor: m702.New("134.158.125.223:502"), } sh.shell.SetCtrlCAborts(true) sh.shell.SetCompleter(func(line string) (c []string) { for n := range sh.cmds { if strings.HasPrefix(n, strings.ToLower(line)) { c = append(c, n) } } return }) if f, err := os.Open(sh.hist); err == nil { sh.shell.ReadHistory(f) f.Close() } sh.cmds = map[string]shellCmd{ "dump": sh.cmdDump, "get": sh.cmdGet, "motor": sh.cmdMotor, "quit": sh.cmdQuit, "set": sh.cmdSet, } return sh }
func New(args []string) *cli { if len(args) > 1 { return nil } // We assume the terminal starts in cooked mode. cooked, _ = liner.TerminalMode() if cooked == nil { return nil } i := &cli{liner.NewLiner()} if history_path, err := task.GetHistoryFilePath(); err == nil { if f, err := os.Open(history_path); err == nil { i.ReadHistory(f) f.Close() } } uncooked, _ = liner.TerminalMode() i.SetCtrlCAborts(true) i.SetTabCompletionStyle(liner.TabPrints) i.SetWordCompleter(complete) return i }
// NewCLI create CLI from Config. func NewCLI(conf *Config) (*CLI, error) { origin := "http://127.0.0.1" if conf.Origin != "" { origin = conf.Origin } conn, err := websocket.Dial(conf.URL, "", origin) if err != nil { return nil, err } template := EmptyTemplate if _, err := os.Stat(conf.Template); err == nil { template, err = NewTemplateFile(conf.Template) if err != nil { return nil, err } } cli := &CLI{ conn, liner.NewLiner(), template, conf.Debug, } cli.liner.SetCtrlCAborts(true) cli.liner.SetCompleter(Completer(template)) return cli, nil }
func terminal(path string) (*liner.State, error) { term := liner.NewLiner() go func() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) <-c err := persist(term, history) if err != nil { fmt.Fprintf(os.Stderr, "failed to properly clean up terminal: %v\n", err) os.Exit(1) } os.Exit(0) }() f, err := os.Open(path) if err != nil { return term, err } defer f.Close() _, err = term.ReadHistory(f) return term, err }
func main() { flag.Parse() line := liner.NewLiner() line.SetCtrlCAborts(true) defer line.Close() for { cmd, err := line.Prompt("> ") if err == liner.ErrPromptAborted || err == io.EOF { break } else if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } args := shlex.Parse(cmd) switch strings.ToLower(args[0]) { case "search": if err := search(args[1:]); err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) } case "magnet": if err := magnet(args[1:]); err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) } } } }
func TestParseCommand_HistoryWithBlankCommand(t *testing.T) { t.Parallel() c := cli.CommandLine{Line: liner.NewLiner()} defer c.Line.Close() // append one entry to history c.Line.AppendHistory("x") tests := []struct { cmd string }{ {cmd: "history"}, {cmd: " history"}, {cmd: "history "}, {cmd: "History "}, {cmd: ""}, // shouldn't be persisted in history {cmd: " "}, // shouldn't be persisted in history } // don't validate because blank commands are never executed for _, test := range tests { c.ParseCommand(test.cmd) } // buf shall not contain empty commands var buf bytes.Buffer c.Line.WriteHistory(&buf) scanner := bufio.NewScanner(&buf) for scanner.Scan() { if scanner.Text() == "" || scanner.Text() == " " { t.Fatal("Empty commands should not be persisted in history.") } } }
func PromptConfirm(prompt string) (bool, error) { var ( input string err error ) prompt = prompt + " [y/N] " if liner.TerminalSupported() { lr := liner.NewLiner() defer lr.Close() input, err = lr.Prompt(prompt) } else { fmt.Print(prompt) input, err = bufio.NewReader(os.Stdin).ReadString('\n') fmt.Println() } if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" { return true, nil } else { return false, nil } return false, err }
func TestParseCommand_History(t *testing.T) { t.Parallel() c := cli.CommandLine{Line: liner.NewLiner()} defer c.Line.Close() // append one entry to history c.Line.AppendHistory("abc") tests := []struct { cmd string }{ {cmd: "history"}, {cmd: " history"}, {cmd: "history "}, {cmd: "History "}, } for _, test := range tests { if err := c.ParseCommand(test.cmd); err != nil { t.Fatalf(`Got error %v for command %q, expected nil.`, err, test.cmd) } } // buf size should be at least 1 var buf bytes.Buffer c.Line.WriteHistory(&buf) if buf.Len() < 1 { t.Fatal("History is borked") } }
func New(client service.Client) *Term { return &Term{ prompt: "(dlv) ", line: liner.NewLiner(), client: client, } }
func RunRepl(store *Secstore) { var sections []string var line string var err error liner := liner.NewLiner() defer liner.Close() liner.SetCompleter(completer) for { line, err = liner.Prompt("> ") if err != nil { break } liner.AppendHistory(line) sections = splitSections(line) if len(sections) == 0 { } else if strings.HasPrefix("quit", sections[0]) { break } else { err = EvalCommand(store, sections) if err != nil { fmt.Fprintln(os.Stderr, err) } } } fmt.Fprintln(os.Stderr, "Exiting...") }
func commandLoop() error { in := liner.NewLiner() defer in.Close() in.SetCtrlCAborts(true) f := NewForther() in.SetCompleter(f.Complete) for { line, err := in.Prompt(f.Prompt()) if err == io.EOF || err == liner.ErrPromptAborted { return nil } else if err != nil { return err } in.AppendHistory(line) for i, cmd := range strings.Fields(line) { if err := f.Process(cmd); err == io.EOF { return nil } else if err != nil { fmt.Printf("Cannot run op %d (%q): %v\n", i+1, cmd, err) break } } } }
func runTerm(cmd *cobra.Command, args []string) { if len(args) != 0 { cmd.Usage() return } db := makeSQLClient() liner := liner.NewLiner() defer func() { _ = liner.Close() }() for { l, err := liner.Prompt("> ") if err != nil { if err != io.EOF { fmt.Fprintf(os.Stderr, "Input error: %s\n", err) } break } if len(l) == 0 { continue } liner.AppendHistory(l) if err := processOneLine(db, l); err != nil { fmt.Printf("Error: %s\n", err) } } }
func uiLoop() { line := liner.NewLiner() line.SetCtrlCAborts(true) fmt.Print("\n\nFlow v0.1.0\n\nPress Ctrl+C to exit\n\n") for { if input, err := line.Prompt("flow> "); err == nil { inputs := strings.SplitN(input, " ", 2) if len(inputs) > 1 { cmd := inputs[0] args := inputs[1] checkCmd(cmd, args) } else { checkCmd(input, "") } } else if err == liner.ErrPromptAborted { break } else { log.Printf("error de terminal: %s\n", err.Error()) } } line.Close() out <- Event{ Type: UserExit, Data: nil, } }
func newLightweightJSRE(libPath string, client comms.EthereumClient, interactive bool) *jsre { js := &jsre{ps1: "> "} js.wait = make(chan *big.Int) js.client = client js.ds = docserver.New("/") // update state in separare forever blocks js.re = re.New(libPath) if err := js.apiBindings(js); err != nil { utils.Fatalf("Unable to initialize console - %v", err) } if !liner.TerminalSupported() || !interactive { js.prompter = dumbterm{bufio.NewReader(os.Stdin)} } else { lr := liner.NewLiner() js.withHistory(func(hist *os.File) { lr.ReadHistory(hist) }) lr.SetCtrlCAborts(true) js.loadAutoCompletion() lr.SetWordCompleter(apiWordCompleter) lr.SetTabCompletionStyle(liner.TabPrints) js.prompter = lr js.atexit = func() { js.withHistory(func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) }) lr.Close() close(js.wait) } } return js }
// Initialise the shell func (sh *Shell) Init(editorName string) error { // create directory dir := path.Join(os.TempDir(), "bshell") if _, err := os.Stat(dir); err != nil { if err = os.Mkdir(dir, 0777); err != nil { return err } } // create files sh.editorFileBQL = path.Join(dir, "bql_editor.txt") if err := sh.touchFile(sh.editorFileBQL); err != nil { return err } sh.editorFileJS = path.Join(dir, "js_editor.js") if err := sh.touchFile(sh.editorFileJS); err != nil { return err } sh.historyFile = path.Join(dir, "history") if err := sh.touchFile(sh.historyFile); err != nil { return err } // create shell sh.line = liner.NewLiner() // setup history if f, err := os.Open(sh.historyFile); err == nil { sh.line.ReadHistory(f) f.Close() } // set editor sh.editorName = editorName return nil }
func New(client service.Client, conf *config.Config) *Term { return &Term{ prompt: "(dlv) ", line: liner.NewLiner(), client: client, conf: conf, } }
func main() { flag.Parse() common.SetupLogger() config := common.LoadConfig() cassandraConfig := cassandra.CassandraMetricMetadataConfig{ Hosts: config.MetricMetadataConfig.Hosts, Keyspace: config.MetricMetadataConfig.Keyspace, } apiInstance := common.NewMetricMetadataAPI(cassandraConfig) ruleset, err := util.LoadRules(config.MetricMetadataConfig.ConversionRulesPath) if err != nil { //Blah } graphite := util.RuleBasedGraphiteConverter{Ruleset: ruleset} config.Blueflood.GraphiteMetricConverter = &graphite blueflood := blueflood.NewBlueflood(config.Blueflood) l := liner.NewLiner() defer l.Close() for { input, err := l.Prompt("> ") if err != nil { return } l.AppendHistory(input) cmd, err := query.Parse(input) if err != nil { fmt.Println("parsing error", err.Error()) continue } n, ok := cmd.(query.Node) if !ok { fmt.Printf("error: %#v doesn't implement Node\n", cmd) continue } fmt.Println(query.PrintNode(n)) result, err := cmd.Execute(query.ExecutionContext{TimeseriesStorageAPI: blueflood, MetricMetadataAPI: apiInstance, FetchLimit: 1000}) if err != nil { fmt.Println("execution error:", err.Error()) continue } encoded, err := json.MarshalIndent(result, "", " ") if err != nil { fmt.Println("encoding error:", err.Error()) return } fmt.Println("success:") fmt.Println(string(encoded)) } }
// New returns a new Term. func New(client service.Client, conf *config.Config) *Term { return &Term{ prompt: "(dlv) ", line: liner.NewLiner(), client: client, conf: conf, dumb: strings.ToLower(os.Getenv("TERM")) == "dumb", } }
func main() { flag.Parse() line := liner.NewLiner() defer line.Close() line.SetCtrlCAborts(true) line.SetCompleter(lineCompleter) if f, err := os.Open(historyf); err == nil { line.ReadHistory(f) f.Close() } client := Client{ vdirect: *vdirect, gdirect: *gdirect, gmode: *groupmode, } sm := "value" if client.gmode { sm = "group" } fmt.Printf("\u2728 oort-cli - in %s mode \u2728\n\n", sm) for { if cmd, err := line.Prompt(prompt); err == nil { if client.gmode { res, err := client.parseGroupCmd(cmd) if err != nil { fmt.Println(err.Error()) return } fmt.Println(res) line.AppendHistory(cmd) } else { res, err := client.parseValueCmd(cmd) if err != nil { fmt.Println(err.Error()) return } fmt.Println(res) line.AppendHistory(cmd) } } else if err == liner.ErrPromptAborted { log.Print("Aborted") return } else { log.Print("Error reading line: ", err) return } if f, err := os.Create(historyf); err != nil { log.Print("Error writing history file: ", err) } else { line.WriteHistory(f) f.Close() } } }
func main() { rand.Seed(time.Now().UnixNano()) line := liner.NewLiner() defer line.Close() line.SetCtrlCAborts(true) for { str, err := line.Prompt("> ") if err == liner.ErrPromptAborted { break } else if err != nil { fmt.Fprintln(os.Stderr, err) break } else if str == "" { continue } submatch := diceRegexp.FindStringSubmatch(str) if submatch == nil { fmt.Fprintln(os.Stderr, "invalid syntax.") continue } dice, err := strconv.ParseInt(submatch[1], 10, 0) if err != nil { fmt.Fprintln(os.Stderr, err) continue } sides, err := strconv.ParseInt(submatch[2], 10, 0) if err != nil { fmt.Fprintln(os.Stderr, err) continue } var total int64 if submatch[3] != "" { bonus, err := strconv.ParseInt(submatch[5], 10, 0) if err != nil { fmt.Fprintln(os.Stderr, err) continue } if submatch[4] == "+" { total += bonus } else { total -= bonus } } for i := 0; i < int(dice); i++ { total += int64(rand.Intn(int(sides)) + 1) } fmt.Println(total) line.AppendHistory(str) } }
func initTerm() { getShellState().term = liner.NewLiner() c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt) go func() { <-c closeTerm() fmt.Println("Exiting shed") os.Exit(1) }() }
func main() { if len(os.Args) < 2 { usage(0) } srvs := map[string]int{} if len(os.Args) > 2 { // Parse service:port pairs for _, s := range os.Args[2:] { parts := strings.Split(s, ":") if len(parts) != 2 { usage(1) } if port, err := strconv.Atoi(parts[1]); err != nil { usage(2) } else { srvs[parts[0]] = port } } } line := liner.NewLiner() defer line.Close() line.SetCtrlCAborts(true) // Start new mDNS instance m, err := mdns.NewMDNS(os.Args[1], srvs) if err != nil { log.Fatal(err) } // Read discovery/resolve requests in a loop until Ctrl+C is pressed for { if s, err := line.Prompt("> "); err == nil { line.AppendHistory(s) if len(s) > 0 { if s[0] == '_' { log.Println(m.Browse(s, true)) } else { log.Println(m.Resolve(s)) } } } else if err == liner.ErrPromptAborted { break } else { log.Fatal(err) } } m.Shutdown() }
func (x *cmdConsole) initConsole() error { // FIXME: add history (ReadHistory/WriteHistory) x.extraCommands = []consoleCommand{ {"help", x.doHelp}, {"shell", x.doShell}, } x.repl = liner.NewLiner() x.repl.SetCompleter(x.snappyCompleter) return nil }
// start a REPL shell. func (c *impl) CmdLine() { log.Log.Println("cfmedias", c.currentVersion) c.repl = liner.NewLiner() c.repl.SetCompleter(c.completer) for c.replActive = true; c.replActive; { c.reading = true cmd, err := c.repl.Prompt("> ") //c.repl.Close() c.reading = false if err != nil && c.replActive { fmt.Println(err) c.replActive = false break } if !c.replActive { return } cmd = strings.Replace(cmd, `\ `, maxUnicodeString, -1) cmd = strings.Replace(cmd, `\\`, `\`, -1) split := strings.Split(cmd, " ") if len(split) > 0 && len(cmd) > 0 { // convert arg list to map, using format // name=max fruits=apple fruits=orange // ==> map[name: [max], fruits: [apple, orange]] args := make(core.ArgMap) for _, e := range split[1:] { e = strings.Replace(e, maxUnicodeString, ` `, -1) tuple := strings.Split(e, "=") if _, ok := args[tuple[0]]; !ok { args[tuple[0]] = make([]string, 0) } if len(tuple) > 0 { args[tuple[0]] = append(args[tuple[0]], strings.Join(tuple[1:], "=")) } } result := c.Cmd(core.CommandContext{split[0], args, core.AuthRoot, nil}) if result.Error != core.ErrorCmdNotFound { c.repl.AppendHistory(cmd) } bytes, _ := json.MarshalIndent(result, "", " ") os.Stdout.Write(bytes) fmt.Println() } } }
func readPassword(prompt string, warnTerm bool) (string, error) { if liner.TerminalSupported() { lr := liner.NewLiner() defer lr.Close() return lr.PasswordPrompt(prompt) } if warnTerm { fmt.Println("!! Unsupported terminal, password will be echoed.") } fmt.Print(prompt) input, err := bufio.NewReader(os.Stdin).ReadString('\n') fmt.Println() return input, err }
// Собирает данные для отправки из stdin func (c wscon) textIn() { line := liner.NewLiner() defer func() { line.Close() if f, err := os.Create(history); err != nil { log.Error("Error writing history file: ", err) } else { line.WriteHistory(f) f.Close() } }() if f, err := os.Open(history); err == nil { line.ReadHistory(f) f.Close() } for { if text, err := line.Prompt(fmt.Sprintf("%s%s >> ", bindURL.Host, bindURL.Path)); err != nil { log.Print("Error reading line: ", err) } else { cmdline := strings.TrimSpace(text) if len(cmdline) == 0 { continue } switch cmdline[0] { case '!': // get output from external cmd cmd := exec.Command("bash", "-c", cmdline[1:]) if extout, err := cmd.Output(); err != nil { log.Errorf("External command %s failed", cmd) continue } else { text = string(extout) } case '<': // load from file if data, err := ioutil.ReadFile(cmdline[1:]); err != nil { log.Errorf("can't load file %s", cmdline[1:]) continue } else { text = string(data) } } c.TextIn <- bytes.NewBufferString(text) stamp = time.Now() line.AppendHistory(text) } } }
func main() { c := cli{} fs := flag.NewFlagSet("default", flag.ExitOnError) fs.StringVar(&c.host, "host", "localhost", "influxdb host to connect to") fs.IntVar(&c.port, "port", 8086, "influxdb port to connect to") fs.StringVar(&c.username, "username", c.username, "username to connect to the server. can be blank if authorization is not required") fs.StringVar(&c.password, "password", c.password, "password to connect to the server. can be blank if authorization is not required") fs.StringVar(&c.database, "database", c.database, "database to connect to the server.") fs.Parse(os.Args[1:]) // TODO Determine if we are an ineractive shell or running commands fmt.Println("InfluxDB shell") c.connect("") line := liner.NewLiner() defer line.Close() var historyFile string usr, err := user.Current() // Only load history if we can get the user if err == nil { historyFile = filepath.Join(usr.HomeDir, ".influx_history") if f, err := os.Open(historyFile); err == nil { line.ReadHistory(f) f.Close() } } for { l, e := line.Prompt("> ") if e != nil { break } if !c.parseCommand(l) { // write out the history if f, err := os.Create(historyFile); err == nil { line.WriteHistory(f) f.Close() } break } line.AppendHistory(l) } }
func main() { flag.Parse() common.SetupLogger() config := common.LoadConfig() apiInstance := common.NewAPI(config.API) myBackend := blueflood.NewBlueflood(config.Blueflood) l := liner.NewLiner() defer l.Close() for { input, err := l.Prompt("> ") if err != nil { return } l.AppendHistory(input) cmd, err := query.Parse(input) if err != nil { fmt.Println("parsing error", err.Error()) continue } n, ok := cmd.(query.Node) if !ok { fmt.Printf("error: %#v doesn't implement Node\n", cmd) continue } fmt.Println(query.PrintNode(n)) result, err := cmd.Execute(query.ExecutionContext{Backend: backend.NewSequentialMultiBackend(myBackend), API: apiInstance, FetchLimit: 1000}) if err != nil { fmt.Println("execution error:", err.Error()) continue } encoded, err := json.MarshalIndent(result, "", " ") if err != nil { fmt.Println("encoding error:", err.Error()) return } fmt.Println("success:") fmt.Println(string(encoded)) } }
func main() { state := liner.NewLiner() defer state.Close() for { cmd, err := state.Prompt(defaultPrompt) if err != nil { fmt.Println(err) break } state.AppendHistory(cmd) result, err := query.Parse(cmd + "\n") if err == nil { iterator := result.Iterator reducerOp := "" for _, op := range result.Ops { switch op.Name { case "take": iterator = iterator.Take(op.Args[0].(uint)) case "drop": iterator = iterator.Drop(op.Args[0].(uint)) case "reverse": iterator = iterator.Reverse() case "length", "max", "min", "last": reducerOp = op.Name break } } switch reducerOp { case "length": fmt.Println(iterator.Length()) case "max": fmt.Println(iterator.Max()) case "min": fmt.Println(iterator.Min()) case "last": fmt.Println(iterator.Last()) default: fmt.Println(iterator) } } else { fmt.Println(err) } } }