60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"errors"
|
|
"io"
|
|
|
|
|
|
"github.com/charmbracelet/log"
|
|
"github.com/h2non/filetype"
|
|
)
|
|
|
|
|
|
func getExtension(filePath string) (extension string, err error) {
|
|
buf, _ := os.ReadFile(filePath)
|
|
|
|
kind, _ := filetype.Match(buf)
|
|
if kind == filetype.Unknown {
|
|
return "", errors.New(fmt.Sprintf("Unknown file type."))
|
|
}
|
|
|
|
return kind.Extension, nil
|
|
}
|
|
|
|
func copyFile(src, dst string) (error) {
|
|
log.Debugf("Copying file \"%s\" to \"%s\"", src, dst)
|
|
|
|
// Get source file stats (e.g. permissions).
|
|
srcFileStat, err := os.Stat(src)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get file info for %s: %v", src, err)
|
|
}
|
|
|
|
// Check whether the source is a regular file.
|
|
if !srcFileStat.Mode().IsRegular() {
|
|
return fmt.Errorf("source file %s is not a regular file", src)
|
|
}
|
|
|
|
// Open the source file.
|
|
srcFile, err := os.Open(src)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to open source file %s: %v", src, err)
|
|
}
|
|
defer srcFile.Close()
|
|
|
|
// Create the destination file, with the same permissions as the source.
|
|
dstFile, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, srcFileStat.Mode())
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create destination file %s: %v", dst, err)
|
|
}
|
|
defer dstFile.Close()
|
|
|
|
// Copy the file contents from source to destination.
|
|
if _, err := io.Copy(dstFile, srcFile); err != nil {
|
|
return fmt.Errorf("error copying file from %s to %s: %v", src, dst, err)
|
|
}
|
|
|
|
return nil
|
|
}
|