on master help sign in
prybar/utils/utils.go
81 lines 1.9 kB history raw
1package utils
3import (
4 "flag"
5 "fmt"
6 "os"
7 "runtime"
8)
10type Config struct {
11 Code string
12 Quiet bool
13 Exp string
14 Ps1, Ps2 string
15 Args []string
16 Interactive, OurInteractive bool
19func ParseFlags() *Config {
20 config := &Config{}
22 flag.StringVar(&config.Code, "c", "", "execute without printing result")
23 flag.StringVar(&config.Exp, "e", "", "evaluate and print result")
25 flag.StringVar(&config.Ps1, "ps1", "--> ", "repl prompt")
26 flag.StringVar(&config.Ps2, "ps2", "... ", "repl continuation prompt")
28 flag.BoolVar(&config.Interactive, "i", false, "interactive (use language repl)")
29 flag.BoolVar(&config.OurInteractive, "I", false, "interactive (use readline repl)")
30 flag.BoolVar(&config.Quiet, "q", false, "don't print language version")
32 flag.Usage = func() {
33 fmt.Fprintf(os.Stderr, "Usage: %s [FLAGS] [FILENAME]...\n", os.Args[0])
34 flag.PrintDefaults()
35 }
37 flag.Parse()
39 config.Args = flag.Args()
40 return config
43func DoCli(p PluginBase) {
45 config := ParseFlags()
47 runtime.LockOSThread()
48 p.Open()
49 lang := &Language{ptr: p, ps1: config.Ps1}
51 if !config.Quiet {
52 fmt.Println(lang.Version())
53 }
55 if config.Code != "" {
56 lang.Eval(config.Code)
57 }
58 if config.Exp != "" {
59 lang.EvalAndTryToPrint(config.Exp)
60 }
62 if len(config.Args) > 0 {
63 if _, err := os.Stat(config.Args[0]); os.IsNotExist(err) {
64 fmt.Println("No such file:", config.Args[0])
65 os.Exit(2)
66 } else {
67 exitCode := lang.EvalFile(config.Args[0], config.Args[1:])
68 // TODO: Maybe log if exitCode is non-zero and interractive is true?
69 if exitCode != 0 && !config.Interactive && !config.OurInteractive {
70 os.Exit(exitCode)
71 }
72 }
73 }
75 if config.Interactive {
76 lang.SetPrompts(config.Ps1, config.Ps2)
77 lang.REPL()
78 } else if config.OurInteractive {
79 lang.InternalREPL()
80 }