golang.org/x/tools/gopls@v0.15.3/internal/protocol/command/util.go (about)

     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  // ID returns the command name for use in the LSP.
    13  func ID(name string) string {
    14  	return "gopls." + name
    15  }
    16  
    17  type Command string
    18  
    19  // ID returns the command identifier to use in the executeCommand request.
    20  func (c Command) ID() string {
    21  	return ID(string(c))
    22  }
    23  
    24  // MarshalArgs encodes the given arguments to json.RawMessages. This function
    25  // is used to construct arguments to a protocol.Command.
    26  //
    27  // Example usage:
    28  //
    29  //	jsonArgs, err := MarshalArgs(1, "hello", true, StructuredArg{42, 12.6})
    30  func 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  func UnmarshalArgs(jsonArgs []json.RawMessage, args ...interface{}) error {
    55  	if len(args) != len(jsonArgs) {
    56  		return fmt.Errorf("DecodeArgs: expected %d input arguments, got %d JSON arguments", len(args), len(jsonArgs))
    57  	}
    58  	for i, arg := range args {
    59  		if err := json.Unmarshal(jsonArgs[i], arg); err != nil {
    60  			return err
    61  		}
    62  	}
    63  	return nil
    64  }