AppleScript - Folder actions - add tag to file in workflow

Hi there


I'm no star in all this, I tried to create it myself, but after 2 days of trying to change all the parameters, I'm pulling a "hail mary" and hoping someone can tell me how it is done:


I'm running macOS Catalina.

The resources I already tried to incorporate (and some others, but they boil down to these 3, most of the time):

https://discussions.apple.com/thread/8267280?answerId=32971986022#32971986022

https://apple.stackexchange.com/questions/106109/any-way-to-set-add-tags-on-a-file-with-applescript-under-mavericks

https://apple.stackexchange.com/questions/131258/add-and-remove-multiple-tags-at-once-from-a-file-or-a-folder


I have a workflow when I add a file to a folder:

  1. add specific tags
  2. upload to cloud
  3. create backup file


Since I ran into some Folder actions issues (eg: not running), I want to add some extra steps, so it would look like this:

  1. add specific tags (related to the folder)
  2. upload to cloud
  3. add tag "uploaded"
  4. create backup
  5. add tag "backup"


and if you would indulge me, let me stretch my request, just a little bit:

in step 1, would it be possible to

  • add a tag, based on the first 4 digits of the filename?
  • add a tag, based on the 5th and 6th digit of the filename (eg: 1 to 3 = 1, 4 to 6 = 2, 7 to 9 = 3, etc...)?


The code I have until now:

  • create tags:
property ca : current application
property tagname : {"tag1", "tag2", "tag3"}

use framework "foundation"
use AppleScript version "2.4" -- Yosemite 10.10 or later required
use scripting additions

on run {input, parameters}
	repeat with anItem in input
		set_tag(anItem, tagname)
	end repeat
	return input
end run

on set_tag(theFile, atag)
	set tagArray to ca's NSArray's arrayWithArray:atag
	set fileURL to ca's |NSURL|'s fileURLWithPath:(POSIX path of theFile)
	fileURL's setResourceValue:tagArray forKey:(ca's NSURLTagNamesKey) |error|:(missing value)
end set_tag


  • upload to cloud
on run {input, parameters}
	
	set targetNotebook to "notebook 1"
	
	repeat with this_item in the input
		set the item_info to info for this_item
		# uncomment if you want to copy tags to evernote:
		# set the_tags to paragraphs of (do shell script "mdls -raw -name kMDItemUserTags " & quoted form of POSIX path of this_item & " | sed 's/^[()]$//g' | ruby -ne 'each = $_.strip.end_with?(\",\") ? $_.strip[0...-1] : $_.strip; puts each if each != \"\"'"
		tell application "Finder"
			set createdFileDate to (the creation date of (this_item as alias))
			set modFileDate to (the modification date of (this_item as alias))
		end tell
		
		tell application "Evernote"
			launch
			# uncomment if you want to copy tags to evernote:
			# set theItem to create note from file this_item notebook targetNotebook tags the_tags created createdFileDate
			set theItem to create note from file this_item notebook targetNotebook created createdFileDate
			set (modification date of theItem) to modFileDate
		end tell
	end repeat
	
	return input
end run


  • copy Finder items is the third step, and is standard.


Thank you very much, in advance!

Posted on Apr 12, 2020 3:00 AM

Reply
Question marked as Top-ranking reply

Posted on Apr 12, 2020 7:11 AM

Immediately after the set_tag handler, place the following handler to add tags to an existing tagged file or folder.


on add_tag(theFile, atag)
	set fileURL to ca's |NSURL|'s fileURLWithPath:(POSIX path of theFile)
	set {theResult, theTags} to fileURL's getResourceValue:(reference) forKey:(ca's NSURLTagNamesKey) |error|:(missing value)
	if theTags is not missing value then
		set tagList to (theTags as list) & atag
		-- set will eliminate duplicate tag names
		set tagList to (ca's NSOrderedSet's orderedSetWithArray:tagList)'s allObjects()
	end if
	-- apply the additional tag(s) to the file/folder
	fileURL's setResourceValue:tagList forKey:(ca's NSURLTagNamesKey) |error|:(missing value)
	return
end add_tag


Usage:


on run {input, parameters}
	
	repeat with anItem in input
		set_tag(anItem, {"uploaded"})
		add_tag(anItem, {"backup"})
	end repeat
	return input
end run



The tag names used above must already be defined in Finder Preferences : Tags, as one cannot create new tag names, and add them to Finder programmatically. Tags are intended for Apple filesystems (e.g. HFS+, APFS, iCloud), and moving them to other filesystems can strip the tag attributes from the files.

Similar questions

6 replies
Question marked as Top-ranking reply

Apr 12, 2020 7:11 AM in response to syberon

Immediately after the set_tag handler, place the following handler to add tags to an existing tagged file or folder.


on add_tag(theFile, atag)
	set fileURL to ca's |NSURL|'s fileURLWithPath:(POSIX path of theFile)
	set {theResult, theTags} to fileURL's getResourceValue:(reference) forKey:(ca's NSURLTagNamesKey) |error|:(missing value)
	if theTags is not missing value then
		set tagList to (theTags as list) & atag
		-- set will eliminate duplicate tag names
		set tagList to (ca's NSOrderedSet's orderedSetWithArray:tagList)'s allObjects()
	end if
	-- apply the additional tag(s) to the file/folder
	fileURL's setResourceValue:tagList forKey:(ca's NSURLTagNamesKey) |error|:(missing value)
	return
end add_tag


Usage:


on run {input, parameters}
	
	repeat with anItem in input
		set_tag(anItem, {"uploaded"})
		add_tag(anItem, {"backup"})
	end repeat
	return input
end run



The tag names used above must already be defined in Finder Preferences : Tags, as one cannot create new tag names, and add them to Finder programmatically. Tags are intended for Apple filesystems (e.g. HFS+, APFS, iCloud), and moving them to other filesystems can strip the tag attributes from the files.

Apr 13, 2020 12:23 PM in response to VikingOSX

Thanks for the info @VikingOSX, I don't mind creating them beforehand, it's only 5 tags.


I have been playing around today, but I don't manage to resolve the more pressing issue: "the backup tag is added to the file I backed up, not to the original file."


Do you know, how I can ignore the input of the "finder copy items" task and use the same input as the "finder copy items" task? I added a picture of my workflow, should that make it more clear.



The adding of the tag has to happen after I backup the file, as this is a webdav drive, I mount manually (and thus sometimes forget, hence the need for the backup tag, so I now if it backed up the file already or I should do it again).

I do this, this way, should I ever be the victim of a ransomware, then I can ignore it, as all my important files are backed up, and not connected to my pc.

Apr 12, 2020 5:29 PM in response to syberon

I found a caveat, in my way of working: the backup tag is added to the file I backed up, not to the original file. which makes it a bit useless, atm ;) if I find it on my backup drive, I know it's backed up. I need to now, when sorting on my tags, which backups failed.


For completeness, I did it a little bit different:

  • 1st and 2nd script remain the same.
  • then I inserted a new "run Applescript" with following code:


property ca : current application
property tagname : {"evernote"}

use framework "foundation"
use AppleScript version "2.4" -- Yosemite 10.10 or later required
use scripting additions

on run {input, parameters}
	repeat with anItem in input
		add_tag(anItem, tagname)
	end repeat
	return input
end run

on add_tag(theFile, atag)
	set fileURL to ca's |NSURL|'s fileURLWithPath:(POSIX path of theFile)
	set {theResult, theTags} to fileURL's getResourceValue:(reference) forKey:(ca's NSURLTagNamesKey) |error|:(missing value)
	if theTags is not missing value then
		set tagList to (theTags as list) & atag
		-- set will eliminate duplicate tag names
		set tagList to (ca's NSOrderedSet's orderedSetWithArray:tagList)'s allObjects()
	end if
	-- apply the additional tag(s) to the file/folder
	fileURL's setResourceValue:tagList forKey:(ca's NSURLTagNamesKey) |error|:(missing value)
	return
end add_tag


  • the 4th action remained untouched as well
  • then I repeated the above script, but with the "backup" tag.


concerning the second question:

  • add/create a tag, based on the first 4 digits of the filename?
  • add/create a tag, based on the 5th and 6th digit of the filename (eg: 1 to 3 = 1, 4 to 6 = 2, 7 to 9 = 3, etc...)?


Does anyone have an idea on how to do this or a place where I could go and look for a solution?

A quick lookup on duckduckgo didn't show me much promise

Apr 13, 2020 5:11 AM in response to syberon

All custom Finder tag names must be initially, and manually created in the Finder Preferences : Tag panel, where they are assigned a color, and a status of active/inactive.


The only exception to this rule is that the Finder has internal code that detects when a new file arrives on the machine that was assigned a tagname, color, and status on another Mac — the Finder will automatically update that information into its tag database, and this appears in the Finder Tags panel as active. There are no Objective-C, or AppleScript methods to accomplish paragraph one, so your hope of auto-generation of tag names constructed from filenames has no support.


You can use the set_tag handler to assign an unregistered tag name on a file, but it will have no color, and is inactive by default. Spotlight can find this tag, but that is all.


One can set, append, or clear Finder comments on a file via Finder Get Info, or access via Spotlight via comment:"string".

Apr 13, 2020 1:51 PM in response to syberon


  1. Run AppleScript - add initial tags
  2. Run AppleScript - copy to Evernote
  3. Run AppleScript - add evernote tag if successful
    1. Needs to return full path to Evernote file
  4. Set Value of Variable - Storage
  5. Copy Finder Items
    1. Option - Ignore this action's input
  6. Get Value of Variable - Storage
    1. Option - Ignore this action's input
  7. Run AppleScript - add backup tag
    1. Only the Evernote file from 3 is the input item here


This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

AppleScript - Folder actions - add tag to file in workflow

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.