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.
Not tested on files > 1GB

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, is the file finished writing
		item 2 - the CurrentFileSize as integer
Examples:
isDone("path:to:file.txt", -1) --> {false, 6207}
isDone("path:to:file.txt", 39402708) --> {false, 42402708}
isDone("path:to:file.txt", LastFileSize) --> {true, 564689207}

written by Jeff Case & Julio J Sancho 2004
*)


property StillGrowing : null
property CurrentFileSize : null
on run {File2Check, LastFileSize}
	set File2Check to File2Check as Unicode text
	set StillBusy to isBusy(File2Check)
	isGrowing(File2Check, LastFileSize)
	if StillBusy is false and StillGrowing is false then
		return {true, CurrentFileSize}
	else
		return {false, CurrentFileSize}
	end if
end run

on isBusy(File2Check)
	-- isBusy() written by Julio J. Sancho
	set File2Check to File2Check as Unicode text
	if File2Check does not contain ":" then set File2Check to POSIX file File2Check as Unicode text
	
	if busy status of (info for alias File2Check) then return true
	
	--> but some times this is not good enough
	try
		open for access file File2Check with write permission
		close access result
		return false
	on error
		return true
	end try
end isBusy

on isGrowing(f, LastFileSize)
	-- isGrowing() written by Jeff Case
	-- 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 (f))))
		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