MacOS – How to restart a currently-running application with AppleScript

applescriptautomatormacos

I've created an application with a "Run AppleScript" action in Automator.

I've created a Service in Automator which launches the aforementioned app.

The Service is triggered by a keyboard shortcut, assigned in System Preferences

The application presents a series of dialogs to the user. I would like to give the user the option of restarting the entire application mid-application. For example, suppose that the following line was Line 100 of the code:

set buttonChoice to button returned of (display alert "Do you want to replace this entry?" as critical buttons {"Start over", "No", "Yes"})

   if buttonChoice is "Start over" then     
      <this is where I need your help, Ask Different>
   end if

When I say "restart" or "start over," I mean that I want to return the user to the initial dialog of the application, that is, the very first line of code of the application.

Can this be done using AppleScript?

If needed, this is the location of the application file:

/Applications/My Applications/My Log.app

Best Answer

The following code example assume that the Run AppleScript action starts with an on run command without any list, e.g. {input, parameters} and consequently ends the script with end run:

on run

    (*
            This comment represents the e.g. previous 99 lines of code.
        *)

    set buttonChoice to button returned of (display alert "Do you want to replace this entry?" as critical buttons {"Start over", "No", "Yes"})
    try
        if buttonChoice is "Start over" then
            return on run
        end if
    end try

    (*
            This comment represents the rest of the code in the script.
        *)

end run

Note that I tested this in macOS Sierra 10.12 and while it does appear to start over, because if you press the "Start over" button it loops until you select another choice, I'm not sure this is the best way to implement this. I say that because I do not know the structure and coding of the rest of the script and that may make a difference along with the fact that while testing other code on each side of this, I was able to crash the app depending on what was going on if I looped more then once at this point.

So with that said, I'm offering this as something to test throughly before implementing it in the final code.

I'd suggest just allowing the user to terminate the app with a message to manually restart by pressing the key-combo to trigger the service that starts the app over implementing a loop such as this.