github.com/please-build/puku@v1.7.3-0.20240516143641-f7d7f4941f57/e2e/harness/harness.go (about)

     1  package harness
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"log"
     7  	"os"
     8  	"path/filepath"
     9  
    10  	"github.com/please-build/buildtools/build"
    11  	exec "golang.org/x/sys/execabs"
    12  
    13  	"github.com/please-build/puku/config"
    14  )
    15  
    16  type TestHarness struct {
    17  	Puku     string
    18  	Please   string
    19  	RepoRoot string
    20  }
    21  
    22  func MustNew() *TestHarness {
    23  	readEnvAbs := func(envVar string) string {
    24  		v, ok := os.LookupEnv(envVar)
    25  		if !ok {
    26  			log.Fatalf("$%v not set", envVar)
    27  		}
    28  		v, err := filepath.Abs(v)
    29  		if err != nil {
    30  			log.Fatalf("%v", err)
    31  		}
    32  		return v
    33  	}
    34  
    35  	puku := readEnvAbs("DATA_PUKU")
    36  	please := readEnvAbs("DATA_PLEASE")
    37  	repo := readEnvAbs("DATA_REPO")
    38  
    39  	conf := config.Config{
    40  		PleasePath: please,
    41  	}
    42  	bs, err := json.Marshal(conf)
    43  	if err != nil {
    44  		log.Fatalf("failed to write puku.json: %v", err)
    45  	}
    46  
    47  	if err := os.WriteFile(filepath.Join(repo, "puku.json"), bs, 0644); err != nil {
    48  		log.Fatalf("failed to write puku.json: %v", err)
    49  	}
    50  
    51  	return &TestHarness{
    52  		Puku:     puku,
    53  		Please:   please,
    54  		RepoRoot: repo,
    55  	}
    56  }
    57  
    58  func (h *TestHarness) Format(paths ...string) error {
    59  	cmd := exec.Command(h.Puku, append([]string{"fmt"}, paths...)...)
    60  	cmd.Dir = h.RepoRoot
    61  	out, err := cmd.CombinedOutput()
    62  	if err != nil {
    63  		return fmt.Errorf("failed to run puku fmt %v: %v:\n%v", paths, err, string(out))
    64  	}
    65  	return nil
    66  }
    67  
    68  func (h *TestHarness) ParseFile(path string) (*build.File, error) {
    69  	absPath := filepath.Join(h.RepoRoot, path)
    70  	file, err := os.ReadFile(absPath)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  	return build.Parse(path, file)
    75  }