ytva/file.go

86 lines
2.1 KiB
Go
Raw Permalink Normal View History

2024-12-31 16:33:46 -05:00
package main
import (
"fmt"
"os"
"errors"
2024-12-31 19:48:37 -05:00
"io"
"strings"
"regexp"
2024-12-31 16:33:46 -05:00
2024-12-31 19:48:37 -05:00
"github.com/charmbracelet/log"
2024-12-31 16:33:46 -05:00
"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
}
func replaceDelimiters(input string) string {
replacer := strings.NewReplacer(
2025-01-04 01:49:17 -05:00
"/", "",
"\\", "",
)
return replacer.Replace(input)
}
func sanitizeFilename(filename string) string {
2025-01-04 01:49:17 -05:00
invalidFilenameChars := regexp.MustCompile(`[^a-zA-Z0-9._-[[:blank:]]]+`)
sanitized := invalidFilenameChars.ReplaceAllString(filename, "-")
// Trim any leading or trailing spaces or underscores.
sanitized = strings.Trim(sanitized, " _.")
if sanitized == "" {
sanitized = " "
}
return sanitized
}