AppleScript to write Finder tag from folder name

This is a weird one that came from a request on reddit.

Not really useful (to me) as intended, but I envision it could be re-worked to a FolderAction that would help tag photos. Especially if coupled with a file sorter. But incorporating the tag writing into the sorter would be much more sane.

The commented out do shell script lines were meant as a way to read existing tags and then add the folder name after them. That didn’t work out thanks to xattr -p spitting out hexadecimal instead of a plist array, which is the format used when writing the tags. WTF, Apple…

-- http://strawhousepig.net/
on run
    set _drop to {}
    set end of _drop to (choose folder)
    my do_it(_drop)
end run

on open _drop
    my do_it(_drop)
end open

on do_it(_drop)
    display dialog "WARNING: This script will overwrite ALL tags of files in or targeted from the opened folder with the name of the opened folder." with icon 0
    repeat with d in _drop
        if folder of (info for d) is true then
            set f to {}
            try
                tell application "Finder"
                    set _tag to "<string>" & name of (info for d) & "</string>"
                    set _files to (every item in d)
                    repeat with f in _files
                        if alias of (info for f as alias) is true then
                            set f to original item of f as alias
                        end if
                        -- 'xattr -p' will print the value for a named metadata ID. Naturally that value is printed as hexadecimal. :|
                        --                      set f_plist to (do shell script "xattr -p com.apple.metadata:_kMDItemUserTags " & quoted form of POSIX path of (f as alias))
                        --                      set _tag to (do shell script "echo \"" & f_plist & "\" | egrep -o \"<string>*</string>\"") & _tag
                        set tag_plist to "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\"><array>" & _tag & "</array></plist>"
                        do shell script "xattr -w com.apple.metadata:_kMDItemUserTags " & quoted form of tag_plist & " " & quoted form of (POSIX path of f)

                    end repeat
                end tell
            on error _err
                display dialog _err
            end try
        end if
    end repeat
end do_it

Leave a Reply

Your email address will not be published. Required fields are marked *