github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/misc/goscan/goscan.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"flag"
     6  	"fmt"
     7  	"go/parser"
     8  	"go/token"
     9  	"os"
    10  
    11  	"github.com/davecgh/go-spew/spew"
    12  	"github.com/gnolang/gno/tm2/pkg/commands"
    13  )
    14  
    15  func main() {
    16  	cmd := commands.NewCommand(
    17  		commands.Metadata{
    18  			ShortUsage: "<file-path>",
    19  			LongHelp:   "Prints out the imports for a given file's AST",
    20  		},
    21  		commands.NewEmptyConfig(),
    22  		execScan,
    23  	)
    24  
    25  	cmd.Execute(context.Background(), os.Args[1:])
    26  }
    27  
    28  func execScan(_ context.Context, args []string) error {
    29  	if len(args) < 1 {
    30  		return flag.ErrHelp
    31  	}
    32  
    33  	fset := token.NewFileSet() // positions are relative to fset
    34  
    35  	filename := args[0]
    36  	bz, err := os.ReadFile(filename)
    37  	if err != nil {
    38  		return fmt.Errorf("unable to read file, %w", err)
    39  	}
    40  
    41  	// Parse src but stop after processing the imports.
    42  	f, err := parser.ParseFile(fset, "", string(bz), parser.ParseComments|parser.DeclarationErrors)
    43  	if err != nil {
    44  		return fmt.Errorf("unable to parse file, %w", err)
    45  	}
    46  
    47  	// Print the imports from the file's AST.
    48  	spew.Dump(f)
    49  
    50  	return nil
    51  }