Debian Codegraph @

gopls/internal/protocol/command/util.go

raw symbols SCIP
1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package command
6
7 import (
8 "encoding/json"
9 "fmt"
10 )
11
12 // A Command identifies one of gopls' ad-hoc extension commands
13 // that may be invoked through LSP's executeCommand.
14 type Command string
15
16 func (c Command) String() string { return string(c) }
17
18 // MarshalArgs encodes the given arguments to json.RawMessages. This function
19 // is used to construct arguments to a protocol.Command.
20 //
21 // Example usage:
22 //
23 // jsonArgs, err := MarshalArgs(1, "hello", true, StructuredArg{42, 12.6})
24 func MarshalArgs(args ...any) ([]json.RawMessage, error) {
25 var out []json.RawMessage
26 for _, arg := range args {
27 argJSON, err := json.Marshal(arg)
28 if err != nil {
29 return nil, err
30 }
31 out = append(out, argJSON)
32 }
33 return out, nil
34 }
35
36 // MustMarshalArgs is like MarshalArgs, but panics on error.
37 func MustMarshalArgs(args ...any) []json.RawMessage {
38 msg, err := MarshalArgs(args...)
39 if err != nil {
40 panic(err)
41 }
42 return msg
43 }
44
45 // UnmarshalArgs decodes the given json.RawMessages to the variables provided
46 // by args. Each element of args should be a pointer.
47 //
48 // Example usage:
49 //
50 // var (
51 // num int
52 // str string
53 // bul bool
54 // structured StructuredArg
55 // )
56 // err := UnmarshalArgs(args, &num, &str, &bul, &structured)
57 func UnmarshalArgs(jsonArgs []json.RawMessage, args ...any) error {
58 if len(args) != len(jsonArgs) {
59 return fmt.Errorf("DecodeArgs: expected %d input arguments, got %d JSON arguments", len(args), len(jsonArgs))
60 }
61 for i, arg := range args {
62 if err := json.Unmarshal(jsonArgs[i], arg); err != nil {
63 return err
64 }
65 }
66 return nil
67 }