github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/gnovm/pkg/integration/coverage.go (about)

     1  package integration
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/rogpeppe/go-internal/testscript"
    10  )
    11  
    12  var coverageEnv struct {
    13  	coverdir string
    14  }
    15  
    16  func init() {
    17  	flag.StringVar(&coverageEnv.coverdir,
    18  		"txtarcoverdir", "", "write testscripts coverage intermediate files to this directory")
    19  }
    20  
    21  // ResolveCoverageDir attempts to resolve the coverage directory from the 'TXTARCOVERDIR'
    22  // environment variable first, and if not set, from the 'test.txtarcoverdir' flag.
    23  // It returns the resolved directory and a boolean indicating if the resolution was successful.
    24  func ResolveCoverageDir() (string, bool) {
    25  	// Attempt to resolve the cover directory from the environment variable or flag
    26  	coverdir := os.Getenv("TXTARCOVERDIR")
    27  	if coverdir == "" {
    28  		coverdir = coverageEnv.coverdir
    29  	}
    30  
    31  	return coverdir, coverdir != ""
    32  }
    33  
    34  // SetupTestscriptsCoverage sets up the given testscripts environment for coverage.
    35  // It will mostly override `GOCOVERDIR` with the target cover directory
    36  func SetupTestscriptsCoverage(p *testscript.Params, coverdir string) error {
    37  	// Check if the given coverage directory exist
    38  	info, err := os.Stat(coverdir)
    39  	if err != nil {
    40  		return fmt.Errorf("output directory %q inaccessible: %w", coverdir, err)
    41  	} else if !info.IsDir() {
    42  		return fmt.Errorf("output %q not a directory", coverdir)
    43  	}
    44  
    45  	// We need to have an absolute path here, because current directory
    46  	// context will change while executing testscripts.
    47  	if !filepath.IsAbs(coverdir) {
    48  		var err error
    49  		if coverdir, err = filepath.Abs(coverdir); err != nil {
    50  			return fmt.Errorf("unable to determine absolute path of %q: %w", coverdir, err)
    51  		}
    52  	}
    53  
    54  	// Backup the original setup function
    55  	origSetup := p.Setup
    56  	p.Setup = func(env *testscript.Env) error {
    57  		if origSetup != nil {
    58  			// Call previous setup first
    59  			origSetup(env)
    60  		}
    61  
    62  		// Override `GOCOVEDIR` directory for sub-execution
    63  		env.Setenv("GOCOVERDIR", coverdir)
    64  		return nil
    65  	}
    66  
    67  	return nil
    68  }