Search code examples
javascriptjavascript-automation

How can I get the posix path of a file that is selected by Finder?


I am trying to get the full path of a file that is selected by Finder. At this point, I have tried many methods:

>> Application('Finder').selection()[0]
=> Application("Finder").startupDisk.folders.byName("Users").folders.byName("example").folders.byName("Tools").folders.byName("my-tools").documentFiles.byName("example.sh")
>>
>> Application('Finder').selection()[0].name()
=> "example.sh"
>>
>> Application('Finder').selection()[0].toString()
=> "[object ObjectSpecifier]"
>>
>> Application('Finder').selection()[0].posixPath()
!! Error on line 1: Error: Can't get object.
>>
>> Application('Finder').selection()[0].path()
!! Error on line 1: Error: Can't get object.
>>
>> Application('Finder').selection()[0].url()
=> "file:///Users/example/Tools/my-tools/example.sh"
>>
>> Path(Application('Finder').selection()[0])
!! Error on line 1: Error: Can't get object.
>>
>> Path(Application('Finder').selection()[0]).toString()
!! Error on line 1: Error: Can't get object.

None of these commands obtain the posix path which is /Users/example/Tools/my-tools/example.sh.

Ultimately, I know I can simply strip the file:// off of the front of the url:

>> Application('Finder').selection()[0].url().replace(/^file:\/\//, '')
=> "/Users/example/Tools/my-tools/example.sh"

But that seems hacky, and it seems like there should be a command to obtain the posix path directly.


Solution

  • If you examin the file's properties(), you will see that the only property which contains the full path is the url(). However, special characters are escaped and the url is prefixed with the file:// protocol when using the url() property:

    >> Application('Finder').selection()[0].name()
    => "asdf\"asdf.txt"
    >>
    >> Application('Finder').selection()[0].url()
    => "file:///Users/example/Tools/my-tools/asdf%22asdf.txt"
    

    In order to get the POSIX path, you can unescape() the url() and remove the file:// protocol from the beginning of the url():

    >> unescape(Application('Finder').selection()[0].url()).replace(/^file[:]\/\//, '')
    => "/Users/example/Tools/my-tools/asdf\"asdf.txt"