package main import ( "fmt" "os" "errors" "io" "strings" "regexp" "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 } func replaceDelimiters(input string) string { replacer := strings.NewReplacer( "/", "/", "\\", "\", ) return replacer.Replace(input) } func sanitizeFilename(filename string) string { 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 }