Source file src/cmd/go/internal/work/cover.go

     1  // Copyright 2023 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  // Action graph execution methods related to coverage.
     6  
     7  package work
     8  
     9  import (
    10  	"cmd/go/internal/base"
    11  	"cmd/go/internal/cfg"
    12  	"cmd/go/internal/str"
    13  	"cmd/internal/cov/covcmd"
    14  	"context"
    15  	"encoding/json"
    16  	"fmt"
    17  	"internal/coverage"
    18  	"io"
    19  	"os"
    20  	"path/filepath"
    21  )
    22  
    23  // CovData invokes "go tool covdata" with the specified arguments
    24  // as part of the execution of action 'a'.
    25  func (b *Builder) CovData(a *Action, cmdargs ...any) ([]byte, error) {
    26  	cmdline := str.StringList(cmdargs...)
    27  	args := append([]string{}, cfg.BuildToolexec...)
    28  	args = append(args, base.Tool("covdata"))
    29  	args = append(args, cmdline...)
    30  	return b.Shell(a).runOut(a.Objdir, nil, args)
    31  }
    32  
    33  // BuildActionCoverMetaFile locates and returns the path of the
    34  // meta-data file written by the "go tool cover" step as part of the
    35  // build action for the "go test -cover" run action 'runAct'. Note
    36  // that if the package has no functions the meta-data file will exist
    37  // but will be empty; in this case the return is an empty string.
    38  func BuildActionCoverMetaFile(runAct *Action) (string, error) {
    39  	p := runAct.Package
    40  	for i := range runAct.Deps {
    41  		pred := runAct.Deps[i]
    42  		if pred.Mode != "build" || pred.Package == nil {
    43  			continue
    44  		}
    45  		if pred.Package.ImportPath == p.ImportPath {
    46  			metaFile := pred.Objdir + covcmd.MetaFileForPackage(p.ImportPath)
    47  			f, err := os.Open(metaFile)
    48  			if err != nil {
    49  				return "", err
    50  			}
    51  			defer f.Close()
    52  			fi, err2 := f.Stat()
    53  			if err2 != nil {
    54  				return "", err2
    55  			}
    56  			if fi.Size() == 0 {
    57  				return "", nil
    58  			}
    59  			return metaFile, nil
    60  		}
    61  	}
    62  	return "", fmt.Errorf("internal error: unable to locate build action for package %q run action", p.ImportPath)
    63  }
    64  
    65  // WriteCoveragePercent writes out to the writer 'w' a "percent
    66  // statements covered" for the package whose test-run action is
    67  // 'runAct', based on the meta-data file 'mf'. This helper is used in
    68  // cases where a user runs "go test -cover" on a package that has
    69  // functions but no tests; in the normal case (package has tests)
    70  // the percentage is written by the test binary when it runs.
    71  func WriteCoveragePercent(b *Builder, runAct *Action, mf string, w io.Writer) error {
    72  	dir := filepath.Dir(mf)
    73  	output, cerr := b.CovData(runAct, "percent", "-i", dir)
    74  	if cerr != nil {
    75  		return b.Shell(runAct).reportCmd("", "", output, cerr)
    76  	}
    77  	_, werr := w.Write(output)
    78  	return werr
    79  }
    80  
    81  // WriteCoverageProfile writes out a coverage profile fragment for the
    82  // package whose test-run action is 'runAct'; content is written to
    83  // the file 'outf' based on the coverage meta-data info found in
    84  // 'mf'. This helper is used in cases where a user runs "go test
    85  // -cover" on a package that has functions but no tests.
    86  func WriteCoverageProfile(b *Builder, runAct *Action, mf, outf string, w io.Writer) error {
    87  	dir := filepath.Dir(mf)
    88  	output, err := b.CovData(runAct, "textfmt", "-i", dir, "-o", outf)
    89  	if err != nil {
    90  		return b.Shell(runAct).reportCmd("", "", output, err)
    91  	}
    92  	_, werr := w.Write(output)
    93  	return werr
    94  }
    95  
    96  // WriteCoverMetaFilesFile writes out a summary file ("meta-files
    97  // file") as part of the action function for the "writeCoverMeta"
    98  // pseudo action employed during "go test -coverpkg" runs where there
    99  // are multiple tests and multiple packages covered. It builds up a
   100  // table mapping package import path to meta-data file fragment and
   101  // writes it out to a file where it can be read by the various test
   102  // run actions. Note that this function has to be called A) after the
   103  // build actions are complete for all packages being tested, and B)
   104  // before any of the "run test" actions for those packages happen.
   105  // This requirement is enforced by adding making this action ("a")
   106  // dependent on all test package build actions, and making all test
   107  // run actions dependent on this action.
   108  func WriteCoverMetaFilesFile(b *Builder, ctx context.Context, a *Action) error {
   109  	sh := b.Shell(a)
   110  
   111  	// Build the metafilecollection object.
   112  	var collection coverage.MetaFileCollection
   113  	for i := range a.Deps {
   114  		dep := a.Deps[i]
   115  		if dep.Mode != "build" {
   116  			panic("unexpected mode " + dep.Mode)
   117  		}
   118  		metaFilesFile := dep.Objdir + covcmd.MetaFileForPackage(dep.Package.ImportPath)
   119  		// Check to make sure the meta-data file fragment exists
   120  		//  and has content (may be empty if package has no functions).
   121  		if fi, err := os.Stat(metaFilesFile); err != nil {
   122  			continue
   123  		} else if fi.Size() == 0 {
   124  			continue
   125  		}
   126  		collection.ImportPaths = append(collection.ImportPaths, dep.Package.ImportPath)
   127  		collection.MetaFileFragments = append(collection.MetaFileFragments, metaFilesFile)
   128  	}
   129  
   130  	// Serialize it.
   131  	data, err := json.Marshal(collection)
   132  	if err != nil {
   133  		return fmt.Errorf("marshal MetaFileCollection: %v", err)
   134  	}
   135  	data = append(data, '\n') // makes -x output more readable
   136  
   137  	// Create the directory for this action's objdir and
   138  	// then write out the serialized collection
   139  	// to a file in the directory.
   140  	if err := sh.Mkdir(a.Objdir); err != nil {
   141  		return err
   142  	}
   143  	mfpath := a.Objdir + coverage.MetaFilesFileName
   144  	if err := sh.writeFile(mfpath, data); err != nil {
   145  		return fmt.Errorf("writing metafiles file: %v", err)
   146  	}
   147  
   148  	// We're done.
   149  	return nil
   150  }
   151  

View as plain text