github.com/jd-ly/tools@v0.5.7/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/jd-ly/tools/internal/lsp/protocol" 13 "github.com/jd-ly/tools/internal/lsp/source" 14 "github.com/jd-ly/tools/internal/tool" 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 } 24 25 func (w *workspace) subCommands() []tool.Application { 26 return []tool.Application{ 27 &generateWorkspaceMod{app: w.app}, 28 } 29 } 30 31 func (w *workspace) Name() string { return "workspace" } 32 func (w *workspace) Usage() string { return "<subcommand> [args...]" } 33 func (w *workspace) ShortHelp() string { 34 return "manage the gopls workspace (experimental: under development)" 35 } 36 37 func (w *workspace) DetailedHelp(f *flag.FlagSet) { 38 fmt.Fprint(f.Output(), "\nsubcommands:\n") 39 for _, c := range w.subCommands() { 40 fmt.Fprintf(f.Output(), " %s: %s\n", c.Name(), c.ShortHelp()) 41 } 42 f.PrintDefaults() 43 } 44 45 func (w *workspace) Run(ctx context.Context, args ...string) error { 46 if len(args) == 0 { 47 return tool.CommandLineErrorf("must provide subcommand to %q", w.Name()) 48 } 49 command, args := args[0], args[1:] 50 for _, c := range w.subCommands() { 51 if c.Name() == command { 52 return tool.Run(ctx, c, args) 53 } 54 } 55 return tool.CommandLineErrorf("unknown command %v", command) 56 } 57 58 // generateWorkspaceMod (re)generates the gopls.mod file for the current 59 // workspace. 60 type generateWorkspaceMod struct { 61 app *Application 62 } 63 64 func (c *generateWorkspaceMod) Name() string { return "generate" } 65 func (c *generateWorkspaceMod) Usage() string { return "" } 66 func (c *generateWorkspaceMod) ShortHelp() string { 67 return "generate a gopls.mod file for a workspace" 68 } 69 70 func (c *generateWorkspaceMod) DetailedHelp(f *flag.FlagSet) { 71 f.PrintDefaults() 72 } 73 74 func (c *generateWorkspaceMod) Run(ctx context.Context, args ...string) error { 75 origOptions := c.app.options 76 c.app.options = func(opts *source.Options) { 77 origOptions(opts) 78 opts.ExperimentalWorkspaceModule = true 79 } 80 conn, err := c.app.connect(ctx) 81 if err != nil { 82 return err 83 } 84 defer conn.terminate(ctx) 85 params := &protocol.ExecuteCommandParams{Command: source.CommandGenerateGoplsMod.ID()} 86 if _, err := conn.ExecuteCommand(ctx, params); err != nil { 87 return fmt.Errorf("executing server command: %v", err) 88 } 89 return nil 90 }