Debian Codegraph @

cmd/gosh/main.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 // gosh is a proof of concept shell built on top of [interp].
5 package main
6
7 import (
8 "context"
9 "errors"
10 "flag"
11 "fmt"
12 "io"
13 "os"
14 "strings"
15
16 "golang.org/x/term"
17
18 "mvdan.cc/sh/v3/interp"
19 "mvdan.cc/sh/v3/syntax"
20 )
21
22 var command = flag.String("c", "", "command to be executed")
23
24 func main() {
25 flag.Parse()
26 err := runAll()
27 if es, ok := errors.AsType[interp.ExitStatus](err); ok {
28 os.Exit(int(es))
29 }
30 if err != nil {
31 fmt.Fprintln(os.Stderr, err)
32 os.Exit(1)
33 }
34 }
35
36 func runAll() error {
37 r, err := interp.New(interp.Interactive(true), interp.StdIO(os.Stdin, os.Stdout, os.Stderr))
38 if err != nil {
39 return err
40 }
41
42 // Note that -c '' is a no-op, so check whether the flag was set.
43 commandSet := false
44 flag.Visit(func(f *flag.Flag) {
45 if f.Name == "c" {
46 commandSet = true
47 }
48 })
49 if commandSet {
50 return run(r, strings.NewReader(*command), "")
51 }
52 if flag.NArg() == 0 {
53 if term.IsTerminal(int(os.Stdin.Fd())) {
54 return runInteractive(r, os.Stdin, os.Stdout, os.Stderr)
55 }
56 return run(r, os.Stdin, "")
57 }
58 for _, path := range flag.Args() {
59 if err := runPath(r, path); err != nil {
60 return err
61 }
62 }
63 return nil
64 }
65
66 func run(r *interp.Runner, reader io.Reader, name string) error {
67 prog, err := syntax.NewParser().Parse(reader, name)
68 if err != nil {
69 return err
70 }
71 r.Reset()
72 ctx := context.Background()
73 return r.Run(ctx, prog)
74 }
75
76 func runPath(r *interp.Runner, path string) error {
77 f, err := os.Open(path)
78 if err != nil {
79 return err
80 }
81 defer f.Close()
82 return run(r, f, path)
83 }
84
85 func runInteractive(r *interp.Runner, stdin io.Reader, stdout, stderr io.Writer) error {
86 parser := syntax.NewParser()
87 fmt.Fprintf(stdout, "$ ")
88 for stmts, err := range parser.InteractiveSeq(stdin) {
89 if err != nil {
90 return err // stop at the first error
91 }
92 if parser.Incomplete() {
93 fmt.Fprintf(stdout, "> ")
94 continue
95 }
96 ctx := context.Background()
97 for _, stmt := range stmts {
98 err := r.Run(ctx, stmt)
99 if r.Exited() {
100 return err
101 }
102 }
103 fmt.Fprintf(stdout, "$ ")
104 }
105 return nil
106 }