diff options
-rw-r--r-- | main.go | 50 |
1 files changed, 32 insertions, 18 deletions
@@ -122,37 +122,44 @@ func cmdRun(args []string) { log.Fatalln(s.ListenAndServe()) } -func importFunc(path string, d fs.DirEntry, err error) error { - if err != nil || d.IsDir() { - return err - } - - // The input may be a relative path, and we want to remember it as such, - // but symlinks for the images must be absolute. - absPath, err := filepath.Abs(path) - if err != nil { - return err - } - +func isImage(path string) (bool, error) { cmd := exec.Command("xdg-mime", "query", "filetype", path) stdout, err := cmd.StdoutPipe() if err != nil { - return err + return false, err } if err := cmd.Start(); err != nil { - return err + return false, err } out, err := io.ReadAll(stdout) if err != nil { - return err + return false, err } if err := cmd.Wait(); err != nil { + return false, err + } + return bytes.HasPrefix(out, []byte("image/")), nil +} + +func importFunc(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + + // The input may be a relative path, and we want to remember it as such, + // but symlinks for the images must be absolute. + absPath, err := filepath.Abs(path) + if err != nil { return err } // Skip videos, which ImageMagick can process, but we don't want it to, // so that they're not converted 1:1 to WebP. - if !bytes.HasPrefix(out, []byte("image/")) { + pathIsImage, err := isImage(path) + if err != nil { + return err + } + if !pathIsImage { return nil } @@ -174,8 +181,11 @@ func importFunc(path string, d fs.DirEntry, err error) error { } hexSHA1 := hex.EncodeToString(hash.Sum(make([]byte, sha1.Size))) - // TODO: Make sure that the subdirectory exists. pathImage := imagePath(hexSHA1) + imageDirname, _ := filepath.Split(pathImage) + if err := os.MkdirAll(imageDirname, 755); err != nil { + return err + } if err := os.Symlink(absPath, pathImage); err != nil && !errors.Is(err, fs.ErrExist) { return err @@ -233,7 +243,11 @@ func cmdCheck(args []string) { } func makeThumbnail(pathImage, pathThumb string) (int, int, error) { - // TODO: Make sure that the trailing subdirectory in pathThumb exists. + thumbDirname, _ := filepath.Split(pathThumb) + if err := os.MkdirAll(thumbDirname, 755); err != nil { + return 0, 0, err + } + cmd := exec.Command("convert", pathImage, "-coalesce", "-colorspace", "RGB", "-auto-orient", "-strip", "-resize", "256x128>", "-colorspace", "sRGB", "-format", "%w %h", "+write", "info:", pathThumb) |