Changing a file in a disk image

Ever wanted to change a file in a disk image, perhaps to update a ‘readmefirst’ or move in a new version of a script? Here’s a script I cobbled together that will do it:


--set f to "path to .dmg to be changed"
--set nF to alias "path to file to replace one of same name in .dmg"

set tDMG to do shell script "hdiutil attach  " & POSIX path of f -- mounts the image, returns path
-- The advantage of the hdiutil approach over simply Finder-mounting the image is that you don't have to include a repeat loop to wait for the image to mount before proceeding.
set tName to word -1 of tDMG -- the name of the image
-- do the swap
tell application "Finder"
	set af to files of disk tName as alias list
	-- assumes the one you want is at top level - otherwise dig for it
	set tmp to (make new folder at (path to desktop folder) with properties {name:tName}) as alias
	duplicate af to tmp with replacing -- move the contents of the old dmg to the folder
	duplicate nF to tmp with replacing -- make the swap in the folder
end tell
tell application "Finder" to eject disk tName -- toss the mounted image (or you can't replace it)

do shell script "hdiutil create -srcfolder " & POSIX path of tmp & " ~/Desktop/" & tName
-- this makes a new image with the contents and name of the temp folder

tell application "Finder" to delete tmp -- toss the temp folder

-- at this point you would move the .dmg from the desktop back where it was with replacing. I didn't do that with my test .dmg