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
5package command
6
7import (
8	"encoding/json"
9	"fmt"
10)
11
12// ID returns the command name for use in the LSP.
13func ID(name string) string {
14	return "gopls." + name
15}
16
17type Command string
18
19func (c Command) ID() string {
20	return ID(string(c))
21}
22
23// MarshalArgs encodes the given arguments to json.RawMessages. This function
24// is used to construct arguments to a protocol.Command.
25//
26// Example usage:
27//
28//   jsonArgs, err := EncodeArgs(1, "hello", true, StructuredArg{42, 12.6})
29//
30func MarshalArgs(args ...interface{}) ([]json.RawMessage, error) {
31	var out []json.RawMessage
32	for _, arg := range args {
33		argJSON, err := json.Marshal(arg)
34		if err != nil {
35			return nil, err
36		}
37		out = append(out, argJSON)
38	}
39	return out, nil
40}
41
42// UnmarshalArgs decodes the given json.RawMessages to the variables provided
43// by args. Each element of args should be a pointer.
44//
45// Example usage:
46//
47//   var (
48//       num int
49//       str string
50//       bul bool
51//       structured StructuredArg
52//   )
53//   err := UnmarshalArgs(args, &num, &str, &bul, &structured)
54//
55func UnmarshalArgs(jsonArgs []json.RawMessage, args ...interface{}) error {
56	if len(args) != len(jsonArgs) {
57		return fmt.Errorf("DecodeArgs: expected %d input arguments, got %d JSON arguments", len(args), len(jsonArgs))
58	}
59	for i, arg := range args {
60		if err := json.Unmarshal(jsonArgs[i], arg); err != nil {
61			return err
62		}
63	}
64	return nil
65}
66