github.com/AlpineAIO/wails/v2@v2.0.0-beta.32.0.20240505041856-1047a8fa5fef/internal/staticanalysis/staticanalysis.go (about)

     1  package staticanalysis
     2  
     3  import (
     4  	"go/ast"
     5  	"path/filepath"
     6  	"strings"
     7  
     8  	"golang.org/x/tools/go/packages"
     9  )
    10  
    11  type EmbedDetails struct {
    12  	BaseDir   string
    13  	EmbedPath string
    14  	All       bool
    15  }
    16  
    17  func (e *EmbedDetails) GetFullPath() string {
    18  	return filepath.Join(e.BaseDir, e.EmbedPath)
    19  }
    20  
    21  func GetEmbedDetails(sourcePath string) ([]*EmbedDetails, error) {
    22  	// read in project files and determine which directories are used for embedding
    23  	// return a list of directories
    24  
    25  	absPath, err := filepath.Abs(sourcePath)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	pkgs, err := packages.Load(&packages.Config{
    30  		Mode: packages.NeedName | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedCompiledGoFiles,
    31  		Dir:  absPath,
    32  	}, "./...")
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	var result []*EmbedDetails
    37  	for _, pkg := range pkgs {
    38  		for index, file := range pkg.Syntax {
    39  			baseDir := filepath.Dir(pkg.CompiledGoFiles[index])
    40  			embedPaths := GetEmbedDetailsForFile(file, baseDir)
    41  			if len(embedPaths) > 0 {
    42  				result = append(result, embedPaths...)
    43  			}
    44  		}
    45  	}
    46  	return result, nil
    47  }
    48  
    49  func GetEmbedDetailsForFile(file *ast.File, baseDir string) []*EmbedDetails {
    50  	var result []*EmbedDetails
    51  	for _, comment := range file.Comments {
    52  		for _, c := range comment.List {
    53  			if strings.HasPrefix(c.Text, "//go:embed") {
    54  				sl := strings.Split(c.Text, " ")
    55  				path := ""
    56  				all := false
    57  				if len(sl) == 1 {
    58  					continue
    59  				}
    60  				embedPath := strings.TrimSpace(sl[1])
    61  				switch true {
    62  				case strings.HasPrefix(embedPath, "all:"):
    63  					path = strings.TrimPrefix(embedPath, "all:")
    64  					all = true
    65  				default:
    66  					path = embedPath
    67  				}
    68  				result = append(result, &EmbedDetails{
    69  					EmbedPath: path,
    70  					All:       all,
    71  					BaseDir:   baseDir,
    72  				})
    73  			}
    74  		}
    75  	}
    76  	return result
    77  }