Creating a .DMG - macos

I want to create a dmg file for my Mac project. Can someone please tell me how to do this? This being my first Mac project, I do not have any idea how to proceed. I also want to give the user an option of running the app on start-up. How do I do this?
Thanks.
P.S. I also want to add a custom license agreement.

To do this manually:
Method 1:
Make a folder with the files your DMG will contain.
Open Disk Utility (It's in /Applications/Utilities/)
Go to File > New > New Image from Folder (Cmd + Shift + N)
Choose the folder containing you files
Make sure "Compressed" is checked, then set where you want to save the created DMG
Method 2:
To do things like setting a background image can be a bit convoluted (You basically add the background image to the DMG, set the windows properties to use that image, using the command line you move the background image from background.png to .background.png to make it hidden)
I would recommend iDMG, which makes things a bit less tedious.
You can also script the creation of DMGs using the command hdiutil. Something along the lines of
hdiutil create -srcfolder mydirtodmg mydmg.dmg
As for the custom license agreement, you should look into the tool included with the Developer Tools "PackageMaker" - it's pretty self-explanatory. It's in /Developers/Application/Utilities/

If you need to add a custom EULA to your disk image, this page describes how to do so using command-line tools. The gist of it is to use the template software licensing agreement resource provided in Apple's slas_for_udifs_1.0.dmg, modify the resource with your EULA text and inject the resource back into your disk image file. (I include brief instructions below in case the above link becomes unavailable, and to update the search term it provides in step 1.)
Using your Apple Developer account go to the Downloads page and search for Software Licensing for UDIF
Download and mount the disk image
In Terminal:
cd /Volumes/SLAs_for_UDIFs_1.0
DeRez SLAResources > /tmp/sla.r
Edit /tmp/sla.r in a text editor, updating the content of the data 'TEXT' (5000, "English SLA") resource to contain your new license text.
Unflatten the disk image file that contains your installer:
hdiutil unflatten installer_image.dmg
Add the edited license resources to the image:
Rez -a /tmp/sla.r -o installer_image.dmg

why don't you just run a script from your xcode project. try something like this:
# be sure to check the man page for hdiutil
# it is very powerful and has tons of options...
hdiutil create -megabytes 54 -fs HFS+ -volname awesome_app_install myAwesomeApplication.dmg
hdiutil mount myAwesomeApplication.dmg
cp -r /build/Release/AwesomeApplication.app /Volumes/awesome_app_install/
then save your script as something like 'makeDMG.sh' and in your target,
select add->new build phase->run script build phase
and drag your script into this build phase.
once you've done all that, then when you build your project the script will create the disk image and copy your release build into it...
of course you should spice your script to flavor... these three lines are just the raw meat
ps: your custom EULA should get built into your packagemaker project (which you can also script very nicely)

I made a little bash script to automate a disc image creation.
It creates a temporary directory to store all needed files then export it in a new DMG file. Temporary directory is then deleted.
You can automatically launch this script at the end of your build process.
#!/bin/bash
# Create .dmg file for macOS
# Adapt these variables to your needs
APP_VERS="1.0"
DMG_NAME="MyApp_v${APP_VERS}_macos"
OUTPUT_DMG_DIR="path_to_output_dmg_file"
APP_FILE="path_to_my_app/MyApp.app"
OTHER_FILES_TO_INCLUDE="path_to_other_files"
# The directory of the script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# The temp directory used, within $DIR
WORK_DIR=`mktemp -d "${DIR}/tmp"`
# Check if tmp dir was created
if [[ ! "${WORK_DIR}" || ! -d "${WORK_DIR}" ]]; then
echo "Could not create temp dir"
exit 1
fi
# Function to deletes the temp directory
function cleanup {
rm -rf "${WORK_DIR}"
#echo "Deleted temp working directory ${WORK_DIR}"
}
# Register the cleanup function to be called on the EXIT signal
trap cleanup EXIT
# Copy application on temp dir
cp -R "${APP_FILE}" "${WORK_DIR}"
# Copy other files without hidden files
rsync -a --exclude=".*" "${OTHER_FILES_TO_INCLUDE}" "${WORK_DIR}"
# Create .dmg
hdiutil create -volname "${DMG_NAME}" -srcfolder "${WORK_DIR}" -ov -format UDZO "${OUTPUT_DMG_DIR}/${DMG_NAME}.dmg"

Related

Alternatives to Platypus (which builds a mac .app that runs a script when user double clicks it), which run on Linux?

I already have software which runs on mac, which can be driven by a main 'runner' script. However, I want the software to be packaged as a .app. On a mac, I can run 'platypus' (https://www.sveinbjorn.org/platypus), and it will create a very nice .app file, which calls that runner script as an entry point (exactly what I am trying to do). It's very simple to use.
The problem is, platypus itself only runs on mac, and I need to bundle this all together (create the .app), on a Linux machine.
Is there an alternative to Platypus, which accomplishes the same result (generates a .app, with a script as the entrypoint), but which you can build on Linux? Or, is anyone aware of up-to date tutorial which explains how to accomplish this manually (but on Linux)?
(I've seen this: How to build a dmg Mac OS X file (on a non-Mac platform)? but it is for dmg files, while I need a .app file. Also, I'm specifically curious about programs simple like Platypus is.)
A mac .app "file" is actually just a folder (you can browse the contents by right clicking, "show package contents".
The main part you'd need to change is the .sh script itself which can be found within the app package: yourapp.app/Contents/MacOS/yourscript.sh
So you could copy an existing yourapp.app and use it as a template, just editing the script contents and app (folder) name all within Linux.
You might have to set permissions when copying back (chmod +x etc.).. I'm not sure having not tested this method, but I can't see why it wouldn't work.
Adding some reference code (bash), on top of BSUK answer:
mkdir -p foo.app/Contents/MacOS
cp foo.sh foo.app/Contents/MacOS/foo
chmod +x foo.app/Contents/MacOS/foo
It's also possible to set a nice icon for the app, with the following reference code:
(please prepare in advance a logo.png file, and its corresponding icon.icns version):
mkdir -p foo.app/Contents/Resources
cp icon.icns foo.app/Contents/Resources/
cp logo.png ./
sips -i logo.png
DeRez -only icns logo.png > tmpicns.rsrc
Rez -append tmpicns.rsrc -o file.ext
SetFile -a C file.ext
cp -f file.ext foo.app/Icon$'\r'
rm tmpicns.rsrc logo.png file.ext
SetFile -a C foo.app
You may then allocate that foo.app on your desktop (for example) with:
mv foo.app "/Users/$(whoami)/Desktop/"

Apple Automator workflow to paste file in .ipa package and then re-sign it using code sign

I've got a packaged .ipa package as a basis for this task.
This I'd like to select and then run the Automator service to do the work for me.
These are the steps the service needs to to:
Rename the input's .ipa to .zip
Extract the zip archive
The extracted archive contains a single directory (Payload) with a single .app file in it.
The service somehow needs to open this .app file. In Finder you simply say "Show Package contents".
Inside the .app package I need to paste a file. Ideally this should have been asked by the Service in the very beginning.
Use codesign to sign the .app package again. Codesign needs a parameter (the certificate to use) as well. This should be asked by the service as well (it's just a String value that needs to be identical to a key in the keystore).
Zip the Payload again
Delete the original file.
Rename the Payload.zip to the original file's name.ipa
Pretty big task and I'm not sure if that can be accomplished with Automator.
Since I've never worked with it, I'm pretty much stuck already at point 3.
I can do all these steps manually, but I'd really have this automated.
As I said, steps 1 and 2 are done using "Rename Finder Items" and "Open Finder Items".
Input value is the selected file in Finder.
If necessary, this can be split into two parts or so if one service isn't going to be able to do this.
Any help would be highly appreciated!
You might just use a shell script like this:
for f; do
temp=/tmp/$(uuidgen)
mkdir $temp
cd $temp
unzip "$f"
cp /path/to/file Payload/*.app
codesign -s /path/to/certificate Payload/*.app
rm "$f"
zip -r "$f" Payload
rm -r $temp
done

Mac zip compress without __MACOSX folder?

When I compress files with the built in zip compressor in Mac OSX, it causes an extra folder titled "__MACOSX" to be created in the extracted zip.
Can I adjust my settings to keep this folder from being created or do I need to purchase a third party compression tool?
UPDATE: I just found a freeware app for OSX that solves my problem: "YemuZip"
UPDATE 2: YemuZip is no longer freeware.
Can be fixed after the fact by zip -d filename.zip __MACOSX/\*
And, to also delete .DS_Store files: zip -d filename.zip \*/.DS_Store
When I had this problem I've done it from command line:
zip file.zip uncompressed
EDIT, after many downvotes: I was using this option for some time ago and I don't know where I learnt it, so I can't give you a better explanation. Chris Johnson's answer is correct, but I won't delete mine. As one comment says, it's more accurate to what OP is asking, as it compress without those files, instead of removing them from a compressed file. I find it easier to remember, too.
Inside the folder you want to be compressed, in terminal:
zip -r -X Archive.zip *
Where -X means: Exclude those invisible Mac resource files such as “_MACOSX” or “._Filename” and .ds store files
source
Note: Will only work for the folder and subsequent folder tree you are in and has to have the * wildcard.
This command did it for me:
zip -r Target.zip Source -x "*.DS_Store"
Target.zip is the zip file to create. Source is the source file/folder to zip up. The -x parameter specifies the file/folder to exclude.
If the above doesn't work for whatever reason, try this instead:
zip -r Target.zip Source -x "*.DS_Store" -x "__MACOSX"
I'm using this Automator Shell Script to fix it after.
It's showing up as contextual menu item (right clicking on any file showing up in Finder).
while read -r p; do
zip -d "$p" __MACOSX/\* || true
zip -d "$p" \*/.DS_Store || true
done
Create a new Service with Automator
Select "Files and Folders" in "Finder"
Add a "Shell Script Action"
zip -r "$destFileName.zip" "$srcFileName" -x "*/\__MACOSX" -x "*/\.*"
-x "*/\__MACOSX": ignore __MACOSX as you mention.
-x "*/\.*": ignore any hidden file, such as .DS_Store .
Quote the variable to avoid file if it's named with SPACE.
Also, you can build Automator Service to make it easily to use in Finder.
Check link below to see detail if you need.
Github
The unwanted folders can be also be deleted by the following way:
zip -d filename.zip "__MACOSX*"
Works best for me
The zip command line utility never creates a __MACOSX directory, so you can just run a command like this:
zip directory.zip -x \*.DS_Store -r directory
In the output below, a.zip which I created with the zip command line utility does not contain a __MACOSX directory, but a 2.zip which I created from Finder does.
$ touch a
$ xattr -w somekey somevalue a
$ zip a.zip a
adding: a (stored 0%)
$ unzip -l a.zip
Archive: a.zip
Length Date Time Name
-------- ---- ---- ----
0 01-02-16 20:29 a
-------- -------
0 1 file
$ unzip -l a\ 2.zip # I created `a 2.zip` from Finder before this
Archive: a 2.zip
Length Date Time Name
-------- ---- ---- ----
0 01-02-16 20:29 a
0 01-02-16 20:31 __MACOSX/
149 01-02-16 20:29 __MACOSX/._a
-------- -------
149 3 files
-x .DS_Store does not exclude .DS_Store files inside directories but -x \*.DS_Store does.
The top level file of a zip archive with multiple files should usually be a single directory, because if it is not, some unarchiving utilites (like unzip and 7z, but not Archive Utility, The Unarchiver, unar, or dtrx) do not create a containing directory for the files when the archive is extracted, which often makes the files difficult to find, and if multiple archives like that are extracted at the same time, it can be difficult to tell which files belong to which archive.
Archive Utility only creates a __MACOSX directory when you create an archive where at least one file contains metadata such as extended attributes, file flags, or a resource fork. The __MACOSX directory contains AppleDouble files whose filename starts with ._ that are used to store OS X-specific metadata. The zip command line utility discards metadata such as extended attributes, file flags, and resource forks, which also means that metadata such as tags is lost, and that aliases stop working, because the information in an alias file is stored in a resource fork.
Normally you can just discard the OS X-specific metadata, but to see what metadata files contain, you can use xattr -l. xattr also includes resource forks and file flags, because even though they are not actually stored as extended attributes, they can be accessed through the extended attributes interface. Both Archive Utility and the zip command line utility discard ACLs.
You can't.
But what you can do is delete those unwanted folders after zipping. Command line zip takes different arguments where one, the -d, is for deleting contents based on a regex. So you can use it like this:
zip -d filename.zip __MACOSX/\*
Cleanup .zip from .DS_Store and __MACOSX, including subfolders:
zip -d archive.zip '__MACOSX/*' '*/__MACOSX/*' .DS_Store '*/.DS_Store'
Walkthrough:
Create .zip as usual by right-clicking on the file (or folder) and selecting "Compress ..."
Open Terminal app (search Terminal in Spotlight search)
Type zip in the Terminal (but don't hit enter)
Drag .zip to the Terminal so it converts to the path
Copy paste -d '__MACOSX/*' '*/__MACOSX/*' .DS_Store '*/.DS_Store'
Hit enter
Use zipinfo archive.zip to list files inside, to check (optional)
I have a better solution after read all of the existed answers. Everything could done by a workflow in a single right click.
NO additional software, NO complicated command line stuffs and NO shell tricks.
The automator workflow:
Input: files or folders from any application.
Step 1: Create Archive, the system builtin with default parameters.
Step 2: Run Shell command, with input as parameters. Copy command below.
zip -d "$#" "__MACOSX/*" || true
zip -d "$#" "*/.DS_Store" || true
Save it and we are done! Just right click folder or bulk of files and choose workflow from services menu. Archive with no metadata will be created alongside.
IMAGE UPDATE: I chose "Quick Action" when creating a new workflow - here’s an English version of the screenshot:
do not zip any hidden file:
zip newzipname filename.any -x "\.*"
with this question, it should be like:
zip newzipname filename.any -x "\__MACOSX"
It must be said, though, zip command runs in terminal just compressing the file, it does not compress any others. So do this the result is the same:
zip newzipname filename.any
Keka does this. Just drag your directory over the app screen.
Do you mean the zip command-line tool or the Finder's Compress command?
For zip, you can try the --data-fork option. If that doesn't do it, you might try --no-extra, although that seems to ignore other file metadata that might be valuable, like uid/gid and file times.
For the Finder's Compress command, I don't believe there are any options to control its behavior. It's for the simple case.
The other tool, and maybe the one that the Finder actually uses under the hood, is ditto. With the -c -k options, it creates zip archives. With this tool, you can experiment with --norsrc, --noextattr, --noqtn, --noacl and/or simply leave off the --sequesterRsrc option (which, according to the man page, may be responsible for the __MACOSX subdirectory). Although, perhaps the absence of --sequesterRsrc simply means to use AppleDouble format, which would create ._ files all over the place instead of one __MACOSX directory.
This is how i avoid the __MACOSX directory when compress files with tar command:
$ cd dir-you-want-to-archive
$ find . | xargs xattr -l # <- list all files with special xattr attributes
...
./conf/clamav: com.apple.quarantine: 0083;5a9018b1;Safari;9DCAFF33-C7F5-4848-9A87-5E061E5E2D55
./conf/global: com.apple.quarantine: 0083;5a9018b1;Safari;9DCAFF33-C7F5-4848-9A87-5E061E5E2D55
./conf/web_server: com.apple.quarantine: 0083;5a9018b1;Safari;9DCAFF33-C7F5-4848-9A87-5E061E5E2D55
Delete the attribute first:
find . | xargs xattr -d com.apple.quarantine
Run find . | xargs xattr -l again, make sure no any file has the xattr attribute. then you're good to go:
tar cjvf file.tar.bz2 dir
Another shell script that could be used with the Automator tool (see also benedikt's answer on how to create the script) is:
while read -r f; do
d="$(dirname "$f")"
n="$(basename "$f")"
cd "$d"
zip "$n.zip" -x \*.DS_Store -r "$n"
done
The difference here is that this code directly compresses selected folders without macOS specific files (and not first compressing and afterwards deleting).

Changing icon of package created by package maker

I have created package (.pkg) file using packagemaker ver 3.0.4. Is it possible to provide custom icon to the .pkg file. Can some one help me how this can be done ?
Thanks in advance.
The same way you set any other file's, folder's, or package's custom icon.
Setting an icon for an mpkg, works fine
# create a file that actually going to set the icon file
touch <package_name>.mpkg/Icon$'\r'
# --- copy the customIcon.icns file to the <package_name>.mpkg before doing the sips, if its needed you
# can take a copy of the file before doing the sips command, doing on a copied file will do good
sips -i <package_name>.mpkg/customIcon.icns
DeRez -only icns <package_name>.mpkg/customIcon.icns > tmpIcon.rsrc
Rez -append tmpIcon.rsrc -o $'<package_name>.mpkg/Icon\r'
SetFile -a C <package_name>.mpkg
# removing the tmp file
rm tmpIcon.rsrc
# remove the .icns from mpkg
rm <package_name>.mpkg/customIcon.icns
# if you want you can hide the Icon$'\r' file inside the .mpkg file, file that presently sets the icon
SetFile -a V <package_name>.mpkg/Icon$'\r'
Hope this helps.

How do I create a nice-looking DMG for Mac OS X using command-line tools?

I need to create a nice installer for a Mac application. I want it to be a disk image (DMG), with a predefined size, layout and background image.
I need to do this programmatically in a script, to be integrated in an existing build system (more of a pack system really, since it only create installers. The builds are done separately).
I already have the DMG creation done using "hdiutil", what I haven't found out yet is how to make an icon layout and specify a background bitmap.
After lots of research, I've come up with this answer, and I'm hereby putting it here as an answer for my own question, for reference:
Make sure that "Enable access for assistive devices" is checked in System Preferences>>Universal Access. It is required for the AppleScript to work. You may have to reboot after this change (it doesn't work otherwise on Mac OS X Server 10.4).
Create a R/W DMG. It must be larger than the result will be. In this example, the bash variable "size" contains the size in Kb and the contents of the folder in the "source" bash variable will be copied into the DMG:
hdiutil create -srcfolder "${source}" -volname "${title}" -fs HFS+ \
-fsargs "-c c=64,a=16,e=16" -format UDRW -size ${size}k pack.temp.dmg
Mount the disk image, and store the device name (you might want to use sleep for a few seconds after this operation):
device=$(hdiutil attach -readwrite -noverify -noautoopen "pack.temp.dmg" | \
egrep '^/dev/' | sed 1q | awk '{print $1}')
Store the background picture (in PNG format) in a folder called ".background" in the DMG, and store its name in the "backgroundPictureName" variable.
Use AppleScript to set the visual styles (name of .app must be in bash variable "applicationName", use variables for the other properties as needed):
echo '
tell application "Finder"
tell disk "'${title}'"
open
set current view of container window to icon view
set toolbar visible of container window to false
set statusbar visible of container window to false
set the bounds of container window to {400, 100, 885, 430}
set theViewOptions to the icon view options of container window
set arrangement of theViewOptions to not arranged
set icon size of theViewOptions to 72
set background picture of theViewOptions to file ".background:'${backgroundPictureName}'"
make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"}
set position of item "'${applicationName}'" of container window to {100, 100}
set position of item "Applications" of container window to {375, 100}
update without registering applications
delay 5
close
end tell
end tell
' | osascript
Finialize the DMG by setting permissions properly, compressing and releasing it:
chmod -Rf go-w /Volumes/"${title}"
sync
sync
hdiutil detach ${device}
hdiutil convert "/pack.temp.dmg" -format UDZO -imagekey zlib-level=9 -o "${finalDMGName}"
rm -f /pack.temp.dmg
On Snow Leopard, the above applescript will not set the icon position correctly - it seems to be a Snow Leopard bug. One workaround is to simply call close/open after setting the icons, i.e.:
..
set position of item "'${applicationName}'" of container window to {100, 100}
set position of item "Applications" of container window to {375, 100}
close
open
There's a little Bash script called create-dmg that builds fancy DMGs with custom backgrounds, custom icon positioning and volume name.
I've built it many years ago for the company that I ran at the time; it survives on other people's contribution since then, and reportedly works well.
There's also node-appdmg which looks like a more modern and active effort based on Node.js; check it out as well.
Don't go there. As a long term Mac developer, I can assure you, no solution is really working well. I tried so many solutions, but they are all not too good. I think the problem is that Apple does not really document the meta data format for the necessary data.
Here's how I'm doing it for a long time, very successfully:
Create a new DMG, writeable(!), big enough to hold the expected binary and extra files like readme (sparse might work).
Mount the DMG and give it a layout manually in Finder or with whatever tools suits you for doing that. The background image is usually an image we put into a hidden folder (".something") on the DMG. Put a copy of your app there (any version, even outdated one will do). Copy other files (aliases, readme, etc.) you want there, again, outdated versions will do just fine. Make sure icons have the right sizes and positions (IOW, layout the DMG the way you want it to be).
Unmount the DMG again, all settings should be stored by now.
Write a create DMG script, that works as follows:
It copies the DMG, so the original one is never touched again.
It mounts the copy.
It replaces all files with the most up to date ones (e.g. latest app after build). You can simply use mv or ditto for that on command line. Note, when you replace a file like that, the icon will stay the same, the position will stay the same, everything but the file (or directory) content stays the same (at least with ditto, which we usually use for that task). You can of course also replace the background image with another one (just make sure it has the same dimensions).
After replacing the files, make the script unmount the DMG copy again.
Finally call hdiutil to convert the writable, to a compressed (and such not writable) DMG.
This method may not sound optimal, but trust me, it works really well in practice. You can put the original DMG (DMG template) even under version control (e.g. SVN), so if you ever accidentally change/destroy it, you can just go back to a revision where it was still okay. You can add the DMG template to your Xcode project, together with all other files that belong onto the DMG (readme, URL file, background image), all under version control and then create a target (e.g. external target named "Create DMG") and there run the DMG script of above and add your old main target as dependent target. You can access files in the Xcode tree using ${SRCROOT} in the script (is always the source root of your product) and you can access build products by using ${BUILT_PRODUCTS_DIR} (is always the directory where Xcode creates the build results).
Result: Actually Xcode can produce the DMG at the end of the build. A DMG that is ready to release. Not only you can create a release DMG pretty easy that way, you can actually do so in an automated process (on a headless server if you like), using xcodebuild from command line (automated nightly builds for example).
Bringing this question up to date by providing this answer.
appdmg is a simple, easy-to-use, open-source command line program that creates dmg-files from a simple json specification. Take a look at the readme at the official website:
https://github.com/LinusU/node-appdmg
Quick example:
Install appdmg
npm install -g appdmg
Write a json file (spec.json)
{
"title": "Test Title",
"background": "background.png",
"icon-size": 80,
"contents": [
{ "x": 192, "y": 344, "type": "file", "path": "TestApp.app" },
{ "x": 448, "y": 344, "type": "link", "path": "/Applications" }
]
}
Run program
appdmg spec.json test.dmg
(disclaimer. I'm the creator of appdmg)
For those of you that are interested in this topic, I should mention how I create the DMG:
hdiutil create XXX.dmg -volname "YYY" -fs HFS+ -srcfolder "ZZZ"
where
XXX == disk image file name (duh!)
YYY == window title displayed when DMG is opened
ZZZ == Path to a folder containing the files that will be copied into the DMG
My app, DropDMG, is an easy way to create disk images with background pictures, icon layouts, custom volume icons, and software license agreements. It can be controlled from a build system via the "dropdmg" command-line tool or AppleScript. If desired, the picture and license RTF files can be stored under your version control system.
For creating a nice looking DMG, you can now just use some well written open sources:
create-dmg
node-appdmg
dmgbuild
I found this great mac app to automate the process - http://www.araelium.com/dmgcanvas/
you must have a look if you are creating dmg installer for your mac app
If you want to set custom volume icon then use below command
/*Add a drive icon*/
cp "/Volumes/customIcon.icns" "/Volumes/dmgName/.VolumeIcon.icns"
/*SetFile -c icnC will change the creator of the file to icnC*/
SetFile -c icnC /<your path>/.VolumeIcon.icns
Now create read/write dmg
/*to set custom icon attribute*/
SetFile -a C /Volumes/dmgName
I finally got this working in my own project (which happens to be in Xcode). Adding these 3 scripts to your build phase will automatically create a Disk Image for your product that is nice and neat. All you have to do is build your project and the DMG will be waiting in your products folder.
Script 1 (Create Temp Disk Image):
#!/bin/bash
#Create a R/W DMG
dir="$TEMP_FILES_DIR/disk"
dmg="$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.temp.dmg"
rm -rf "$dir"
mkdir "$dir"
cp -R "$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.app" "$dir"
ln -s "/Applications" "$dir/Applications"
mkdir "$dir/.background"
cp "$PROJECT_DIR/$PROJECT_NAME/some_image.png" "$dir/.background"
rm -f "$dmg"
hdiutil create "$dmg" -srcfolder "$dir" -volname "$PRODUCT_NAME" -format UDRW
#Mount the disk image, and store the device name
hdiutil attach "$dmg" -noverify -noautoopen -readwrite
Script 2 (Set Window Properties Script):
#!/usr/bin/osascript
#get the dimensions of the main window using a bash script
set {width, height, scale} to words of (do shell script "system_profiler SPDisplaysDataType | awk '/Main Display: Yes/{found=1} /Resolution/{width=$2; height=$4} /Retina/{scale=($2 == \"Yes\" ? 2 : 1)} /^ {8}[^ ]+/{if(found) {exit}; scale=1} END{printf \"%d %d %d\\n\", width, height, scale}'")
set x to ((width / 2) / scale)
set y to ((height / 2) / scale)
#get the product name using a bash script
set {product_name} to words of (do shell script "printf \"%s\", $PRODUCT_NAME")
set background to alias ("Volumes:"&product_name&":.background:some_image.png")
tell application "Finder"
tell disk product_name
open
set current view of container window to icon view
set toolbar visible of container window to false
set statusbar visible of container window to false
set the bounds of container window to {x, y, (x + 479), (y + 383)}
set theViewOptions to the icon view options of container window
set arrangement of theViewOptions to not arranged
set icon size of theViewOptions to 128
set background picture of theViewOptions to background
set position of item (product_name & ".app") of container window to {100, 225}
set position of item "Applications" of container window to {375, 225}
update without registering applications
close
end tell
end tell
The above measurement for the window work for my project specifically due to the size of my background pic and icon resolution; you may need to modify these values for your own project.
Script 3 (Make Final Disk Image Script):
#!/bin/bash
dir="$TEMP_FILES_DIR/disk"
cp "$PROJECT_DIR/$PROJECT_NAME/some_other_image.png" "$dir/"
#unmount the temp image file, then convert it to final image file
sync
sync
hdiutil detach /Volumes/$PRODUCT_NAME
rm -f "$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg"
hdiutil convert "$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.temp.dmg" -format UDZO -imagekey zlib-level=9 -o "$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg"
rm -f "$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.temp.dmg"
#Change the icon of the image file
sips -i "$dir/some_other_image.png"
DeRez -only icns "$dir/some_other_image.png" > "$dir/tmpicns.rsrc"
Rez -append "$dir/tmpicns.rsrc" -o "$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg"
SetFile -a C "$BUILT_PRODUCTS_DIR/$PRODUCT_NAME.dmg"
rm -rf "$dir"
Make sure the image files you are using are in the $PROJECT_DIR/$PROJECT_NAME/ directory!
.DS_Store files stores windows settings in Mac. Windows settings include the icons layout, the window background, the size of the window, etc. The .DS_Store file is needed in creating the window for mounted images to preserve the arrangement of files and the windows background.
Once you have .DS_Store file created, you can just copy it to your created installer (DMG).
I also in need of using command line approach to do the packaging and dmg creation "programmatically in a script". The best answer I found so far is from Adium project' Release building framework (See R1). There is a custom script(AdiumApplescriptRunner) to allow you avoid OSX WindowsServer GUI interaction. "osascript applescript.scpt" approach require you to login as builder and run the dmg creation from a command line vt100 session.
OSX package management system is not so advanced compared to other Unixen which can do this task easily and systematically.
R1: http://hg.adium.im/adium-1.4/file/00d944a3ef16/Release
I've just written a new (friendly) command line utility to do this. It doesn’t rely on Finder/AppleScript, or on any of the (deprecated) Alias Manager APIs, and it’s easy to configure and use.
Anyway, anyone who is interested can find it on PyPi; the documentation is available on Read The Docs.
I used dmgbuild.
Installation: pip3 install dmgbuild
Mount your volume
Create a settings file:
{
"title": "NAME",
"background": "YOUR_BACKGROUND.png",
"format": "UDZO",
"compression-level": 9,
"window": { "position": { "x": 100, "y": 100 },
"size": { "width": 640, "height": 300 } },
"contents": [
{ "x": 140, "y": 165, "type": "file", "path": "/Volumes/YOUR_VOLUME_NAME/YOUR_APP.app" },
{ "x": 480, "y": 165, "type": "link", "path": "/Applications" }
]
}
The width value is the width of the background.
The height value should be the background height + 20 for the window bar.
In a terminal: dmgbuild -s settings.json "YOUR_VOLUME_NAME" output.dmg
These answers are way too complicated and times have changed. The following works on 10.9 just fine, permissions are correct and it looks nice.
Create a read-only DMG from a directory
#!/bin/sh
# create_dmg Frobulator Frobulator.dmg path/to/frobulator/dir [ 'Your Code Sign Identity' ]
set -e
VOLNAME="$1"
DMG="$2"
SRC_DIR="$3"
CODESIGN_IDENTITY="$4"
hdiutil create -srcfolder "$SRC_DIR" \
-volname "$VOLNAME" \
-fs HFS+ -fsargs "-c c=64,a=16,e=16" \
-format UDZO -imagekey zlib-level=9 "$DMG"
if [ -n "$CODESIGN_IDENTITY" ]; then
codesign -s "$CODESIGN_IDENTITY" -v "$DMG"
fi
Create read-only DMG with an icon (.icns type)
#!/bin/sh
# create_dmg_with_icon Frobulator Frobulator.dmg path/to/frobulator/dir path/to/someicon.icns [ 'Your Code Sign Identity' ]
set -e
VOLNAME="$1"
DMG="$2"
SRC_DIR="$3"
ICON_FILE="$4"
CODESIGN_IDENTITY="$5"
TMP_DMG="$(mktemp -u -t XXXXXXX)"
trap 'RESULT=$?; rm -f "$TMP_DMG"; exit $RESULT' INT QUIT TERM EXIT
hdiutil create -srcfolder "$SRC_DIR" -volname "$VOLNAME" -fs HFS+ \
-fsargs "-c c=64,a=16,e=16" -format UDRW "$TMP_DMG"
TMP_DMG="${TMP_DMG}.dmg" # because OSX appends .dmg
DEVICE="$(hdiutil attach -readwrite -noautoopen "$TMP_DMG" | awk 'NR==1{print$1}')"
VOLUME="$(mount | grep "$DEVICE" | sed 's/^[^ ]* on //;s/ ([^)]*)$//')"
# start of DMG changes
cp "$ICON_FILE" "$VOLUME/.VolumeIcon.icns"
SetFile -c icnC "$VOLUME/.VolumeIcon.icns"
SetFile -a C "$VOLUME"
# end of DMG changes
hdiutil detach "$DEVICE"
hdiutil convert "$TMP_DMG" -format UDZO -imagekey zlib-level=9 -o "$DMG"
if [ -n "$CODESIGN_IDENTITY" ]; then
codesign -s "$CODESIGN_IDENTITY" -v "$DMG"
fi
If anything else needs to happen, these easiest thing is to make a temporary copy of the SRC_DIR and apply changes to that before creating a DMG.

Resources