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.
12 "golang.org/x/tools/internal/lsp/command"
13 "golang.org/x/tools/internal/lsp/protocol"
14 "golang.org/x/tools/internal/lsp/source"
15 "golang.org/x/tools/internal/tool"
18 // workspace is a top-level command for working with the gopls workspace. This
19 // is experimental and subject to change. The idea is that subcommands could be
20 // used for manipulating the workspace mod file, rather than editing it
22 type workspace struct {
26 func (w *workspace) subCommands() []tool.Application {
27 return []tool.Application{
28 &generateWorkspaceMod{app: w.app},
32 func (w *workspace) Name() string { return "workspace" }
33 func (w *workspace) Usage() string { return "<subcommand> [args...]" }
34 func (w *workspace) ShortHelp() string {
35 return "manage the gopls workspace (experimental: under development)"
38 func (w *workspace) DetailedHelp(f *flag.FlagSet) {
39 fmt.Fprint(f.Output(), "\nsubcommands:\n")
40 for _, c := range w.subCommands() {
41 fmt.Fprintf(f.Output(), " %s: %s\n", c.Name(), c.ShortHelp())
46 func (w *workspace) Run(ctx context.Context, args ...string) error {
48 return tool.CommandLineErrorf("must provide subcommand to %q", w.Name())
50 command, args := args[0], args[1:]
51 for _, c := range w.subCommands() {
52 if c.Name() == command {
53 return tool.Run(ctx, c, args)
56 return tool.CommandLineErrorf("unknown command %v", command)
59 // generateWorkspaceMod (re)generates the gopls.mod file for the current
61 type generateWorkspaceMod struct {
65 func (c *generateWorkspaceMod) Name() string { return "generate" }
66 func (c *generateWorkspaceMod) Usage() string { return "" }
67 func (c *generateWorkspaceMod) ShortHelp() string {
68 return "generate a gopls.mod file for a workspace"
71 func (c *generateWorkspaceMod) DetailedHelp(f *flag.FlagSet) {
75 func (c *generateWorkspaceMod) Run(ctx context.Context, args ...string) error {
76 origOptions := c.app.options
77 c.app.options = func(opts *source.Options) {
79 opts.ExperimentalWorkspaceModule = true
81 conn, err := c.app.connect(ctx)
85 defer conn.terminate(ctx)
86 cmd, err := command.NewGenerateGoplsModCommand("", command.URIArg{})
90 params := &protocol.ExecuteCommandParams{Command: cmd.Command, Arguments: cmd.Arguments}
91 if _, err := conn.ExecuteCommand(ctx, params); err != nil {
92 return fmt.Errorf("executing server command: %v", err)