github.com/grafana/pyroscope@v1.18.0/pkg/test/copy.go (about)

     1  // SPDX-License-Identifier: AGPL-3.0-only
     2  // Provenance-includes-location: https://github.com/thanos-io/thanos/blob/main/pkg/testutil/e2eutil/copy.go
     3  // Provenance-includes-license: Apache-2.0
     4  // Provenance-includes-copyright: The Thanos Authors.
     5  
     6  package test
     7  
     8  import (
     9  	"io"
    10  	"os"
    11  	"path/filepath"
    12  	"testing"
    13  
    14  	"github.com/grafana/dskit/runutil"
    15  	"github.com/pkg/errors"
    16  	"github.com/stretchr/testify/require"
    17  )
    18  
    19  func Copy(t testing.TB, src, dst string) {
    20  	require.NoError(t, copyRecursive(src, dst))
    21  }
    22  
    23  func copyRecursive(src, dst string) error {
    24  	return filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
    25  		if err != nil {
    26  			return err
    27  		}
    28  
    29  		relPath, err := filepath.Rel(src, path)
    30  		if err != nil {
    31  			return err
    32  		}
    33  
    34  		if info.IsDir() {
    35  			return os.MkdirAll(filepath.Join(dst, relPath), os.ModePerm)
    36  		}
    37  
    38  		if !info.Mode().IsRegular() {
    39  			return errors.Errorf("%s is not a regular file", path)
    40  		}
    41  
    42  		source, err := os.Open(filepath.Clean(path))
    43  		if err != nil {
    44  			return err
    45  		}
    46  		defer runutil.CloseWithErrCapture(&err, source, "close file")
    47  
    48  		destination, err := os.Create(filepath.Join(dst, relPath))
    49  		if err != nil {
    50  			return err
    51  		}
    52  		defer runutil.CloseWithErrCapture(&err, destination, "close file")
    53  
    54  		_, err = io.Copy(destination, source)
    55  		return err
    56  	})
    57  }