github.com/TBD54566975/ftl@v0.219.0/internal/zip_relative.go (about)

     1  //go:build !release
     2  
     3  package internal
     4  
     5  import (
     6  	"archive/zip"
     7  	"os"
     8  	"path/filepath"
     9  	"runtime"
    10  )
    11  
    12  // ZipRelativeToCaller creates a temporary zip file from a path relative to the caller.
    13  //
    14  // This function will leak a file descriptor and thus can only be used in development.
    15  func ZipRelativeToCaller(relativePath string) *zip.Reader {
    16  	_, file, _, _ := runtime.Caller(1)
    17  	dir := filepath.Join(filepath.Dir(file), relativePath)
    18  	w, err := os.CreateTemp("", "")
    19  	if err != nil {
    20  		panic(err)
    21  	}
    22  	defer os.Remove(w.Name()) // This is okay because the zip.Reader will keep it open.
    23  	if err != nil {
    24  		panic(err)
    25  	}
    26  
    27  	err = ZipDir(dir, w.Name())
    28  	if err != nil {
    29  		panic(err)
    30  	}
    31  
    32  	info, err := w.Stat()
    33  	if err != nil {
    34  		panic(err)
    35  	}
    36  	_, _ = w.Seek(0, 0)
    37  	zr, err := zip.NewReader(w, info.Size())
    38  	if err != nil {
    39  		panic(err)
    40  	}
    41  	return zr
    42  }