golang.org/x/exp@v0.0.0-20240506185415-9bf2ced13842/trace/internal/testtrace/format.go (about)

     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  // Code generated by "gen.bash" from internal/trace/v2; DO NOT EDIT.
     6  
     7  //go:build go1.21
     8  
     9  package testtrace
    10  
    11  import (
    12  	"bytes"
    13  	"fmt"
    14  	"golang.org/x/exp/trace/internal/raw"
    15  	"golang.org/x/tools/txtar"
    16  	"io"
    17  )
    18  
    19  // ParseFile parses a test file generated by the testgen package.
    20  func ParseFile(testPath string) (io.Reader, *Expectation, error) {
    21  	ar, err := txtar.ParseFile(testPath)
    22  	if err != nil {
    23  		return nil, nil, fmt.Errorf("failed to read test file for %s: %v", testPath, err)
    24  	}
    25  	if len(ar.Files) != 2 {
    26  		return nil, nil, fmt.Errorf("malformed test %s: wrong number of files", testPath)
    27  	}
    28  	if ar.Files[0].Name != "expect" {
    29  		return nil, nil, fmt.Errorf("malformed test %s: bad filename %s", testPath, ar.Files[0].Name)
    30  	}
    31  	if ar.Files[1].Name != "trace" {
    32  		return nil, nil, fmt.Errorf("malformed test %s: bad filename %s", testPath, ar.Files[1].Name)
    33  	}
    34  	tr, err := raw.NewTextReader(bytes.NewReader(ar.Files[1].Data))
    35  	if err != nil {
    36  		return nil, nil, fmt.Errorf("malformed test %s: bad trace file: %v", testPath, err)
    37  	}
    38  	var buf bytes.Buffer
    39  	tw, err := raw.NewWriter(&buf, tr.Version())
    40  	if err != nil {
    41  		return nil, nil, fmt.Errorf("failed to create trace byte writer: %v", err)
    42  	}
    43  	for {
    44  		ev, err := tr.ReadEvent()
    45  		if err == io.EOF {
    46  			break
    47  		}
    48  		if err != nil {
    49  			return nil, nil, fmt.Errorf("malformed test %s: bad trace file: %v", testPath, err)
    50  		}
    51  		if err := tw.WriteEvent(ev); err != nil {
    52  			return nil, nil, fmt.Errorf("internal error during %s: failed to write trace bytes: %v", testPath, err)
    53  		}
    54  	}
    55  	exp, err := ParseExpectation(ar.Files[0].Data)
    56  	if err != nil {
    57  		return nil, nil, fmt.Errorf("internal error during %s: failed to parse expectation %q: %v", testPath, string(ar.Files[0].Data), err)
    58  	}
    59  	return &buf, exp, nil
    60  }