Debian Codegraph @

python/mozbuild/mozpack/dmg.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import os
6 import platform
7 import shutil
8 import subprocess
9 from pathlib import Path
10 from typing import List
11
12 import mozfile
13
14 from mozbuild.dirutils import ensureParentDir
15
16 is_linux = platform.system() == "Linux"
17 is_osx = platform.system() == "Darwin"
18
19
20 def chmod(dir):
21 "Set permissions of DMG contents correctly"
22 subprocess.check_call(["chmod", "-R", "a+rX,a-st,u+w,go-w", dir])
23
24
25 def rsync(source: Path, dest: Path):
26 "rsync the contents of directory source into directory dest"
27 # Ensure a trailing slash on directories so rsync copies the *contents* of source.
28 raw_source = str(source)
29 if source.is_dir():
30 raw_source = str(source) + "/"
31 subprocess.check_call(["rsync", "-a", "--copy-unsafe-links", raw_source, dest])
32
33
34 def set_folder_icon(dir: Path, tmpdir: Path, hfs_tool: Path = None):
35 "Set HFS attributes of dir to use a custom icon"
36 if is_linux:
37 hfs = tmpdir / "staged.hfs"
38 subprocess.check_call([hfs_tool, hfs, "attr", "/", "C"])
39 elif is_osx:
40 subprocess.check_call(["SetFile", "-a", "C", dir])
41
42
43 def generate_hfs_file(
44 stagedir: Path, tmpdir: Path, volume_name: str, mkfshfs_tool: Path
45 ):
46 """
47 When cross compiling, we zero fill an hfs file, that we will turn into
48 a DMG. To do so we test the size of the staged dir, and add some slight
49 padding to that.
50 """
51 hfs = tmpdir / "staged.hfs"
52 output = subprocess.check_output(["du", "-s", stagedir])
53 size = int(output.split()[0]) / 1000 # Get in MB
54 size = int(size * 1.02) # Bump the used size slightly larger.
55 # Setup a proper file sized out with zero's
56 subprocess.check_call(
57 [
58 "dd",
59 "if=/dev/zero",
60 f"of={hfs}",
61 "bs=1M",
62 f"count={size}",
63 ]
64 )
65 subprocess.check_call([mkfshfs_tool, "-v", volume_name, hfs])
66
67
68 def create_app_symlink(stagedir: Path, tmpdir: Path, hfs_tool: Path = None):
69 """
70 Make a symlink to /Applications. The symlink name is a space
71 so we don't have to localize it. The Applications folder icon
72 will be shown in Finder, which should be clear enough for users.
73 """
74 if is_linux:
75 hfs = os.path.join(tmpdir, "staged.hfs")
76 subprocess.check_call([hfs_tool, hfs, "symlink", "/ ", "/Applications"])
77 elif is_osx:
78 os.symlink("/Applications", stagedir / " ")
79
80
81 def create_dmg_from_staged(
82 stagedir: Path,
83 output_dmg: Path,
84 tmpdir: Path,
85 volume_name: str,
86 hfs_tool: Path = None,
87 dmg_tool: Path = None,
88 mkfshfs_tool: Path = None,
89 attribution_sentinel: str = None,
90 compression: str = None,
91 ):
92 "Given a prepared directory stagedir, produce a DMG at output_dmg."
93 if compression is None:
94 # Easier to put the default here once, than in every place that takes default args
95 compression = "bzip2"
96 if compression not in ["bzip2", "lzma"]:
97 raise Exception("Don't know how to handle %s compression" % (compression,))
98
99 if is_linux:
100 # The dmg tool doesn't create the destination directories, and silently
101 # returns success if the parent directory doesn't exist.
102 ensureParentDir(output_dmg)
103 hfs = os.path.join(tmpdir, "staged.hfs")
104 subprocess.check_call([hfs_tool, hfs, "addall", stagedir])
105
106 dmg_cmd = [dmg_tool, "build", hfs, output_dmg]
107 if attribution_sentinel:
108 while len(attribution_sentinel) < 1024:
109 attribution_sentinel += "\t"
110 subprocess.check_call(
111 [
112 hfs_tool,
113 hfs,
114 "setattr",
115 f"{volume_name}.app",
116 "com.apple.application-instance",
117 attribution_sentinel,
118 ]
119 )
120 subprocess.check_call(["cp", hfs, str(Path(output_dmg).parent)])
121 dmg_cmd.append(attribution_sentinel)
122
123 if compression == "lzma":
124 dmg_cmd.extend(
125 ["--compression", "lzma", "--level", "5", "--run-sectors", "2048"]
126 )
127
128 subprocess.check_call(
129 dmg_cmd,
130 # dmg is seriously chatty
131 stdout=subprocess.DEVNULL,
132 )
133 elif is_osx:
134 format = "UDBZ"
135 if compression == "lzma":
136 format = "ULMO"
137
138 hybrid = tmpdir / "hybrid.dmg"
139 subprocess.check_call(
140 [
141 "hdiutil",
142 "makehybrid",
143 "-hfs",
144 "-hfs-volume-name",
145 volume_name,
146 "-hfs-openfolder",
147 stagedir,
148 "-ov",
149 stagedir,
150 "-o",
151 hybrid,
152 ]
153 )
154 subprocess.check_call(
155 [
156 "hdiutil",
157 "convert",
158 "-format",
159 format,
160 "-imagekey",
161 "bzip2-level=9",
162 "-ov",
163 hybrid,
164 "-o",
165 output_dmg,
166 ]
167 )
168
169
170 def create_dmg(
171 source_directory: Path,
172 output_dmg: Path,
173 volume_name: str,
174 extra_files: List[tuple],
175 dmg_tool: Path,
176 hfs_tool: Path,
177 mkfshfs_tool: Path,
178 attribution_sentinel: str = None,
179 compression: str = None,
180 ):
181 """
182 Create a DMG disk image at the path output_dmg from source_directory.
183
184 Use volume_name as the disk image volume name, and
185 use extra_files as a list of tuples of (filename, relative path) to copy
186 into the disk image.
187 """
188 if platform.system() not in ("Darwin", "Linux"):
189 raise Exception("Don't know how to build a DMG on '%s'" % platform.system())
190
191 with mozfile.TemporaryDirectory() as tmp:
192 tmpdir = Path(tmp)
193 stagedir = tmpdir / "stage"
194 stagedir.mkdir()
195
196 # Copy the app bundle over using rsync
197 rsync(source_directory, stagedir)
198 # Copy extra files
199 for source, target in extra_files:
200 full_target = stagedir / target
201 full_target.parent.mkdir(parents=True, exist_ok=True)
202 shutil.copyfile(source, full_target)
203 if is_linux:
204 # Not needed in osx
205 generate_hfs_file(stagedir, tmpdir, volume_name, mkfshfs_tool)
206 create_app_symlink(stagedir, tmpdir, hfs_tool)
207 # Set the folder attributes to use a custom icon
208 set_folder_icon(stagedir, tmpdir, hfs_tool)
209 chmod(stagedir)
210 create_dmg_from_staged(
211 stagedir,
212 output_dmg,
213 tmpdir,
214 volume_name,
215 hfs_tool,
216 dmg_tool,
217 mkfshfs_tool,
218 attribution_sentinel,
219 compression,
220 )
221
222
223 def extract_dmg_contents(
224 dmgfile: Path,
225 destdir: Path,
226 dmg_tool: Path = None,
227 hfs_tool: Path = None,
228 ):
229 if is_linux:
230 with mozfile.TemporaryDirectory() as tmpdir:
231 hfs_file = os.path.join(tmpdir, "firefox.hfs")
232 subprocess.check_call(
233 [dmg_tool, "extract", dmgfile, hfs_file],
234 # dmg is seriously chatty
235 stdout=subprocess.DEVNULL,
236 )
237 subprocess.check_call([hfs_tool, hfs_file, "extractall", "/", destdir])
238 else:
239 # TODO: find better way to resolve topsrcdir (checkout directory)
240 topsrcdir = Path(__file__).parent.parent.parent.parent.resolve()
241 unpack_diskimage = topsrcdir / "build/package/mac_osx/unpack-diskimage"
242 unpack_mountpoint = Path("/tmp/app-unpack")
243 subprocess.check_call([unpack_diskimage, dmgfile, unpack_mountpoint, destdir])
244
245
246 def extract_dmg(
247 dmgfile: Path,
248 output: Path,
249 dmg_tool: Path = None,
250 hfs_tool: Path = None,
251 dsstore: Path = None,
252 icon: Path = None,
253 background: Path = None,
254 ):
255 if platform.system() not in ("Darwin", "Linux"):
256 raise Exception("Don't know how to extract a DMG on '%s'" % platform.system())
257
258 with mozfile.TemporaryDirectory() as tmp:
259 tmpdir = Path(tmp)
260 extract_dmg_contents(dmgfile, tmpdir, dmg_tool, hfs_tool)
261 applications_symlink = tmpdir / " "
262 if applications_symlink.is_symlink():
263 # Rsync will fail on the presence of this symlink
264 applications_symlink.unlink()
265 rsync(tmpdir, output)
266
267 if dsstore:
268 dsstore.parent.mkdir(parents=True, exist_ok=True)
269 rsync(tmpdir / ".DS_Store", dsstore)
270 if background:
271 background.parent.mkdir(parents=True, exist_ok=True)
272 rsync(tmpdir / ".background" / background.name, background)
273 if icon:
274 icon.parent.mkdir(parents=True, exist_ok=True)
275 rsync(tmpdir / ".VolumeIcon.icns", icon)