util: file copy and exec.LookPath wrapper

Add convenience functions for copying files to owner readable targets and LookPath comma ok wrapper.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
This commit is contained in:
Ophestra 2024-07-15 01:20:52 +09:00
parent 190eb088bc
commit 289e681c41
Signed by: cat
SSH Key Fingerprint: SHA256:gQ67O0enBZ7UdZypgtspB2FDM1g3GVw8nX0XSdcFw8Q

34
util.go
View File

@ -3,8 +3,10 @@ package main
import ( import (
"errors" "errors"
"fmt" "fmt"
"io"
"io/fs" "io/fs"
"os" "os"
"os/exec"
) )
const ( const (
@ -26,3 +28,35 @@ func sdBooted() bool {
} }
return true return true
} }
func which(file string) (string, bool) {
path, err := exec.LookPath(file)
return path, err == nil
}
func copyFile(dst, src string) error {
srcD, err := os.Open(src)
if err != nil {
return err
}
defer func() {
if srcD.Close() != nil {
// unreachable
panic("src file closed prematurely")
}
}()
dstD, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer func() {
if dstD.Close() != nil {
// unreachable
panic("dst file closed prematurely")
}
}()
_, err = io.Copy(dstD, srcD)
return err
}