Source file src/internal/trace/testtrace/helpers_test.go

     1  // Copyright 2025 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  package testtrace
     6  
     7  import (
     8  	"flag"
     9  	"fmt"
    10  	"internal/trace/raw"
    11  	"io"
    12  	"os"
    13  	"testing"
    14  )
    15  
    16  var (
    17  	convert = flag.String("convert", "", "Path to trace text file to convert to binary format")
    18  	output  = flag.String("out", "", "Output path for converted trace")
    19  )
    20  
    21  // TestConvertDump is not actually a test, it is a tool for converting trace
    22  // text dumps generated by Dump into the binary trace format. Set -convert and
    23  // -o to perform a converison.
    24  //
    25  //	go test internal/trace/testtrace -convert in.tracetxt -out out.trace
    26  //
    27  // This would be cleaner as a dedicated internal command rather than a test,
    28  // but cmd/dist does not handle internal (non-distributed) commands in std
    29  // well.
    30  func TestConvertDump(t *testing.T) {
    31  	if *convert == "" {
    32  		t.Skip("Set -convert to convert a trace text file")
    33  	}
    34  	if *output == "" {
    35  		t.Fatal("Set -out to specify conversion output")
    36  	}
    37  
    38  	if err := convertDump(*convert, *output); err != nil {
    39  		t.Error(err)
    40  	}
    41  }
    42  
    43  func convertDump(inPath, outPath string) error {
    44  	in, err := os.Open(inPath)
    45  	if err != nil {
    46  		return fmt.Errorf("error opening input: %v", err)
    47  	}
    48  	defer in.Close()
    49  
    50  	out, err := os.Create(outPath)
    51  	if err != nil {
    52  		return fmt.Errorf("error creating output: %v", err)
    53  	}
    54  	defer out.Close()
    55  
    56  	tr, err := raw.NewTextReader(in)
    57  	if err != nil {
    58  		return fmt.Errorf("error creating text reader: %v", err)
    59  	}
    60  	tw, err := raw.NewWriter(out, tr.Version())
    61  	if err != nil {
    62  		return fmt.Errorf("error creating raw writer: %v", err)
    63  	}
    64  
    65  	for {
    66  		ev, err := tr.ReadEvent()
    67  		if err == io.EOF {
    68  			break
    69  		}
    70  		if err != nil {
    71  			return fmt.Errorf("bad trace file: %v", err)
    72  		}
    73  		if err := tw.WriteEvent(ev); err != nil {
    74  			return fmt.Errorf("failed to write trace bytes: %v", err)
    75  		}
    76  	}
    77  
    78  	return nil
    79  }
    80  

View as plain text