github.com/v2fly/tools@v0.100.0/internal/lsp/cmd/workspace.go (about)

     1  // Copyright 2020 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 cmd
     6  
     7  import (
     8  	"context"
     9  	"flag"
    10  	"fmt"
    11  
    12  	"github.com/v2fly/tools/internal/lsp/command"
    13  	"github.com/v2fly/tools/internal/lsp/protocol"
    14  	"github.com/v2fly/tools/internal/lsp/source"
    15  )
    16  
    17  // workspace is a top-level command for working with the gopls workspace. This
    18  // is experimental and subject to change. The idea is that subcommands could be
    19  // used for manipulating the workspace mod file, rather than editing it
    20  // manually.
    21  type workspace struct {
    22  	subcommands
    23  }
    24  
    25  func newWorkspace(app *Application) *workspace {
    26  	return &workspace{
    27  		subcommands: subcommands{
    28  			&generateWorkspaceMod{app: app},
    29  		},
    30  	}
    31  }
    32  
    33  func (w *workspace) Name() string { return "workspace" }
    34  func (w *workspace) ShortHelp() string {
    35  	return "manage the gopls workspace (experimental: under development)"
    36  }
    37  
    38  // generateWorkspaceMod (re)generates the gopls.mod file for the current
    39  // workspace.
    40  type generateWorkspaceMod struct {
    41  	app *Application
    42  }
    43  
    44  func (c *generateWorkspaceMod) Name() string  { return "generate" }
    45  func (c *generateWorkspaceMod) Usage() string { return "" }
    46  func (c *generateWorkspaceMod) ShortHelp() string {
    47  	return "generate a gopls.mod file for a workspace"
    48  }
    49  
    50  func (c *generateWorkspaceMod) DetailedHelp(f *flag.FlagSet) {
    51  	f.PrintDefaults()
    52  }
    53  
    54  func (c *generateWorkspaceMod) Run(ctx context.Context, args ...string) error {
    55  	origOptions := c.app.options
    56  	c.app.options = func(opts *source.Options) {
    57  		origOptions(opts)
    58  		opts.ExperimentalWorkspaceModule = true
    59  	}
    60  	conn, err := c.app.connect(ctx)
    61  	if err != nil {
    62  		return err
    63  	}
    64  	defer conn.terminate(ctx)
    65  	cmd, err := command.NewGenerateGoplsModCommand("", command.URIArg{})
    66  	if err != nil {
    67  		return err
    68  	}
    69  	params := &protocol.ExecuteCommandParams{Command: cmd.Command, Arguments: cmd.Arguments}
    70  	if _, err := conn.ExecuteCommand(ctx, params); err != nil {
    71  		return fmt.Errorf("executing server command: %v", err)
    72  	}
    73  	return nil
    74  }