Skip to content

Instantly share code, notes, and snippets.

@webercoder
Created January 3, 2017 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webercoder/235e668f9f1cfde6e7a6bec3fb7ac58b to your computer and use it in GitHub Desktop.
Save webercoder/235e668f9f1cfde6e7a6bec3fb7ac58b to your computer and use it in GitHub Desktop.
Recursively find iPhone photos in a directory and copy them to another
package main
import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
)
func usage(msg string) {
if len(msg) == 0 {
fmt.Print(msg)
}
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
func copyFile(source string) error {
sourceDir, sourceFileName := filepath.Split(source)
sourceDir = filepath.Base(sourceDir)
destDir := filepath.Join(os.Args[2], sourceDir)
dest := filepath.Join(destDir, sourceFileName)
dirExists, err := exists(destDir)
if err != nil {
return err
}
if !dirExists {
os.Mkdir(destDir, 0755)
}
fmt.Printf("Copying %s to %s...", strconv.Quote(source), strconv.Quote(dest))
in, err := os.Open(source)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dest)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
cerr := out.Close()
if err != nil {
return err
}
return cerr
}
func isIphonePhoto(path string) (bool, error) {
var (
cmdOut []byte
err error
)
cmdName := "exiftool"
cmdArgs := []string{path}
if cmdOut, err = exec.Command(cmdName, cmdArgs...).Output(); err != nil {
return false, err
}
result := string(cmdOut)
return strings.Contains(result, "iPhone"), nil
}
func checkFile(path string, fi os.FileInfo, err error) error {
var isIphonePhotoResult bool
if err != nil {
fmt.Printf("%+v\n", err)
return nil
}
// Skip directories
if fi.IsDir() {
return nil
}
if isIphonePhotoResult, err = isIphonePhoto(path); err != nil {
// fmt.Printf("Error running exiftool on %s, skipping...\n", path)
return nil
}
if isIphonePhotoResult {
if err = copyFile(path); err != nil {
fmt.Printf("Error running copy operation: %+v\n", err)
return nil
}
fmt.Printf(" Saved.\n")
}
return nil
}
func main() {
if len(os.Args) < 2 {
fmt.Printf("Usage: %s source dest\n", os.Args[0])
os.Exit(1)
}
source := os.Args[1]
filepath.Walk(source, checkFile)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment