Applescript: Get path to .app without opening it - macos

I have the following handler;
on getAppPath(appName)
try
return POSIX path of (path to application appName)
on error
return "NOT INSTALLED"
end try
end getAppPath
Which when called with eg "ImageOptim" will return "/Applications/ImageOptim.app/".
The problem I have is that this opens that application in my Dock, is there a way to get this path string without that happening?
Thanks.

path to is in Standard Additions and it must launch the app to get the return value (with the exception of some of Apple's apps-- see for example TextEdit). One idea is to query the Launch Services Registry, which has records of all executables, and the use grep to pull the path that matches the app name you're specifying. Something like:
getAppPath("TextEdit.app")
on getAppPath(appName)
try
set launchServicesPath to "/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister"
-- get the path to all executables in the Launch Service Registry that contain that appName
set appPaths to paragraphs of (do shell script launchServicesPath & " -dump | grep --only-matching \"/.*\\" & appName & "\"")
return appPaths
on error
return "NOT INSTALLED"
end try
end getAppPath
Note that this can return a list of paths, since there could be more than one executable with a matching string app name. So, you'll want to account for that.

Related

Applescript to find the newest folder

I'm trying to find the folder which has been last modified. (Actually, I'm only interested in that folder and not an ordered list.) I'm getting an -10010 error.
tell application "Finder"
try
set latestFolder to item 1 of (sort (get name of folders of folder ("/Users/c64/Desktop" as POSIX file)) by creation date) as alias
set folderName to latestFolder's name
end try
end tell
If you're looking for the name of the last modified folder on the Desktop, then this will do it:
tell application "Finder"
set latestModifiedFolderName to name of item 1 of (sort every folder by modification date)
end tell
By the way, the AppleScript Dictionary for Finder does not contain terms POSIX file or POSIX path and when using e.g. POSIX file inside of a tell application "Finder" block, Finder will throw a non-fatal error if it can be coerced into an alias, otherwise it can throw a fatal error. That said, if you are dealing with a POSIX path, it's probably best to pass it to Finder as an alias, and I'd recommend coercing the POSIX path to an alias before passing it to Finder, e.g.:
set thisFolderPath to POSIX file "/Path/To/Some/Folder" as alias
tell application "Finder"
set latestModifiedFolderName to name of item 1 of (sort every folder of thisFolderPath by modification date)
end tell
Note: The example AppleScript code above is just that, and does not include any error handling as may be appropriate/needed/wanted, the onus is upon the user to add any error handling for any example code presented and or code written by the oneself.

Using Applescript to open filenames with escaped characters

Once upon a time, it was possible to put file:// urls into webpages, and if that URL matched a file on your desktop, why, the file would open on your computer when you clicked on the link.
This functionality has been disabled for security reasons, but I'm trying to recreate it for my own personal use. I'm trying to use a custom URL protocol and an Applescript application as described at http://www.macosxautomation.com/applescript/linktrigger/. I've almost got it working, with one difficulty: A URL can't have spaces in it, so they get escaped, as do other special characters like "&". How can I convince Applescript to open a file with a path with escaped characters in it, such as "/Users/jim/Dropbox/Getting%20Started.pdf"?
tell application "Finder"
open "/Users/jim/Dropbox/Getting Started.pdf" as POSIX file
works fine, whereas
tell application "Finder"
open "/Users/jim/Dropbox/Getting%20Started.pdf" as POSIX file
fails.
Is there an easy (i.e. non-regex) way to make this work?
You can use the open command in do shell script.
Like this:
set tUrl to "/Users/jim/Dropbox/Getting%20Started.pdf"
do shell script "open 'file://" & tUrl & "'"
Try the following:
tell application "Finder"
open my decodeFromUri("/Users/jim/Dropbox/Getting%20Started.pdf") as POSIX file
end tell
after declaring the following handler:
(*
Decodes a string previously encoded for inclusion in a URI (URL).
Note: Uses Perl and its URI::Escape module (preinstalled as of at least OSX 10.8).
Adapted, with gratitude, from http://applescript.bratis-lover.net/library/url/
Example:
my decodeFromUri("me%2Fyou%20%26%20Mot%C3%B6rhead") # -> "me/you & Motörhead"
*)
on decodeFromUri(str)
if str is missing value or str = "" then return str
try
# !! We MUST use `-ne` with `print` rather than just `-pe`; the latter returns the input unmodified.
return do shell script "printf '%s' " & quoted form of str & " | perl -MURI::Escape -ne 'print uri_unescape($_)'"
on error eMsg number eNum
error "Decoding from URI failed: " & eMsg number eNum
end try
end decodeFromUri

applescript (10.9) Can’t make alias into type specifier

The below applescript registers AppUninstaller.scpt as folder action to Trash folder.
Registering the folder action script works fine in Mac OSX 10.7 and 10.8.
In 10.9, I get the error "Attach error System Events got an error: Can’t make alias "Macintosh HD:Users:[username]:.Trash:" into type specifier."
The error occurs while executing this statement
attach action to _trashFolder using _uninstallerScriptPath
the complete script is below.
on run
tell utils
init()
registerFolderAction()
end tell
end run
script utils
property _uninstallerScript : "AppUninstaller.scpt"
property _resRelativePath : ":Applications:TestDemo.app:Contents:Resources:"
property _folderActionScriptRelativePath : "Scripts:Folder Action Scripts"
global _resPath
global _trashFolder
global _uninstallerScriptPath
on init()
-- Setup paths
set _trashFolder to path to trash folder
set _uninstallerScriptPath to getUninstallerScript()
-- Add boot disk name to App relative path
tell application "Finder"
set startupDisk to (name of startup disk)
set _resPath to startupDisk & _resRelativePath
end tell
set scriptFolderPath to getScriptPath()
-- Copy folder action script file from appbundle to scripts folder
copyScript()
end init
on registerFolderAction()
try
tell application "System Events"
set folder actions enabled to true
log _uninstallerScriptPath
-- problem with below statement.
attach action to _trashFolder using _uninstallerScriptPath
end tell
on error msg
display dialog "Attach error " & msg
end try
end registerFolderAction
on getScriptPath()
return ((path to library folder from user domain) as string) & _folderActionScriptRelativePath
end getScriptPath
on getUninstallerScript()
return getScriptPath() & ":" & _uninstallerScript
end getUninstallerScript
-- copying the script inside app bundle into scripts folder.
on copyScript()
tell application "Finder"
set srcFile to _resPath & _uninstallerScript
set dstFile to my getScriptPath()
log "Src File " & srcFile & " dstFolder " & dstFile
duplicate file srcFile to dstFile with replacing
end tell
end copyScript
end script
Looking at the error (and after testing myself) it seems that in pre-Mavericks systems the first argument of attach action to command is properly coerced into a file/folder object specifier when the argument is an alias. In Mavericks this coercion somehow doesn't happen and an error will occur because the given argument is not an object/type specifier but an alias class. The first argument of attach action to needs to be an object/type specifier so you can solve your problem by forcing the coercion when the command is called.
attach action to folder (_trashFolder as text) using _uninstallerScriptPath
You can do the same with argument using

OSX: How can check whether a file exists in current directory using applescript?

I want to make an automator app which creates an empty file in current directory.
I did some google search and found:
http://hints.macworld.com/article.php?story=20050219134457298 and http://hints.macworld.com/article.php?story=20100509134904820
However, I want to do something more powerful.
If the specified file already exists, I want to show a warning instead of overwriting the original file, which is what one of the above link does. (The other one creates a text file using textEdit. I do not want to create text file. I want an empty file like what linux/unix does)
I already figured out how to do most of the part, but
How can check whether a file exists in current directory using applescript??
How can I concatenate two variable in applescript?
Checking if a file exists (assuming thefullpath is already set as in the referenced question):
tell application "Finder"
if exists POSIX file thefullpath then
--do something here like
display alert "Warning: the file already exists"
end if
end tell
Not sure what you mean by the second part but if you want to concatenate strings stored in var1 and var2 you could simply do
var1 & var2
Something I have been using a lot of late for this sort of thing is the command /bin/test
The test test for the existence of in this case a file
if (do shell script "/bin/test -e " & quoted form of (POSIX path of theFile) & " ; echo $?") is "1" then
-- 1 is false
--do something
end if
The -e option:
-e file True if file exists (regardless of type).
The are tons of other test options shown in the /bin/test man page
The following code, adapted from your second link, is usually right, but it doesn't always work. The current directory is better specified as the directory of the document that is being opened which is most likely from the Finder's front window, but not necessarily. I like to write code that will work no matter what.
on run {input, parameters}
tell application "Finder"
set currentPath to insertion location as text
set x to POSIX path of currentPath
display dialog "currentPath: " & (x as text)
end tell
return x
end run
I wrote a whole "Run AppleScript" action to put things into context:
on run {input, parameters}
# count the number of files
set numFiles to 0
repeat with f in input
# warn the user that folders are not processed in this app
tell application "Finder"
if (kind of f is "Folder") then
display dialog "The item: " & (f as text) & " is a folder. Only files are allowed. Do you want to continue processing files or do you want to cancel?"
else
set numFiles to numFiles + 1
end if
end tell
end repeat
# require that at least one file is being opened
if numFiles < 1 then
display alert "Error: the application Test1.app cannot be run because it requires at least one file as input"
error number -128
end if
# get the current directory from the first file
set theFirstFile to (item 1 of input)
tell application "System Events" to set theFolder to (container of theFirstFile)
# ask the user for a file name
set thefilename to text returned of (display dialog "Create file named:" default answer "filename")
# create the file
tell application "System Events" to set thefullpath to (POSIX path of theFolder) & "/" & thefilename
set theCommand to "touch \"" & thefullpath & "\""
do shell script theCommand
# return the input as the output
return input
end run
The "touch" command is OK. If the file doesn't exist, it is created and if it does exist, only the modification date is changed (which isn't too bad) but it doesn't overwrite the file. If your file is being overwritten, it's not the touch command that is doing it.
I changed the default file name to remove the extension ".txt" This extension may default to being opened by TextEdit.app, but you can change this in the Finder by choosing "Get Info" for a file and changing the "Open With" property. You can change which application opens the file with that extension or you can change them all. For example, all of my ".txt" files are opened with BBEdit.app
Will you vote my answer up?
Another option that doesn't require Finder or System Events is to try to coerce a POSIX file or file object to an alias:
try
POSIX file "/tmp/test" as alias
true
on error
false
end try

Getting the file name of files dropped on the script

I made this Applescript script to create symbolic links.
Appart from POSIX path of, how can I get the file name, without the path, of the dropped file?
on open filelist
repeat with i in filelist
do shell script "ln -s " & POSIX path of i & " /Users/me/Desktop/symlink"
end repeat
end open
PS: I know this expects many files to be dropped and tries to create many links with the same name, which gives an error. Actually I copied this example from a website and as I don't know almost anything about Applescript, I don't know how to do this for a single file, help on that would be appreciated too.
I'm not sure what precisely you're trying to do, but I have a guess. Is the idea that you want to take every file dropped on the script and create a symbolic link to each one on the Desktop? So if I drop ~/look/at/me and ~/an/example, you'll have ~/Desktop/me and ~/Desktop/example? If that's what you want, then you're in luck: ln -s <file1> <file2> ... <directory> does exactly that. (Edit: Although you have to watch out for the two-argument case.) Thus, your code could look like this:
-- EDITED: Added the conditional setting of `dest` to prevent errors in the
-- two-arguments-to-ln case (see my comment).
on quoted(f)
return quoted form of POSIX path of f
end quoted
on open filelist
if filelist is {} then return
set dest to missing value
if (count of filelist) is 1 then
tell application "System Events" to set n to the name of item 1 of filelist
set dest to (path to desktop as string) & n
else
set dest to path to desktop
end if
set cmd to "ln -s"
repeat with f in filelist & dest
set cmd to cmd & " " & quoted(f)
end repeat
do shell script cmd
end open
Note the use of quoted form of; it wraps its argument in single quotes so executing in in the shell won't do anything funny.
If you want to get at the name of the file for another reason, you don't need to call out to the Finder; you can use System Events instead:
tell application "System Events" to get name of myAlias
will return the name of the file stored in myAlias.
Edit: If you want to do something to a single file, it's pretty easy. Instead of using repeat to iterate over every file, just perform the same action on the first file, accessed by item 1 of theList. So in this case, you might want something like this:
-- EDITED: Fixed the "linking a directory" case (see my comment).
on quoted(f)
return quoted form of POSIX path of f
end quoted
on open filelist
if filelist is {} then return
set f to item 1 of filelist
tell application "System Events" to set n to the name of f
do shell script "ln -s " & ¬
quoted(f) & " " & quoted((path to desktop as string) & n)
end open
It's pretty much the same, but we grab the first item in filelist and ignore the rest. Additionally, at the end, we display a dialog containing the name of the symlink, so the user knows what just happened.
As an example, you can work with the Finder instead of a shell script to get the name of a single file that is dropped on the script that is saved as an application. If you don't need the display dialog, you can remove it, but you have the file name as a variable to work with:
on open the_files
repeat with i from 1 to the count of the_files
tell application "Finder"
set myFileName to name of (item i of the_files)
end tell
display dialog "The file's name is " & myFileName
end repeat
end open

Resources