use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
property searchIsDone : false
my searchInListOfPaths:{POSIX path of (path to home folder)} forTags:{"Red"}
on searchInListOfPaths:scopeList forTags:tagList -- pass empty list for any tags
(* scope can be a list of POSIX paths and/or the following enums:
NSMetadataQueryUserHomeScope
NSMetadataQueryLocalComputerScope
NSMetadataQueryNetworkScope
NSMetadataQueryUbiquitousDocumentsScope
NSMetadataQueryUbiquitousDataScope
NSMetadataQueryAccessibleUbiquitousExternalDocumentsScope
NSMetadataQueryIndexedLocalComputerScope -- 10.10 or later
NSMetadataQueryIndexedNetworkScope
Eg:
searchInListOfPaths:{current application's NSMetadataQueryLocalComputerScope} forTags:tagList
*)
-- Build the search predicate
set tagListCount to count of tagList
if tagListCount = 0 then -- any tags
set pred to current application's NSPredicate's predicateWithFormat:("kMDItemUserTags LIKE '*'")
else if tagListCount = 1 then
set pred to current application's NSPredicate's predicateWithFormat:"kMDItemUserTags CONTAINS[c] %@" argumentArray:tagList
else
set predList to {}
repeat with aTag in tagList
set end of predList to (current application's NSPredicate's predicateWithFormat:"kMDItemUserTags CONTAINS[c] %@" argumentArray:{aTag})
end repeat
set pred to current application's NSCompoundPredicate's andPredicateWithSubpredicates:predList
end if
-- make the query
set theQuery to current application's NSMetadataQuery's alloc()'s init()
theQuery's setPredicate:pred
-- set its scope
theQuery's setSearchScopes:scopeList
-- tell the notification center to tell us when it's done
set notifCenter to current application's NSNotificationCenter's defaultCenter()
notifCenter's addObserver:me selector:"searchDone:" |name|:(current application's NSMetadataQueryDidFinishGatheringNotification) object:theQuery
-- start searching
set my searchIsDone to false
theQuery's startQuery()
-- loop until it's done
repeat
delay 0.01
if searchIsDone then exit repeat
end repeat
-- get results
theQuery's stopQuery()
set theCount to theQuery's resultCount()
set resultsArray to current application's NSMutableArray's array() -- to hold results
repeat with i from 1 to theCount
(resultsArray's addObject:((theQuery's resultAtIndex:(i - 1))'s valuesForAttributes:{current application's NSMetadataItemPathKey, "kMDItemUserTags"}))
end repeat
return resultsArray as list -- will be list of records
end searchInListOfPaths:forTags:
on searchDone:notification
set my searchIsDone to true
end searchDone: