// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package testtrace

import (
	
	
	
	
	
	
	
	
	
)

// Dump saves the trace to a file or the test log.
func ( *testing.T,  string,  []byte,  bool) {
	 := testenv.Builder() != ""
	 := !strings.Contains(testenv.Builder(), "gotip") && !strings.Contains(testenv.Builder(), "go1")

	if  && ! {
		// Dump directly to the test log on the builder, since this
		// data is critical for debugging and this is the only way
		// we can currently make sure it's retained.
		 := dumpTraceToText(, )
		if  && len() > 1<<20+512<<10 {
			// The old build infrastructure truncates logs at ~2 MiB.
			// Let's assume we're the only failure and give ourselves
			// up to 1.5 MiB to dump the trace.
			//
			// TODO(mknyszek): Remove this when we've migrated off of
			// the old infrastructure.
			.Logf("text trace too large to dump (%d bytes)", len())
		} else {
			.Log()
			.Log("Convert this to a raw trace with `go test internal/trace/testtrace -convert in.tracetxt -out out.trace`")
		}
	} else {
		// We asked to dump the trace or failed. Write the trace to a file.
		.Logf("wrote trace to file: %s", dumpTraceToFile(, , ))
	}
}

func dumpTraceToText( *testing.T,  []byte) string {
	.Helper()

	,  := raw.NewReader(bytes.NewReader())
	if  != nil {
		.Fatalf("dumping trace: %v", )
	}
	var  strings.Builder
	,  := raw.NewTextWriter(&, version.Current)
	if  != nil {
		.Fatalf("dumping trace: %v", )
	}
	for {
		,  := .ReadEvent()
		if  == io.EOF {
			break
		}
		if  != nil {
			.Fatalf("dumping trace: %v", )
		}
		if  := .WriteEvent();  != nil {
			.Fatalf("dumping trace: %v", )
		}
	}
	return .String()
}

func dumpTraceToFile( *testing.T,  string,  []byte) string {
	.Helper()

	 := fmt.Sprintf("%s.trace.", )
	,  := os.CreateTemp(.ArtifactDir(), )
	if  != nil {
		.Fatalf("creating temp file: %v", )
	}
	defer .Close()
	if ,  := io.Copy(, bytes.NewReader());  != nil {
		.Fatalf("writing trace dump to %q: %v", .Name(), )
	}
	return .Name()
}