38 lines
1.0 KiB
Go
38 lines
1.0 KiB
Go
package fileops
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
// WriteSiblingTemp writes and closes a temporary sibling without installing it.
|
|
// The caller owns the returned path and must remove or install it.
|
|
func WriteSiblingTemp(destination string, write func(io.Writer) error) (string, error) {
|
|
if strings.TrimSpace(destination) == "" {
|
|
return "", fmt.Errorf("destination path is required")
|
|
}
|
|
if write == nil {
|
|
return "", fmt.Errorf("temporary writer is required")
|
|
}
|
|
directory := filepath.Dir(destination)
|
|
if err := EnsureWorkspaceDirectory(directory); err != nil {
|
|
return "", fmt.Errorf("create destination directory: %w", err)
|
|
}
|
|
file, err := os.CreateTemp(directory, "."+filepath.Base(destination)+".tmp-*")
|
|
if err != nil {
|
|
return "", fmt.Errorf("create sibling temporary file: %w", err)
|
|
}
|
|
path := file.Name()
|
|
writeErr := write(file)
|
|
closeErr := file.Close()
|
|
if err := errors.Join(writeErr, closeErr); err != nil {
|
|
removeErr := os.Remove(path)
|
|
return "", errors.Join(err, removeErr)
|
|
}
|
|
return path, nil
|
|
}
|