github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/internal/lsp/cmd/check.go (about)

     1  // Copyright 2019 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/powerman/golang-tools/internal/span"
    13  	errors "golang.org/x/xerrors"
    14  )
    15  
    16  // check implements the check verb for gopls.
    17  type check struct {
    18  	app *Application
    19  }
    20  
    21  func (c *check) Name() string      { return "check" }
    22  func (c *check) Parent() string    { return c.app.Name() }
    23  func (c *check) Usage() string     { return "<filename>" }
    24  func (c *check) ShortHelp() string { return "show diagnostic results for the specified file" }
    25  func (c *check) DetailedHelp(f *flag.FlagSet) {
    26  	fmt.Fprint(f.Output(), `
    27  Example: show the diagnostic results of this file:
    28  
    29  	$ gopls check internal/lsp/cmd/check.go
    30  `)
    31  	printFlagDefaults(f)
    32  }
    33  
    34  // Run performs the check on the files specified by args and prints the
    35  // results to stdout.
    36  func (c *check) Run(ctx context.Context, args ...string) error {
    37  	if len(args) == 0 {
    38  		// no files, so no results
    39  		return nil
    40  	}
    41  	checking := map[span.URI]*cmdFile{}
    42  	var uris []span.URI
    43  	// now we ready to kick things off
    44  	conn, err := c.app.connect(ctx)
    45  	if err != nil {
    46  		return err
    47  	}
    48  	defer conn.terminate(ctx)
    49  	for _, arg := range args {
    50  		uri := span.URIFromPath(arg)
    51  		uris = append(uris, uri)
    52  		file := conn.AddFile(ctx, uri)
    53  		if file.err != nil {
    54  			return file.err
    55  		}
    56  		checking[uri] = file
    57  	}
    58  	if err := conn.diagnoseFiles(ctx, uris); err != nil {
    59  		return err
    60  	}
    61  	conn.Client.filesMu.Lock()
    62  	defer conn.Client.filesMu.Unlock()
    63  
    64  	for _, file := range checking {
    65  		for _, d := range file.diagnostics {
    66  			spn, err := file.mapper.RangeSpan(d.Range)
    67  			if err != nil {
    68  				return errors.Errorf("Could not convert position %v for %q", d.Range, d.Message)
    69  			}
    70  			fmt.Printf("%v: %v\n", spn, d.Message)
    71  		}
    72  	}
    73  	return nil
    74  }