#!/usr/bin/perl -w use strict; ## A small program to check and set the text attribute ## of a file for Spotlight. Uses Unix's 'file' utility. ## ## usage: tag-text-for-spotlight.pl [filename] ## ## effect: if the file doesn't already have a type, ## and if GetFileInfo identifies the file as ASCII text, ## we set the type attribute with SetFile. ## Executes a shell command in a slightly more careful way; should ## work even if arguments have spaces in them. sub safeExec { my ($cmd, @args) = @_; my $pid = open (CHILD, "-|"); if ($pid) { my @result = ; close(CHILD); return "@result"; } else { exec $cmd, @args; } } ## Sets the text attribute using Apple's SetFile. sub setTextAttribute { my ($filename) = @_; safeExec("/Developer/Tools/SetFile", "-t", "TEXT", $filename); } ## Returns true if this file's text metadata is already flagged as something. sub isAlreadyFlaggedAsSomething { my ($filename) = @_; my $results = safeExec("/Developer/Tools/GetFileInfo", "-t", $filename); if ($results =~ m/^""$/m) { return 0; } else { return 1; } } ## Returns true if the file appears to be ASCII text according to ## Unix 'find'. sub isText { my ($filename) = @_; my ($result) = safeExec("file", $filename); if ($result =~ m/ASCII text$/m) { return 1; } else { return 0; } } ## Main loop: go through all files, flagging those that don't have ## an associated type and look like ASCII. for my $filename (@ARGV) { if ((!isAlreadyFlaggedAsSomething($filename)) && isText($filename)) { print "Setting attribute on $filename\n"; setTextAttribute($filename); } }