macdevcenter.com
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Apache and AppleScript
Pages: 1, 2

Step 1: Initialize the Access File

In order to generate the comments for our web site, the very first thing we'll have to do is get a reference to the document root--we never move above this folder, only below. This folder could be /Library/WebServer/Documents, ~/Sites/, or, if you have a virtual host enabled on your machine, pretty much any directory in the filesystem. With AppleScript, specifying a reference to a folder at runtime can be done in one of two ways:



  1. By dragging a folder (or a series of folders) onto the droplet from within the Finder.
  2. By making a call to the choose folder function from within your script.

To allow both methods to be used, we will save the script as an application and create a subroutine that is invoked from each method handler, named appropriately enough, addComments:

(* invoked when files are dragged onto the script
within the Finder *)
on open (myfiles)
  tell application "Finder"
    repeat with i in myfiles
      my addComments(i)
    end repeat
  end tell
end open

(* invoked when the script is opened from the Finder
(either double-click, or via Script Menu *)
on run
  set myfile to choose folder
  my addComments(myfile)
end run
Dropping our web document folder onto the script's droplet for processing Figure 5. Dropping our web document folder onto the script's droplet for processing

The meat and potatoes of the script is contained within the addComments subroutine, although it relies on several other subroutines for assistance:

on addComments(myfile)
	
  set myPOSIX to (POSIX path of myfile as string)
	
  (* check to see if this is a folder*)
  if (my isFolder(myfile)) then
    tell application "Finder"
      (* make sure there's an access file in this 
       directory *)
      set accessfile to my prepareAccessFile(myPOSIX)

      (* add a description for the parent folder *)
      set myparent to parent of myfile
      my addDescription(accessfile,"..",comment of myparent)

      (* add a description for every file/folder... *)
      set myfiles to items of myfile
      repeat with i in myfiles
        set m to i as alias
        (* add an entry for it in the access file *)
        my addDescription(accessfile,name of i,comment of i)

  (* and repeat this process with it if its a subfolder *)
        if (my isFolder(m)) then
          my addComments(m)
        end if
      end repeat

    end tell

  (* if it's not a folder, then ignore it*)
  end if
end addComments

The addComments routine is invoked with every file that is contained in the document tree of our web site. And with each parameter that is passed to the routine, in addition to the file's parent directory (denoted by ..), an AddDescription directive is added to the Apache access file residing in the file's directory. But before the description is added to the access file, we must ensure that there is an access file in place. Which turns out to be more complicated than it sounds.

Preparing the access file can take one of two courses:

  • If the access file exists (whether it was manually created or through a previous execution of this script), then all of the AddDescription directives that it contains will have to be deleted. However, because there is the possibility that it may contain other directives, all other directives will have to remain untouched.
  • If the file doesn't exist, then a blank file will need to be created so that it can be populated.

This step is where the script becomes more complex than your run-of-the-mill AppleScript:

(* checks to see if a folder has a ACCESS_FILE in it;
   if yes, then formats it to start from scratch,
   if not then creates one *)
on prepareAccessFile(myPOSIX)

  (* get the path name that we will be testing *)	
  set myaccess to (myPOSIX as string) & ACCESS_FILENAME
  set accessposix to myaccess as POSIX file
	
  (* checks to see if the access file already exists *)
  if (my hasAccessFile(myPOSIX)) then
    set myScript to
      ("perl -pi -e \"s/^(.*AddDescription.*)//sg\" ") &
      (quoted form of POSIX path of accessposix as string)
    do shell script myScript
  else
    (* if no access file exists, then make one *)
    my makeAccessFile(myPOSIX)
  end if
	
  return accessposix
	
end prepareAccessFile

The first step is to determine whether or not an access file exists, which is accomplished via the hasAccessFile routine. This routine returns a Boolean indicating whether or not an access file already exists in the directory:

(* returns true if the given folder has an ACCESS_FILE in 
 it *)
on hasAccessFile(posixFolder)
  set myListing to do shell script "ls -a " &
    quoted form of posixFolder
  return (myListing contains ACCESS_FILENAME)
end hasAccessFile

The traditional way of doing this would be to tell the Finder to get a list of all of the items in the folder and see if that list contains the access file. However, because our access files are hidden by the Finder (that is, they begin with a .), the Finder won't include it in the list of files. This can be remedied by using one of the various hacks (such as this one) to instruct the Finder to list all files in a directory. But to avoid such trickery, we'll use the shell to leave the Finder's preferences intact. ls, of course, is the UNIX command to list all files in a directory, and the -a flag will tell the command to include all files in the listing, even hidden ones.

If the access file exists, then all AddDescription directives contained within it must be deleted, as they may contain descriptions that are out of date. There are several ways of accomplishing this step, each with its own pros and cons:

  • AppleScript has the capability to manipulate the contents of text files (through reading and writing), but it is by no means an easy task to do. Third-party extensions (also known as "osax" for "Open Scripting Architecture eXtension") that add regular expression capabilities to simplify the task are available, but require installation and often have licensing fees.
  • Using the AppleScript functionality of a text editor (such as BBEdit) will make our task easier, but again, this method will require the application to be installed on the computer where the script will run.
  • Another way of accomplishing this step is to make use of OS X's UNIX foundation; command-line tools are typically built solely to manipulate files and text. The only downside to this method is the complexity in creating the UNIX command.

After all of the discussion earlier in the article regarding AppleScript and UNIX, it should come as no surprise that the third method was chosen: it is the only way to accomplish the task at hand without requiring some kind of extension, whether it be a scripting addition or application.

The following statements will do exactly what we need:

 set myScript to
  ("perl -pi -e \"s/^(.*AddDescription.*)//sg\" ") &
  (quoted form of POSIX path of accessposix as string)
 do shell script myScript

For those in the audience that don't happen to be Perl hackers--I happen to fall into this category myself--the above command will use the Perl interpreter to scan through the access file and remove all lines that contain the string AddDescription (as shown in Geoffrey Bradwell's article, "FMTYEWTK About Mass Edits In Perl"). We now have a fresh access file devoid of AddDescription directives, assuming it existed before running our script.

But what happens if it doesn't exist? Well, we're going to have go ahead and create it, and that's what the makeAccessFile routine takes care of:

(* creates an ACCESS_FILE in the given directory *)
on makeAccessFile(posixPath)
  
  (* build the path where the file should be located *)
  set myquoted to quoted form of posixPath
  set myquoted to (characters 1 thru
    ((length of myquoted) - 1) of myquoted)
  set mypath to
    (myquoted & ACCESS_FILENAME & "'") as string
  
  (* create the file *)
  do shell script "touch " & mypath &
    "; chmod 744 " & mypath
  (* ensure the proper permissions are set *)
  do shell script "chmod 744 " & mypath
  
  (* and add a comment indicating when it was generated*)
  set myScript to "echo \"" & ACCESS_COMMENT &
    "\" >> " & mypath
  do shell script myScript
  
end makeAccessFile

This routine takes a similar route to creating the access file: instead of telling the Finder to create the file, the UNIX command touch is used, and then the proper permissions are set on the file. The last call to do shell script merely adds a comment to the top of the file to mark when and how the file was created.

There are only two things left to do: add the actual AddDescription directives to the access file for each file, and then recursively invoke addComments with any sub-folders of the current folder. And thankfully, both steps are much simpler than the code we just walked through.

Steps 2 and 3. Create the AddDescription Directive and Recurse

The next block of code in the addComments routine is the following:

repeat with i in myfiles
  set m to i as alias
  my addDescription(accessfile, name of i, comment of i)
  if (my isFolder(m)) then
    my addComments(m)
  end if
end repeat

The above block accomplishes the first and second steps of our algorithm--add the comments for the current file and then dig down into it if it's a folder. The addDescription routine is shown below:

(* adds an AddDescription directive into the
   specified access file *)
on addDescription(accessposix, fileName, comments)
	
  set mypath to POSIX path of accessposix
  set myquote to quoted form of mypath

  if (comments is not equal to "") then
    set myScript to "echo \"AddDescription \\\"" &
    my urlencode(comments) & "\\\" \\\"" & 
    my escape(fileName) & "\\\" \" >> " & (myquote)
		
    set a to do shell script (myScript)
  end if
end addDescription

Again, we are using a UNIX command to add the directive to the end of the access file; the name of the file is escaped (in case it contains a quote, backslash, or another misbehaving character) and the comment is URL-encoded.

Several sections of the script weren't covered in this article (such as the urlencode and urlescape routines for embedding the filename and its comment within the UNIX command); rest assured that they aren't directly involved in the script's functionality.

Putting the Script to Use

We've walked through the code for the script; now let's see it in action. The following files all reside in the same folder within my web document root (/Library/WebServer/Documents), and each have a comment applied to them through the Finder's Get Info window:

Setting comments for the files in a folder of our web document folder Figure 6. Setting comments for the files in a folder of our web document folder

And the following is the index page generated by Apache, which uses the information covered in my previous article "Mo' Betta Indexes" and the access files generated by the script:

The result of all our hard work Figure 7. The result of all of our hard work. Click for a larger version.

Although a lot of effort has been expended in to create this one index page, we can now leverage our toolset to create as many pages as we want and have most of the content generated for us, not by us. All we have to do is click a couple of buttons here and there.

Final Thoughts

In this article, we put AppleScript to use in a way that it was not originally designed to be used. While many developers trained in high-level languages such as Java and C despise AppleScript because of its verbose and unstructured syntax, it still plays an integral role within OS X. And with the release of Automator in the next version of OS X, scripters are going to be able to build even more complex tools to suit their needs.

David Miller is combining his passions of photography and working on the web at iStockphoto; when not hacking away with a text editor and a few web browsers in hand, he can be seen huddled over his laptop tweaking levels and curves for his freelance photography. Keep track of David's latest projects over at his home on the web.


Return to MacDevCenter.com.