github.com/jhump/golang-x-tools@v0.0.0-20220218190644-4958d6d39439/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/jhump/golang-x-tools/internal/lsp/command"
    13  	"github.com/jhump/golang-x-tools/internal/lsp/protocol"
    14  	"github.com/jhump/golang-x-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  	app *Application
    23  	subcommands
    24  }
    25  
    26  func newWorkspace(app *Application) *workspace {
    27  	return &workspace{
    28  		app: app,
    29  		subcommands: subcommands{
    30  			&generateWorkspaceMod{app: app},
    31  		},
    32  	}
    33  }
    34  
    35  func (w *workspace) Name() string   { return "workspace" }
    36  func (w *workspace) Parent() string { return w.app.Name() }
    37  func (w *workspace) ShortHelp() string {
    38  	return "manage the gopls workspace (experimental: under development)"
    39  }
    40  
    41  // generateWorkspaceMod (re)generates the gopls.mod file for the current
    42  // workspace.
    43  type generateWorkspaceMod struct {
    44  	app *Application
    45  }
    46  
    47  func (c *generateWorkspaceMod) Name() string  { return "generate" }
    48  func (c *generateWorkspaceMod) Usage() string { return "" }
    49  func (c *generateWorkspaceMod) ShortHelp() string {
    50  	return "generate a gopls.mod file for a workspace"
    51  }
    52  
    53  func (c *generateWorkspaceMod) DetailedHelp(f *flag.FlagSet) {
    54  	printFlagDefaults(f)
    55  }
    56  
    57  func (c *generateWorkspaceMod) Run(ctx context.Context, args ...string) error {
    58  	origOptions := c.app.options
    59  	c.app.options = func(opts *source.Options) {
    60  		origOptions(opts)
    61  		opts.ExperimentalWorkspaceModule = true
    62  	}
    63  	conn, err := c.app.connect(ctx)
    64  	if err != nil {
    65  		return err
    66  	}
    67  	defer conn.terminate(ctx)
    68  	cmd, err := command.NewGenerateGoplsModCommand("", command.URIArg{})
    69  	if err != nil {
    70  		return err
    71  	}
    72  	params := &protocol.ExecuteCommandParams{Command: cmd.Command, Arguments: cmd.Arguments}
    73  	if _, err := conn.ExecuteCommand(ctx, params); err != nil {
    74  		return fmt.Errorf("executing server command: %v", err)
    75  	}
    76  	return nil
    77  }