-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
67 lines (56 loc) · 1.43 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"context"
"fmt"
"os"
"sort"
"strings"
"github.com/carlverge/jsonnet-lsp/pkg/lsp"
)
type cmd struct {
Fn func(args []string) error
Help string
}
var subcommands = map[string]cmd{
"lsp": {Fn: doLSP, Help: "Run the jsonnet language server. Uses stdin/stdout for communication."},
}
func fmtUsage(cmds map[string]cmd) string {
names := []string{}
for n := range cmds {
names = append(names, n)
}
sort.Strings(names)
res := strings.Builder{}
res.WriteString("usage:\n")
res.WriteString(" help - show this help message\n")
for _, n := range names {
res.WriteString(fmt.Sprintf(" %s - %s\n", n, cmds[n].Help))
}
return res.String()
}
func dispatch(args []string, cmds map[string]cmd) error {
if len(args) == 0 || args[0] == "help" || args[0] == "--help" || args[0] == "-h" {
os.Stdout.WriteString(fmtUsage(cmds))
return nil
}
sub, ok := cmds[args[0]]
if !ok {
return fmt.Errorf("unknown subcommand %s", args[0])
}
return sub.Fn(args[1:])
}
func doLSP(args []string) error {
// swap out process-level stdout right away to ensure that nothing else writes to it
// otherwise it will desync the jsonrpc stream
oldout := os.Stdout
os.Stdout = os.Stderr
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
return lsp.RunServer(ctx, oldout)
}
func main() {
if err := dispatch(os.Args[1:], subcommands); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}