Package or folder size


(Jonas Whale) #1

Why this code is always returning missing value with all kind of packages and folders?

use framework "Foundation"

set theURL to current application's NSURL's fileURLWithPath:"/Applications/"
set theWorkspace to current application's NSWorkspace's sharedWorkspace()
set {hasResult, theResult} to (theURL's getResourceValue:(reference) forKey:(current application's NSURLTotalFileAllocatedSizeKey) |error|:(missing value))

(Shane Stanley) #2

Because that value isn’t stored anywhere for directories — it has to be calculated from its contents.

This will return the same values as the Finder shows in a Get Info window:

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set theFolder to "/Users/shane/Desktop/"
set totalSize to its sizeOfFolder:theFolder
display dialog (its formatAsBytes:totalSize)

on sizeOfFolder:folderPosixPath
	set theURL to current application's |NSURL|'s fileURLWithPath:folderPosixPath
	set totalSize to 0
	set theEnumerator to current application's NSFileManager's defaultManager()'s enumeratorAtURL:theURL includingPropertiesForKeys:{current application's NSURLTotalFileSizeKey} options:0 errorHandler:(missing value)
	repeat with nextURL in theEnumerator's allObjects()
		set {hasResult, theResult} to (nextURL's getResourceValue:(reference) forKey:(current application's NSURLTotalFileSizeKey) |error|:(missing value))
		if theResult is not missing value then
			set totalSize to totalSize + (theResult as real)
		end if
	end repeat
	return totalSize
end sizeOfFolder:

on formatAsBytes:theValue
	set theNSByteCountFormatter to current application's NSByteCountFormatter's alloc()'s init()
	theNSByteCountFormatter's setIncludesActualByteCount:true
	theNSByteCountFormatter's setCountStyle:(current application's NSByteCountFormatterCountStyleFile)
	return (theNSByteCountFormatter's stringFromByteCount:theValue) as text
end formatAsBytes:

(Jonas Whale) #3

Thank you for adding the formatAsBytes handler.

No relation to the above:
I’m wondering why, when I make a call to a library (like Dialog Toolkit Plus) in a script that contains the term reference, this term is changed to specifier?
Is it problematic or not?

(Shane Stanley) #4

I don’t really know. It’s one of those AppleScript oddities.