ashtml
version 0.2
Requires Mac OS X 10.4 or higher


HAMSoft Engineering allows free use of this code and/or software in its "as is" condition. HAMSoft Engineering disclaims any liability of any kind for any damages whatsoever resulting from the use of this code and/or software. If you find it useful please consider making a donation to help HAMSoft Engineering stay in business.

download the compiled command line tool

Thank you to Martin Michel who posted the code for this on the MacScripter website.
I have made a few modifications to the code and am posting those here.
You can see the original post
here.

With this code you can create a command line tool which will convert an applescript script or application
into an html document suitable for posting as a web page. Formatting and coloring of the script
is preserved in the html file.

Version 0.2 mods are as follows:
1. added a check for a help flag (i.e. -h) such that the basic usage of the tool is written to stdOut
2. added support for “scptd” files. Previously they were seen as directories and thus would not process.


Source Code for ashtml.m:

//

// created 03.05.2009 by Martin Michel

// modified 06.11.2009 by Hank McShane

// version: 0.2

// requires: Mac OS X 10.4 or higher

// http://macscripter.net/viewtopic.php?id=29142


// Usage:

// ashtml -input /path/to/applescript/file -output /path/to/HTML/file


// This foundation tool converts AppleScript code to an HTML document.

// If you do not specify an output path for the HTML document, then ashtml

// saves the HTML document in the same directory as the original

// AppleScript file with the same name and with an html file extension:

// ../Folder/example.scpt -> ../Folder/example.html

// The application will not replace existing HTML files.


#import <Foundation/Foundation.h>

#import <AppKit/AppKit.h>

#import <ScreenSaver/ScreenSaver.h>


// Returns the file path of an unused temporary file

// (e.g. /var/folders/NU/.../1023.tmp)

NSString *getTempFilePath (NSString *extension) {

NSString *tempDirectory = NSTemporaryDirectory();

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *tempFilePath;

BOOL pathExists = YES;

while (pathExists == YES) {

// creating a random integer value between 1000 and 9999 with

// a convenient function found in the ScreenSaver framework

int randnum = SSRandomIntBetween(1000, 9999);

// e.g. /TemporaryDirectory/8765.tmp

tempFilePath = [NSString stringWithFormat:@"%@%d.%@", tempDirectory, randnum, extension];

if ([fileManager fileExistsAtPath:tempFilePath] == NO) {

pathExists = NO;

}

}

// tempFilePath is an autoreleased object (created with [NSSString stringWithFormat])

return tempFilePath;

}


// converts the source code of an AppleScript file to an HTML document

int main (int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

// see if help is being requested

NSArray* pInfo = [[NSArray alloc] initWithArray:[[NSProcessInfo processInfo] arguments]];

if ([pInfo count] == 1 || [[pInfo objectAtIndex:1] isEqualToString:@"h"] || [[pInfo objectAtIndex:1] isEqualToString:@"-h"]) {

printf("Usage:\nashtml -input /path/to/applescript/file -output /path/to/HTML/file\n\nThis foundation tool converts AppleScript code to an HTML document.\nIf you do not specify an output path for the HTML document, then ashtml\nsaves the HTML document in the same directory as the original\nAppleScript file with the same name and with an html file extension.\n\nNote: The application will not replace existing HTML files.\n\n");

return 1;

}

[pInfo release];

// reading the command line arguments

NSString* asFilePath = [[NSUserDefaults standardUserDefaults] stringForKey:@"input"];

if (asFilePath == NULL) {

printf("ERROR: Missing AppleScript file\n");

return 1;

}

// does the given AppleScript file path really exist or point to a directory?

NSFileManager* fileManager = [NSFileManager defaultManager];

BOOL isDir;

if ([fileManager fileExistsAtPath:asFilePath isDirectory:&isDir] == NO) {

printf("ERROR: The AppleScript file path does not exist: %s\n", [asFilePath UTF8String]);

return 1;

} else {

if ((isDir == YES) && (([asFilePath hasSuffix:@".app"] == NO) && ([asFilePath hasSuffix:@".app/"] == NO) && ([asFilePath hasSuffix:@".scptd"] == NO))) {

printf("ERROR: The AppleScript path points to a directory: %s\n", [asFilePath UTF8String]);

return 1;

}

}

// initializing the AppleScript object

NSURL* asFileURL = [NSURL fileURLWithPath:asFilePath];

NSDictionary* asErrorDict;

NSAppleScript* appleScript = [[NSAppleScript alloc] initWithContentsOfURL:asFileURL error:&asErrorDict];

if (appleScript == nil) {

NSString* asErrorMessage = [asErrorDict objectForKey:@"NSAppleScriptErrorMessage"];

printf("ERROR: Could not create an AppleScript object from the given file:\n%s\n%s\n", [asFilePath UTF8String], [asErrorMessage UTF8String]);

return 1;

}

// can we successfully compile the AppleScript code?

BOOL asCompileSuccess = [appleScript compileAndReturnError:&asErrorDict];

if (asCompileSuccess == NO) {

NSString* asErrorMessage = [asErrorDict objectForKey:@"NSAppleScriptErrorMessage"];

printf("ERROR: Could not compile the code from the given AppleScript file:\n%s\n%s\n", [asFilePath UTF8String], [asErrorMessage UTF8String]);

return 1;

}

// getting the AppleScript source code as rich text

NSAttributedString* appleScriptCode = [appleScript richTextSource];

[appleScript release];

// conversion to RTF

NSData* rtfData = [appleScriptCode RTFFromRange:NSMakeRange(0, [appleScriptCode length]) documentAttributes:nil];

NSString* tmpFilePath = getTempFilePath(@"rtf");

BOOL rtfWriteSuccess = [rtfData writeToFile:tmpFilePath atomically:NO];

if (rtfWriteSuccess == NO) {

printf("ERROR: Could not write temporary RTF file: %s\n", [tmpFilePath UTF8String]);

return 1;

}

// determining the output path for the HTML file

NSString* htmlFilePath = [[NSUserDefaults standardUserDefaults] stringForKey:@"output"];

if (htmlFilePath == nil || [htmlFilePath isEqualToString:@""]) {

if ([asFilePath hasSuffix:@".scpt"] == YES) {

htmlFilePath = [[asFilePath stringByDeletingPathExtension] stringByAppendingPathExtension:@"html"];

} else if ([asFilePath hasSuffix:@".scptd"] == YES) {

htmlFilePath = [[asFilePath stringByDeletingPathExtension] stringByAppendingPathExtension:@"html"];

} else if ([asFilePath hasSuffix:@".applescript"] == YES) {

htmlFilePath = [[asFilePath stringByDeletingPathExtension] stringByAppendingPathExtension:@"html"];

} else if ([asFilePath hasSuffix:@".app"] == YES) {

htmlFilePath = [[asFilePath stringByDeletingPathExtension] stringByAppendingPathExtension:@"html"];

} else if ([asFilePath hasSuffix:@".app/"] == YES) {

htmlFilePath = [[asFilePath stringByDeletingPathExtension] stringByAppendingPathExtension:@"html"];

} else if ([asFilePath hasSuffix:@"."] == YES) {

htmlFilePath = [asFilePath stringByAppendingString:@"html"];

} else {

htmlFilePath = [asFilePath stringByAppendingString:@".html"];

}

}

// check if the html file path exists

if ([fileManager fileExistsAtPath:htmlFilePath]) {

printf("ERROR: The HTML file already exists: %s\n", [htmlFilePath UTF8String]);

return 1;

}

// convert the temporary RTF file to HTML using the built-in textutil command line tool

NSTask* shellCommand = [[NSTask alloc] init];

[shellCommand setLaunchPath:@"/usr/bin/textutil"];

[shellCommand setArguments:[NSArray arrayWithObjects:@"-convert", @"html", @"-output", htmlFilePath, tmpFilePath, nil]];

[shellCommand launch];

[shellCommand waitUntilExit];

int status = [shellCommand terminationStatus];

if (status != 0) {

printf("ERROR: The temporary RTF file could not be converted to HTML.\n");

[fileManager removeFileAtPath:tmpFilePath handler:nil];

return 1;

}

[shellCommand release];

// delete the temp rtf file

BOOL removeFileSuccess = [fileManager removeFileAtPath:tmpFilePath handler:nil];

if (removeFileSuccess == NO) {

printf("Warning: The temporary RTF file could not be removed: %s\n", [tmpFilePath UTF8String]);

}

    [pool drain];

    return 0;

}



Example usage of the tool with applescript:
Open this Script in your Editor

set ashtmlPath to (path to home folder as text) & "UnixBins:ashtml"

set scriptPath to choose file with prompt "Choose the applescript file to convert:" without invisibles

set applescriptName to item 1 of (getName_andExtension(scriptPath))

tell application "Finder" to set applescriptContainerFolder to container of scriptPath

set outputPath to choose file name with prompt "Where do you want the output HTML file saved:" default name (applescriptName & ".html") default location (applescriptContainerFolder as alias)


try

do shell script quoted form of POSIX path of ashtmlPath & space & "-input " & quoted form of POSIX path of scriptPath & space & "-output " & quoted form of POSIX path of outputPath

on error theError number errorNumber

tell me

activate

display dialog "There was an error:" & return & theError & return & return & "Error Number: " & errorNumber as text buttons {"OK"} default button 1 with icon stop

end tell

end try


(*=========== SUBROUTINES ============*)

on getName_andExtension(F)

set F to F as Unicode text

set {name:Nm, name extension:Ex} to info for file F

if Ex is missing value then set Ex to ""

if Ex is not "" then

set Nm to text 1 thru ((count Nm) - (count Ex) - 1) of Nm

set Ex to "." & Ex

end if

return {Nm, Ex}

end getName_andExtension