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