github.com/thanos-io/thanos@v0.32.5/pkg/testutil/e2eutil/copy.go (about)

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