isDone()

This a handler to return the “done writing” status of a file. Works on file writes of all kinds; saving or copying - local or WAN. Returns the “Done” status as well as current data size of the file.

OS version: OS X

(*
isDone()
Checks if a file has finished writing to disk.

Parameters:
File2Check: file path, alias, posix path
LastFileSize: initialize with -1; seed each subsequent call with the return of the previous LastFileSize

Returns:
	2 item list:
		item 1 - true or false
		item 2 - the CurrentFileSize as integer++
		         (++ returns -1 if file does not exist)
Examples:
isDone("path:to:file.txt", -1) --> {false, 6207} == file not done.
isDone("path:to:file.txt", 39402708) --> {false, -1} == file write aborted???
isDone("path:to:file.txt", LastFileSize) --> {true, 564689207} == file is done.

written by Jeff Case 2004
*)

property StillGrowing : null
property CurrentFileSize : null
--property File2Check : "JData:Downloads:LakeGenevaCover.psd"
--property LastFileSize : -1
on run {File2Check, LastFileSize}
	tell application "Finder"
		if alias File2Check exists then
		else
			return {false, -1}
		end if
	end tell
	set File2Check to File2Check as Unicode text
	set StillOpen to isOpen(File2Check)
	isGrowing(File2Check, LastFileSize)
	if StillGrowing is false then
		return {true, CurrentFileSize}
	else
		return {false, CurrentFileSize}
	end if
	
	if StillOpen is false and StillGrowing is false then
		return {true, CurrentFileSize}
	else
		return {false, CurrentFileSize}
	end if
	
end run

on isOpen(File2Check)
	-- check the "open" status of the file
	-- thanks to captnswing for the 'lsof' command
	-- works on SMB transfers
	set ItzOpen to ((do shell script ("echo `lsof " & (quoted form of (POSIX path of (File2Check))) & " | wc -l`")) as integer)
	if ItzOpen = 0 then
		return false
	else
		return true
	end if
end isOpen

on isGrowing(File2Check, LastFileSize)
	-- parse the return of "ls" for the current file size - NOT the Finder
	-- sometimes it reports back as 0 even though some data has written
	-- so this waits for a valid "size" report from "ls"
	-- "ls" more responsive and reliable than a Finder query
	set CurrentFileSize to 0
	repeat while CurrentFileSize is 0
		set LSreturn to do shell script ("ls -l " & (quoted form of (POSIX path of alias (File2Check))))
		set AppleScript's text item delimiters to "  "
		set CurrentFileSize to (text item 4 of LSreturn)
		set AppleScript's text item delimiters to " "
		set CurrentFileSize to ((text item 1 of CurrentFileSize) as string) as integer
		set AppleScript's text item delimiters to ""
	end repeat
	set AppleScript's text item delimiters to ""
	if CurrentFileSize > LastFileSize then
		set StillGrowing to true
	else
		set StillGrowing to false
	end if
end isGrowing