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

View as plain text