How to get applications that can open a file on macOS
I needed to get a list from the terminal of applications that could be selected with ‘Open with’ in Finder. This process is similar to what is described in the following link.
By the way, all extensions can specify the application to be opened by default. and obtaining this was easy: just use the ‘mdls’ or ‘duti’ commands.
So, how can I achieve the process I’m aiming for?
For example, if you search the Internet, you will discover a technique that uses the “lsregister” command.
Although this was terribly redundant for me.
This is because the amount of stdout dumped at one time is approximately 20 MB. Do we use the grep command to extract the necessary information from it? The answer is no.
Therefore, I thought of another approach
From a Mac terminal, AppleScript can be executed using the "osascript" command. And AppleScript can use Swift excellent functions.
How about the LSCopyAllRoleHandlersForContentType function as a test?
However, this function is apparently obsolete since macOS 12.0.
I took further time to investigate, and as a result, I finally found the method I was looking for in AppKit: the URLsForApplicationsToOpenURL method.
Actually write an AppleScript based on this.
use AppleScript version "2.4"
use scripting additions
use framework "AppKit"
set filePath to "file path"
set fileURL to current application's NSURL's fileURLWithPath:filePath
set workspace to current application's NSWorkspace's sharedWorkspace()
set appsArray to workspace's URLsForApplicationsToOpenURL:fileURL
set resultList to {}
repeat with appURL in appsArray
set end of resultList to appURL's lastPathComponent() as text
end repeat
return resultList
I tried it with a PNG file and was able to get a list of applications that could open it with flying colors.
And this would be feasible from the terminal.
Discussion