blob: 44e2662ce79f52d1fcc63d9892e9083ede0ac98b [file] [log] [blame]
Jack Jansena6db44f2002-09-06 19:47:49 +00001#!/usr/bin/env python
2
3"""buildpkg.py -- Build OS X packages for Apple's Installer.app.
4
5This is an experimental command-line tool for building packages to be
6installed with the Mac OS X Installer.app application.
7
8It is much inspired by Apple's GUI tool called PackageMaker.app, that
9seems to be part of the OS X developer tools installed in the folder
10/Developer/Applications. But apparently there are other free tools to
11do the same thing which are also named PackageMaker like Brian Hill's
12one:
13
14 http://personalpages.tds.net/~brian_hill/packagemaker.html
15
16Beware of the multi-package features of Installer.app (which are not
17yet supported here) that can potentially screw-up your installation
18and are discussed in these articles on Stepwise:
19
20 http://www.stepwise.com/Articles/Technical/Packages/InstallerWoes.html
21 http://www.stepwise.com/Articles/Technical/Packages/InstallerOnX.html
22
23Beside using the PackageMaker class directly, by importing it inside
24another module, say, there are additional ways of using this module:
25the top-level buildPackage() function provides a shortcut to the same
26feature and is also called when using this module from the command-
27line.
28
29 ****************************************************************
30 NOTE: For now you should be able to run this even on a non-OS X
31 system and get something similar to a package, but without
32 the real archive (needs pax) and bom files (needs mkbom)
33 inside! This is only for providing a chance for testing to
34 folks without OS X.
35 ****************************************************************
36
37TODO:
38 - test pre-process and post-process scripts (Python ones?)
39 - handle multi-volume packages (?)
40 - integrate into distutils (?)
41
42Dinu C. Gherman,
43gherman@europemail.com
44November 2001
45
46!! USE AT YOUR OWN RISK !!
47"""
48
49__version__ = 0.2
50__license__ = "FreeBSD"
51
52
53import os, sys, glob, fnmatch, shutil, string, copy, getopt
54from os.path import basename, dirname, join, islink, isdir, isfile
55
56
57PKG_INFO_FIELDS = """\
58Title
59Version
60Description
61DefaultLocation
62Diskname
63DeleteWarning
64NeedsAuthorization
65DisableStop
66UseUserMask
67Application
68Relocatable
69Required
70InstallOnly
71RequiresReboot
72InstallFat\
73"""
74
75######################################################################
76# Helpers
77######################################################################
78
79# Convenience class, as suggested by /F.
80
81class GlobDirectoryWalker:
82 "A forward iterator that traverses files in a directory tree."
83
84 def __init__(self, directory, pattern="*"):
85 self.stack = [directory]
86 self.pattern = pattern
87 self.files = []
88 self.index = 0
89
90
91 def __getitem__(self, index):
92 while 1:
93 try:
94 file = self.files[self.index]
95 self.index = self.index + 1
96 except IndexError:
97 # pop next directory from stack
98 self.directory = self.stack.pop()
99 self.files = os.listdir(self.directory)
100 self.index = 0
101 else:
102 # got a filename
103 fullname = join(self.directory, file)
104 if isdir(fullname) and not islink(fullname):
105 self.stack.append(fullname)
106 if fnmatch.fnmatch(file, self.pattern):
107 return fullname
108
109
110######################################################################
111# The real thing
112######################################################################
113
114class PackageMaker:
115 """A class to generate packages for Mac OS X.
116
117 This is intended to create OS X packages (with extension .pkg)
118 containing archives of arbitrary files that the Installer.app
119 will be able to handle.
120
121 As of now, PackageMaker instances need to be created with the
122 title, version and description of the package to be built.
123 The package is built after calling the instance method
124 build(root, **options). It has the same name as the constructor's
125 title argument plus a '.pkg' extension and is located in the same
126 parent folder that contains the root folder.
127
128 E.g. this will create a package folder /my/space/distutils.pkg/:
129
130 pm = PackageMaker("distutils", "1.0.2", "Python distutils.")
131 pm.build("/my/space/distutils")
132 """
133
134 packageInfoDefaults = {
135 'Title': None,
136 'Version': None,
137 'Description': '',
138 'DefaultLocation': '/',
139 'Diskname': '(null)',
140 'DeleteWarning': '',
141 'NeedsAuthorization': 'NO',
142 'DisableStop': 'NO',
143 'UseUserMask': 'YES',
144 'Application': 'NO',
145 'Relocatable': 'YES',
146 'Required': 'NO',
147 'InstallOnly': 'NO',
148 'RequiresReboot': 'NO',
149 'InstallFat': 'NO'}
150
151
152 def __init__(self, title, version, desc):
153 "Init. with mandatory title/version/description arguments."
154
155 info = {"Title": title, "Version": version, "Description": desc}
156 self.packageInfo = copy.deepcopy(self.packageInfoDefaults)
157 self.packageInfo.update(info)
158
159 # variables set later
160 self.packageRootFolder = None
161 self.packageResourceFolder = None
162 self.resourceFolder = None
163
164
165 def build(self, root, resources=None, **options):
166 """Create a package for some given root folder.
167
168 With no 'resources' argument set it is assumed to be the same
169 as the root directory. Option items replace the default ones
170 in the package info.
171 """
172
173 # set folder attributes
174 self.packageRootFolder = root
175 if resources == None:
176 self.packageResourceFolder = root
177
178 # replace default option settings with user ones if provided
179 fields = self. packageInfoDefaults.keys()
180 for k, v in options.items():
181 if k in fields:
182 self.packageInfo[k] = v
183
184 # do what needs to be done
185 self._makeFolders()
186 self._addInfo()
187 self._addBom()
188 self._addArchive()
189 self._addResources()
190 self._addSizes()
191
192
193 def _makeFolders(self):
194 "Create package folder structure."
195
196 # Not sure if the package name should contain the version or not...
197 # packageName = "%s-%s" % (self.packageInfo["Title"],
198 # self.packageInfo["Version"]) # ??
199
200 packageName = self.packageInfo["Title"]
201 rootFolder = packageName + ".pkg"
202 contFolder = join(rootFolder, "Contents")
203 resourceFolder = join(contFolder, "Resources")
204 os.mkdir(rootFolder)
205 os.mkdir(contFolder)
206 os.mkdir(resourceFolder)
207
208 self.resourceFolder = resourceFolder
209
210
211 def _addInfo(self):
212 "Write .info file containing installing options."
213
214 # Not sure if options in PKG_INFO_FIELDS are complete...
215
216 info = ""
217 for f in string.split(PKG_INFO_FIELDS, "\n"):
218 info = info + "%s %%(%s)s\n" % (f, f)
219 info = info % self.packageInfo
220 base = basename(self.packageRootFolder) + ".info"
221 path = join(self.resourceFolder, base)
222 f = open(path, "w")
223 f.write(info)
224
225
226 def _addBom(self):
227 "Write .bom file containing 'Bill of Materials'."
228
229 # Currently ignores if the 'mkbom' tool is not available.
230
231 try:
232 base = basename(self.packageRootFolder) + ".bom"
233 bomPath = join(self.resourceFolder, base)
234 cmd = "mkbom %s %s" % (self.packageRootFolder, bomPath)
235 res = os.system(cmd)
236 except:
237 pass
238
239
240 def _addArchive(self):
241 "Write .pax.gz file, a compressed archive using pax/gzip."
242
243 # Currently ignores if the 'pax' tool is not available.
244
245 cwd = os.getcwd()
246
247 packageRootFolder = self.packageRootFolder
248
249 try:
250 # create archive
251 d = dirname(packageRootFolder)
252 os.chdir(packageRootFolder)
253 base = basename(packageRootFolder) + ".pax"
254 archPath = join(d, self.resourceFolder, base)
255 cmd = "pax -w -f %s %s" % (archPath, ".")
256 res = os.system(cmd)
257
258 # compress archive
259 cmd = "gzip %s" % archPath
260 res = os.system(cmd)
261 except:
262 pass
263
264 os.chdir(cwd)
265
266
267 def _addResources(self):
268 "Add Welcome/ReadMe/License files, .lproj folders and scripts."
269
270 # Currently we just copy everything that matches the allowed
271 # filenames. So, it's left to Installer.app to deal with the
272 # same file available in multiple formats...
273
274 if not self.packageResourceFolder:
275 return
276
277 # find candidate resource files (txt html rtf rtfd/ or lproj/)
278 allFiles = []
279 for pat in string.split("*.txt *.html *.rtf *.rtfd *.lproj", " "):
280 pattern = join(self.packageResourceFolder, pat)
281 allFiles = allFiles + glob.glob(pattern)
282
283 # find pre-process and post-process scripts
284 # naming convention: packageName.{pre,post}-{upgrade,install}
285 packageName = self.packageInfo["Title"]
286 for pat in ("*upgrade", "*install"):
287 pattern = join(self.packageResourceFolder, packageName + pat)
288 allFiles = allFiles + glob.glob(pattern)
289
290 # check name patterns
291 files = []
292 for f in allFiles:
293 for s in ("Welcome", "License", "ReadMe"):
294 if string.find(basename(f), s) == 0:
295 files.append(f)
296 if f[-6:] == ".lproj":
297 files.append(f)
298 elif f[-8:] == "-upgrade":
299 files.append(f)
300 elif f[-8:] == "-install":
301 files.append(f)
302
303 # copy files
304 for g in files:
305 f = join(self.packageResourceFolder, g)
306 if isfile(f):
307 shutil.copy(f, self.resourceFolder)
308 elif isdir(f):
309 # special case for .rtfd and .lproj folders...
310 d = join(self.resourceFolder, basename(f))
311 os.mkdir(d)
312 files = GlobDirectoryWalker(f)
313 for file in files:
314 shutil.copy(file, d)
315
316
317 def _addSizes(self):
318 "Write .sizes file with info about number and size of files."
319
320 # Not sure if this is correct, but 'installedSize' and
321 # 'zippedSize' are now in Bytes. Maybe blocks are needed?
322 # Well, Installer.app doesn't seem to care anyway, saying
323 # the installation needs 100+ MB...
324
325 numFiles = 0
326 installedSize = 0
327 zippedSize = 0
328
329 packageRootFolder = self.packageRootFolder
330
331 files = GlobDirectoryWalker(packageRootFolder)
332 for f in files:
333 numFiles = numFiles + 1
334 installedSize = installedSize + os.stat(f)[6]
335
336 d = dirname(packageRootFolder)
337 base = basename(packageRootFolder) + ".pax.gz"
338 archPath = join(d, self.resourceFolder, base)
339 try:
340 zippedSize = os.stat(archPath)[6]
341 except OSError: # ignore error
342 pass
343 base = basename(packageRootFolder) + ".sizes"
344 f = open(join(self.resourceFolder, base), "w")
345 format = "NumFiles %d\nInstalledSize %d\nCompressedSize %d"
346 f.write(format % (numFiles, installedSize, zippedSize))
347
348
349# Shortcut function interface
350
351def buildPackage(*args, **options):
352 "A Shortcut function for building a package."
353
354 o = options
355 title, version, desc = o["Title"], o["Version"], o["Description"]
356 pm = PackageMaker(title, version, desc)
357 apply(pm.build, list(args), options)
358
359
360######################################################################
361# Tests
362######################################################################
363
364def test0():
365 "Vanilla test for the distutils distribution."
366
367 pm = PackageMaker("distutils2", "1.0.2", "Python distutils package.")
368 pm.build("/Users/dinu/Desktop/distutils2")
369
370
371def test1():
372 "Test for the reportlab distribution with modified options."
373
374 pm = PackageMaker("reportlab", "1.10",
375 "ReportLab's Open Source PDF toolkit.")
376 pm.build(root="/Users/dinu/Desktop/reportlab",
377 DefaultLocation="/Applications/ReportLab",
378 Relocatable="YES")
379
380def test2():
381 "Shortcut test for the reportlab distribution with modified options."
382
383 buildPackage(
384 "/Users/dinu/Desktop/reportlab",
385 Title="reportlab",
386 Version="1.10",
387 Description="ReportLab's Open Source PDF toolkit.",
388 DefaultLocation="/Applications/ReportLab",
389 Relocatable="YES")
390
391
392######################################################################
393# Command-line interface
394######################################################################
395
396def printUsage():
397 "Print usage message."
398
399 format = "Usage: %s <opts1> [<opts2>] <root> [<resources>]"
400 print format % basename(sys.argv[0])
401 print
402 print " with arguments:"
403 print " (mandatory) root: the package root folder"
404 print " (optional) resources: the package resources folder"
405 print
406 print " and options:"
407 print " (mandatory) opts1:"
408 mandatoryKeys = string.split("Title Version Description", " ")
409 for k in mandatoryKeys:
410 print " --%s" % k
411 print " (optional) opts2: (with default values)"
412
413 pmDefaults = PackageMaker.packageInfoDefaults
414 optionalKeys = pmDefaults.keys()
415 for k in mandatoryKeys:
416 optionalKeys.remove(k)
417 optionalKeys.sort()
418 maxKeyLen = max(map(len, optionalKeys))
419 for k in optionalKeys:
420 format = " --%%s:%s %%s"
421 format = format % (" " * (maxKeyLen-len(k)))
422 print format % (k, repr(pmDefaults[k]))
423
424
425def main():
426 "Command-line interface."
427
428 shortOpts = ""
429 keys = PackageMaker.packageInfoDefaults.keys()
430 longOpts = map(lambda k: k+"=", keys)
431
432 try:
433 opts, args = getopt.getopt(sys.argv[1:], shortOpts, longOpts)
434 except getopt.GetoptError, details:
435 print details
436 printUsage()
437 return
438
439 optsDict = {}
440 for k, v in opts:
441 optsDict[k[2:]] = v
442
443 ok = optsDict.keys()
444 if not (1 <= len(args) <= 2):
445 print "No argument given!"
446 elif not ("Title" in ok and \
447 "Version" in ok and \
448 "Description" in ok):
449 print "Missing mandatory option!"
450 else:
451 apply(buildPackage, args, optsDict)
452 return
453
454 printUsage()
455
456 # sample use:
457 # buildpkg.py --Title=distutils \
458 # --Version=1.0.2 \
459 # --Description="Python distutils package." \
460 # /Users/dinu/Desktop/distutils
461
462
463if __name__ == "__main__":
464 main()