Skip to content

Instantly share code, notes, and snippets.

@IlyaGulya
Created August 14, 2025 13:52
Show Gist options
  • Save IlyaGulya/62d03a661362a2a819c7a27f27dba6cc to your computer and use it in GitHub Desktop.
Save IlyaGulya/62d03a661362a2a819c7a27f27dba6cc to your computer and use it in GitHub Desktop.
converts an embedded filesystem directory to ContainerFile slice
import (
"fmt"
"io/fs"
"path/filepath"
"strings"
"github.com/testcontainers/testcontainers-go"
)
// EmbedToContainerFiles converts an embedded filesystem directory to ContainerFile slice
// embedFS: the embedded filesystem
// embedPath: the path within the embedded filesystem to read from
// containerBasePath: the base path where files should be placed in the container
func EmbedToContainerFiles(embedFS fs.FS, embedPath string, containerBasePath string) ([]testcontainers.ContainerFile, error) {
var containerFiles []testcontainers.ContainerFile
err := fs.WalkDir(embedFS, embedPath, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// Skip directories
if d.IsDir() {
return nil
}
// Read file content
content, err := fs.ReadFile(embedFS, path)
if err != nil {
return fmt.Errorf("failed to read embedded file %s: %w", path, err)
}
// Convert embed path to container path
// Remove the embedPath prefix and join with containerBasePath
relativePath := strings.TrimPrefix(path, embedPath)
relativePath = strings.TrimPrefix(relativePath, "/") // Remove leading slash if present
containerPath := filepath.Join(containerBasePath, relativePath)
containerFiles = append(containerFiles, testcontainers.ContainerFile{
Reader: strings.NewReader(string(content)),
ContainerFilePath: containerPath,
FileMode: 0644,
})
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to walk embedded directory %s: %w", embedPath, err)
}
return containerFiles, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment