Skip to content

Instantly share code, notes, and snippets.

@cesarandreu
Last active October 1, 2018 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cesarandreu/f3fc0c7e3f314e3735723c7eb750cbbc to your computer and use it in GitHub Desktop.
Save cesarandreu/f3fc0c7e3f314e3735723c7eb750cbbc to your computer and use it in GitHub Desktop.
macOS JXA utilities

macOS JXA utilities

  • pfd: Return the path of the frontmost Finder window. Mnemonic: print Finder directory.
  • pfs: Return the current Finder selection. Mnemonic: print Finder selection.
  • cdf: cd to the current Finder directory. Mnemonic: cd Finder.

Installation

  1. Open Script Editor from /Applications/Utilities.
  2. Create a new script and save it to ~/Library/Script Libraries with the name FinderUtils.scpt. Make sure that File Format is set to Script in the save dialog.
  3. Copy the contents of FinderUtils.js to your newly created script library.
  4. Save each utility to ~/.local/bin with permissions set to 755.

Notes

None of these may be used remotely, they will only work locally.

The pfd utility will fail for special views such as Recents, Computer, AirDrop, or Network. I don't know if it works with iCloud Drive.

These utilities were heavily inspired by oh-my-fish's osx plugin.

License: MIT.

#!/usr/bin/env sh
# cd to the current Finder directory
set -e
cd "$(pfd)"
function getSelection () {
return Application('Finder')
.selection()
.map(item => urlToPath(item.url()))
.join('\n')
}
function getPath () {
const windows = Application('Finder').windows()
if (!windows.length) {
throw new Error('No Finder windows open')
} else {
return urlToPath(windows[0].target().url())
}
}
function urlToPath (url) {
if (!url.startsWith('file://')) {
throw new Error(`Unexpected URL scheme: ${url}`)
}
return $.NSURL.alloc.initWithString($(url)).fileSystemRepresentation
}
#!/usr/bin/env osascript -l JavaScript
// Return the path of the frontmost Finder window
Library('FinderUtils').getPath()
#!/usr/bin/env osascript -l JavaScript
// Return the current Finder selection
Library("FinderUtils").getSelection()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment