aboutsummaryrefslogtreecommitdiffstats
path: root/share/qbs/modules/bundle/BundleModule.qbs
blob: f1a80a6686ee2b682e4dcb58c069cb33505d93e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qbs.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

import qbs
import qbs.BundleTools
import qbs.DarwinTools
import qbs.Environment
import qbs.File
import qbs.FileInfo
import qbs.ModUtils
import qbs.PropertyList
import qbs.TextFile
import qbs.Utilities
import "bundle.js" as Bundle

Module {
    Depends { name: "xcode"; required: false; }

    Probe {
        id: bundleSettingsProbe
        condition: qbs.targetOS.contains("darwin")

        property string xcodeDeveloperPath: xcode.developerPath

        // Note that we include several settings pointing to properties which reference the output
        // of this probe (WRAPPER_NAME, WRAPPER_EXTENSION, etc.). This is to ensure that derived
        // properties take into account the value of these settings if the user customized them.
        property var additionalSettings: ({
            "DEVELOPMENT_LANGUAGE": "English",
            "EXECUTABLE_VARIANT_SUFFIX": "", // e.g. _debug, _profile
            "FRAMEWORK_VERSION": frameworkVersion,
            "GENERATE_PKGINFO_FILE": generatePackageInfo !== undefined
                                     ? (generatePackageInfo ? "YES" : "NO")
                                     : undefined,
            "PRODUCT_NAME": product.targetName,
            "LOCAL_APPS_DIR": Environment.getEnv("HOME") + "/Applications",
            "LOCAL_LIBRARY_DIR": Environment.getEnv("HOME") + "/Library",
            "TARGET_BUILD_DIR": product.buildDirectory,
            "WRAPPER_NAME": bundleName,
            "WRAPPER_EXTENSION": extension
        })

        // Outputs
        property var xcodeSettings: ({})

        configure: {
            var specsPath = path;
            var specsSeparator = "-";
            if (xcodeDeveloperPath && _useXcodeBuildSpecs) {
                specsPath = xcodeDeveloperPath
                        + "/Platforms/MacOSX.platform/Developer/Library/Xcode/Specifications";
                specsSeparator = " ";
            }

            var reader = new Bundle.XcodeBuildSpecsReader(specsPath,
                                                          specsSeparator,
                                                          additionalSettings,
                                                          !qbs.targetOS.contains("osx"));
            var settings = reader.expandedSettings(_productTypeIdentifier);
            if (settings) {
                xcodeSettings = settings;
                found = true;
            } else {
                xcodeSettings = {};
                found = false;
            }
        }
    }

    additionalProductTypes: ["bundle"]

    property bool isBundle: !product.consoleApplication && qbs.targetOS.contains("darwin") &&
        product.type.containsAny(["application", "dynamiclibrary", "loadablemodule"])

    readonly property bool isShallow: bundleSettingsProbe.xcodeSettings["SHALLOW_BUNDLE"] === "YES"

    property string identifierPrefix: "org.example"
    property string identifier: [identifierPrefix, Utilities.rfc1034Identifier(product.targetName)].join(".")

    property string extension: bundleSettingsProbe.xcodeSettings["WRAPPER_EXTENSION"]

    property string packageType: {
        if (product.type.contains("inapppurchase"))
            return undefined;
        if (product.type.contains("xpcservice"))
            return "XPC!";
        if (product.type.contains("application"))
            return "APPL";
        if (product.type.containsAny(["dynamiclibrary", "staticlibrary"]))
            return "FMWK";
        if (product.type.contains("kernelmodule"))
            return "KEXT";
        return "BNDL";
    }

    property string signature: "????" // legacy creator code in Mac OS Classic (CFBundleSignature), can be ignored

    property string bundleName: bundleSettingsProbe.xcodeSettings["WRAPPER_NAME"]

    property string frameworkVersion: {
        var n = parseInt(product.version, 10);
        return isNaN(n) ? bundleSettingsProbe.xcodeSettings["FRAMEWORK_VERSION"] : String(n);
    }

    property bool generatePackageInfo: {
        // Make sure to return undefined as default to indicate "not set"
        var genPkgInfo = bundleSettingsProbe.xcodeSettings["GENERATE_PKGINFO_FILE"];
        if (genPkgInfo)
            return genPkgInfo === "YES";
    }

    property pathList publicHeaders
    property pathList privateHeaders
    property pathList resources

    property var infoPlist
    property bool processInfoPlist: true
    property bool embedInfoPlist: product.type.contains("application") && !isBundle
    property string infoPlistFormat: qbs.targetOS.contains("osx") ? "same-as-input" : "binary1"

    property string localizedResourcesFolderSuffix: ".lproj"

    property string lsregisterName: "lsregister"
    property string lsregisterPath: FileInfo.joinPaths(
                                        "/System/Library/Frameworks/CoreServices.framework" +
                                        "/Versions/A/Frameworks/LaunchServices.framework" +
                                        "/Versions/A/Support", lsregisterName);

    // all paths are relative to the directory containing the bundle
    readonly property string infoPlistPath: bundleSettingsProbe.xcodeSettings["INFOPLIST_PATH"]
    readonly property string infoStringsPath: bundleSettingsProbe.xcodeSettings["INFOSTRINGS_PATH"]
    readonly property string pbdevelopmentPlistPath: bundleSettingsProbe.xcodeSettings["PBDEVELOPMENTPLIST_PATH"]
    readonly property string pkgInfoPath: bundleSettingsProbe.xcodeSettings["PKGINFO_PATH"]
    readonly property string versionPlistPath: bundleSettingsProbe.xcodeSettings["VERSIONPLIST_PATH"]

    readonly property string executablePath: bundleSettingsProbe.xcodeSettings["EXECUTABLE_PATH"]

    readonly property string contentsFolderPath: bundleSettingsProbe.xcodeSettings["CONTENTS_FOLDER_PATH"]
    readonly property string documentationFolderPath: bundleSettingsProbe.xcodeSettings["DOCUMENTATION_FOLDER_PATH"]
    readonly property string executableFolderPath: bundleSettingsProbe.xcodeSettings["EXECUTABLE_FOLDER_PATH"]
    readonly property string executablesFolderPath: bundleSettingsProbe.xcodeSettings["EXECUTABLES_FOLDER_PATH"]
    readonly property string frameworksFolderPath: bundleSettingsProbe.xcodeSettings["FRAMEWORKS_FOLDER_PATH"]
    readonly property string javaFolderPath: bundleSettingsProbe.xcodeSettings["JAVA_FOLDER_PATH"]
    readonly property string localizedResourcesFolderPath: bundleSettingsProbe.xcodeSettings["LOCALIZED_RESOURCES_FOLDER_PATH"]
    readonly property string pluginsFolderPath: bundleSettingsProbe.xcodeSettings["PLUGINS_FOLDER_PATH"]
    readonly property string privateHeadersFolderPath: bundleSettingsProbe.xcodeSettings["PRIVATE_HEADERS_FOLDER_PATH"]
    readonly property string publicHeadersFolderPath: bundleSettingsProbe.xcodeSettings["PUBLIC_HEADERS_FOLDER_PATH"]
    readonly property string scriptsFolderPath: bundleSettingsProbe.xcodeSettings["SCRIPTS_FOLDER_PATH"]
    readonly property string sharedFrameworksFolderPath: bundleSettingsProbe.xcodeSettings["SHARED_FRAMEWORKS_FOLDER_PATH"]
    readonly property string sharedSupportFolderPath: bundleSettingsProbe.xcodeSettings["SHARED_SUPPORT_FOLDER_PATH"]
    readonly property string unlocalizedResourcesFolderPath: bundleSettingsProbe.xcodeSettings["UNLOCALIZED_RESOURCES_FOLDER_PATH"]
    readonly property string versionsFolderPath: bundleSettingsProbe.xcodeSettings["VERSIONS_FOLDER_PATH"]

    // private properties
    property string _productTypeIdentifier: Bundle.productTypeIdentifier(product.type)

    property bool _useXcodeBuildSpecs: true // false to use ONLY the qbs build specs

    readonly property var extraEnv: ({
        "PRODUCT_BUNDLE_IDENTIFIER": identifier
    })

    readonly property var qmakeEnv: {
        return {
            "BUNDLEIDENTIFIER": identifier,
            "EXECUTABLE": product.targetName,
            "FULL_VERSION": product.version || "1.0", // CFBundleVersion
            "ICON": product.targetName, // ### QBS-73
            "LIBRARY": product.targetName,
            "SHORT_VERSION": product.version || "1.0", // CFBundleShortVersionString
            "TYPEINFO": signature // CFBundleSignature
        };
    }

    readonly property var defaultInfoPlist: {
        return {
            CFBundleDevelopmentRegion: "en", // default localization
            CFBundleDisplayName: product.targetName, // localizable
            CFBundleExecutable: product.targetName,
            CFBundleIdentifier: identifier,
            CFBundleInfoDictionaryVersion: "6.0",
            CFBundleName: product.targetName, // short display name of the bundle, localizable
            CFBundlePackageType: packageType,
            CFBundleShortVersionString: product.version || "1.0", // "release" version number, localizable
            CFBundleSignature: signature, // legacy creator code in Mac OS Classic, can be ignored
            CFBundleVersion: product.version || "1.0.0" // build version number, must be 3 octets
        };
    }

    validate: {
        if (!qbs.targetOS.contains("darwin"))
            return;
        if (!bundleSettingsProbe.found) {
            var error = "Bundle product type " + _productTypeIdentifier + " is not supported.";
            if ((_productTypeIdentifier || "").startsWith("com.apple.product-type."))
                error += " You may need to upgrade Xcode.";
            throw error;
        }

        var validator = new ModUtils.PropertyValidator("bundle");
        validator.setRequiredProperty("bundleName", bundleName);
        validator.setRequiredProperty("infoPlistPath", infoPlistPath);
        validator.setRequiredProperty("pbdevelopmentPlistPath", pbdevelopmentPlistPath);
        validator.setRequiredProperty("pkgInfoPath", pkgInfoPath);
        validator.setRequiredProperty("versionPlistPath", versionPlistPath);
        validator.setRequiredProperty("executablePath", executablePath);
        validator.setRequiredProperty("contentsFolderPath", contentsFolderPath);
        validator.setRequiredProperty("documentationFolderPath", documentationFolderPath);
        validator.setRequiredProperty("executableFolderPath", executableFolderPath);
        validator.setRequiredProperty("executablesFolderPath", executablesFolderPath);
        validator.setRequiredProperty("frameworksFolderPath", frameworksFolderPath);
        validator.setRequiredProperty("javaFolderPath", javaFolderPath);
        validator.setRequiredProperty("localizedResourcesFolderPath", localizedResourcesFolderPath);
        validator.setRequiredProperty("pluginsFolderPath", pluginsFolderPath);
        validator.setRequiredProperty("privateHeadersFolderPath", privateHeadersFolderPath);
        validator.setRequiredProperty("publicHeadersFolderPath", publicHeadersFolderPath);
        validator.setRequiredProperty("scriptsFolderPath", scriptsFolderPath);
        validator.setRequiredProperty("sharedFrameworksFolderPath", sharedFrameworksFolderPath);
        validator.setRequiredProperty("sharedSupportFolderPath", sharedSupportFolderPath);
        validator.setRequiredProperty("unlocalizedResourcesFolderPath", unlocalizedResourcesFolderPath);

        if (packageType === "FMWK") {
            validator.setRequiredProperty("frameworkVersion", frameworkVersion);
            validator.setRequiredProperty("versionsFolderPath", versionsFolderPath);
        }

        // extension and infoStringsPath might not be set
        return validator.validate();
    }

    FileTagger {
        fileTags: ["infoplist"]
        patterns: ["Info.plist", "*-Info.plist"]
    }

    // TODO: Remove in 1.6 (deprecated, backwards compatibility)
    property path infoPlistFile
    Group { name: "Info.plist"; files: bundle.infoPlistFile ? [bundle.infoPlistFile] : [] }

    Rule {
        condition: qbs.targetOS.contains("darwin")
        multiplex: true
        inputs: ["qbs", "infoplist", "partial_infoplist"]

        outputFileTags: ["aggregate_infoplist"]
        outputArtifacts: {
            var artifacts = [];
            var embed = ModUtils.moduleProperty(product, "embedInfoPlist");
            if (ModUtils.moduleProperty(product, "isBundle") || embed) {
                artifacts.push({
                    filePath: FileInfo.joinPaths(
                                  product.destinationDirectory, embed
                                      ? product.name + "-Info.plist"
                                      : ModUtils.moduleProperty(product, "infoPlistPath")),
                    fileTags: ["aggregate_infoplist"]
                });
            }
            return artifacts;
        }

        prepare: {
            var cmd = new JavaScriptCommand();
            cmd.description = "generating Info.plist for " + product.name;
            cmd.highlight = "codegen";
            cmd.infoPlistFiles = inputs.infoplist;
            cmd.partialInfoPlistFiles = inputs.partial_infoplist;
            cmd.infoPlist = ModUtils.moduleProperty(product, "infoPlist") || {};
            cmd.processInfoPlist = ModUtils.moduleProperty(product, "processInfoPlist");
            cmd.infoPlistFormat = ModUtils.moduleProperty(product, "infoPlistFormat");
            cmd.extraEnv = ModUtils.moduleProperty(product, "extraEnv");
            cmd.qmakeEnv = ModUtils.moduleProperty(product, "qmakeEnv");

            cmd.buildEnv = product.moduleProperty("cpp", "buildEnv");
            cmd.defines = product.moduleProperty("cpp", "defines");
            cmd.platformDefines = product.moduleProperty("cpp", "platformDefines");
            cmd.compilerDefines = product.moduleProperty("cpp", "compilerDefines");
            cmd.allDefines = [].concat(cmd.defines || []).concat(cmd.platformDefines || []).concat(cmd.compilerDefines || []);

            cmd.developerPath = product.moduleProperty("xcode", "developerPath");
            cmd.platformInfoPlist = product.moduleProperty("xcode", "platformInfoPlist");
            cmd.sdkSettingsPlist = product.moduleProperty("xcode", "sdkSettingsPlist");
            cmd.toolchainInfoPlist = product.moduleProperty("xcode", "toolchainInfoPlist");

            cmd.osBuildVersion = product.moduleProperty("qbs", "hostOSBuildVersion");

            cmd.sourceCode = function() {
                var plist, process, key, i;

                // Contains the combination of default, file, and in-source keys and values
                // Start out with the contents of this file as the "base", if given
                var aggregatePlist = {};
                for (i in infoPlistFiles) {
                    aggregatePlist = BundleTools.infoPlistContents(infoPlistFiles[i].filePath);
                    infoPlistFormat = (infoPlistFormat === "same-as-input")
                            ? BundleTools.infoPlistFormat(infoPlistFiles[i].filePath)
                            : "xml1";
                    break;
                }

                // Add local key-value pairs (overrides equivalent keys specified in the file if
                // one was given)
                for (key in infoPlist) {
                    if (infoPlist.hasOwnProperty(key))
                        aggregatePlist[key] = infoPlist[key];
                }

                // Do some postprocessing if desired
                if (processInfoPlist) {
                    // Add default values to the aggregate plist if the corresponding keys
                    // for those values are not already present
                    var defaultValues = ModUtils.moduleProperty(product, "defaultInfoPlist");
                    for (key in defaultValues) {
                        if (defaultValues.hasOwnProperty(key) && !(key in aggregatePlist))
                            aggregatePlist[key] = defaultValues[key];
                    }

                    // Add keys from platform's Info.plist if not already present
                    var platformInfo = {};
                    var sdkSettings = {};
                    var toolchainInfo = {};
                    if (developerPath) {
                        plist = new PropertyList();
                        try {
                            plist.readFromFile(platformInfoPlist);
                            platformInfo = plist.toObject();
                        } finally {
                            plist.clear();
                        }

                        var additionalProps = platformInfo["AdditionalInfo"];
                        for (key in additionalProps) {
                            // override infoPlist?
                            if (additionalProps.hasOwnProperty(key) && !(key in aggregatePlist))
                                aggregatePlist[key] = defaultValues[key];
                        }
                        props = platformInfo['OverrideProperties'];
                        for (key in props) {
                            aggregatePlist[key] = props[key];
                        }

                        plist = new PropertyList();
                        try {
                            plist.readFromFile(sdkSettingsPlist);
                            sdkSettings = plist.toObject();
                        } finally {
                            plist.clear();
                        }

                        plist = new PropertyList();
                        try {
                            plist.readFromFile(toolchainInfoPlist);
                            toolchainInfo = plist.toObject();
                        } finally {
                            plist.clear();
                        }
                    }

                    aggregatePlist["BuildMachineOSBuild"] = osBuildVersion;

                    // setup env
                    env = {
                        "SDK_NAME": sdkSettings["CanonicalName"],
                        "XCODE_VERSION_ACTUAL": toolchainInfo["DTXcode"],
                        "SDK_PRODUCT_BUILD_VERSION": toolchainInfo["DTPlatformBuild"],
                        "GCC_VERSION": platformInfo["DTCompiler"],
                        "XCODE_PRODUCT_BUILD_VERSION": platformInfo["DTPlatformBuild"],
                        "PLATFORM_PRODUCT_BUILD_VERSION": platformInfo["ProductBuildVersion"],
                    }
                    env["MAC_OS_X_PRODUCT_BUILD_VERSION"] = osBuildVersion;

                    for (key in extraEnv)
                        env[key] = extraEnv[key];

                    for (key in buildEnv)
                        env[key] = buildEnv[key];

                    for (key in qmakeEnv)
                        env[key] = qmakeEnv[key];

                    for (i = 0; i < allDefines.length; ++i) {
                        var parts = allDefines[i].split('=');
                        env[parts[0]] = parts[1];
                    }

                    DarwinTools.expandPlistEnvironmentVariables(aggregatePlist, env, true);

                    // Add keys from partial Info.plists from asset catalogs, XIBs, and storyboards
                    for (i in partialInfoPlistFiles) {
                        var partialInfoPlist = BundleTools.infoPlistContents(partialInfoPlistFiles[i].filePath) || {};
                        for (key in partialInfoPlist) {
                            if (partialInfoPlist.hasOwnProperty(key))
                                aggregatePlist[key] = partialInfoPlist[key];
                        }
                    }
                }

                // Anything with an undefined or otherwise empty value should be removed
                // Only JSON-formatted plists can have null values, other formats error out
                // This also follows Xcode behavior
                DarwinTools.cleanPropertyList(aggregatePlist);

                if (infoPlistFormat === "same-as-input")
                    infoPlistFormat = "xml1";

                var validFormats = [ "xml1", "binary1", "json" ];
                if (!validFormats.contains(infoPlistFormat))
                    throw("Invalid Info.plist format " + infoPlistFormat + ". " +
                          "Must be in [xml1, binary1, json].");

                // Write the plist contents in the format appropriate for the current platform
                plist = new PropertyList();
                try {
                    plist.readFromObject(aggregatePlist);
                    plist.writeToFile(outputs.aggregate_infoplist[0].filePath, infoPlistFormat);
                } finally {
                    plist.clear();
                }
            }
            return cmd;
        }
    }

    Rule {
        condition: qbs.targetOS.contains("darwin")
        multiplex: true
        inputs: ["aggregate_infoplist"]

        outputFileTags: ["pkginfo"]
        outputArtifacts: {
            var artifacts = [];
            if (ModUtils.moduleProperty(product, "isBundle") && ModUtils.moduleProperty(product, "generatePackageInfo")) {
                artifacts.push({
                    filePath: FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, "pkgInfoPath")),
                    fileTags: ["pkginfo"]
                });
            }
            return artifacts;
        }

        prepare: {
            var cmd = new JavaScriptCommand();
            cmd.description = "generating PkgInfo for " + product.name;
            cmd.highlight = "codegen";
            cmd.sourceCode = function() {
                var infoPlist = BundleTools.infoPlistContents(inputs.aggregate_infoplist[0].filePath);

                var pkgType = infoPlist['CFBundlePackageType'];
                if (!pkgType)
                    throw("CFBundlePackageType not found in Info.plist; this should not happen");

                var pkgSign = infoPlist['CFBundleSignature'];
                if (!pkgSign)
                    throw("CFBundleSignature not found in Info.plist; this should not happen");

                var pkginfo = new TextFile(outputs.pkginfo[0].filePath, TextFile.WriteOnly);
                pkginfo.write(pkgType + pkgSign);
                pkginfo.close();
            }
            return cmd;
        }
    }

    Rule {
        condition: qbs.targetOS.contains("darwin")
        multiplex: true
        inputs: ["aggregate_infoplist", "pkginfo", "hpp",
                 "icns", "resourcerules", "xcent",
                 "compiled_ibdoc", "compiled_assetcatalog",
                 "xcode.provisioningprofile.main"]

        outputFileTags: ["bundle",
            "bundle.symlink.headers", "bundle.symlink.private-headers",
            "bundle.symlink.resources", "bundle.symlink.executable",
            "bundle.symlink.version", "bundle.hpp", "bundle.resource",
            "bundle.provisioningprofile"]
        outputArtifacts: {
            var i, artifacts = [];
            if (ModUtils.moduleProperty(product, "isBundle")) {
                artifacts.push({
                    filePath: FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, "bundleName")),
                    fileTags: ["bundle"]
                });

                for (i in inputs["xcode.provisioningprofile.main"]) {
                    var ext = inputs["xcode.provisioningprofile.main"][i].fileName.split('.')[1];
                    artifacts.push({
                        filePath: FileInfo.joinPaths(product.destinationDirectory,
                                                     ModUtils.moduleProperty(product,
                                                                             "contentsFolderPath"),
                                                     "embedded." + ext),
                        fileTags: ["bundle.provisioningprofile"]
                    });
                }

                var packageType = ModUtils.moduleProperty(product, "packageType");
                var isShallow = ModUtils.moduleProperty(product, "isShallow");
                if (packageType === "FMWK" && !isShallow) {
                    var publicHeaders = ModUtils.moduleProperties(product, "publicHeaders");
                    if (publicHeaders && publicHeaders.length) {
                        artifacts.push({
                            filePath: FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, "bundleName"), "Headers"),
                            fileTags: ["bundle.symlink.headers"]
                        });
                    }

                    var privateHeaders = ModUtils.moduleProperties(product, "privateHeaders");
                    if (privateHeaders && privateHeaders.length) {
                        artifacts.push({
                            filePath: FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, "bundleName"), "PrivateHeaders"),
                            fileTags: ["bundle.symlink.private-headers"]
                        });
                    }

                    artifacts.push({
                        filePath: FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, "bundleName"), "Resources"),
                        fileTags: ["bundle.symlink.resources"]
                    });

                    artifacts.push({
                        filePath: FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, "bundleName"), product.targetName),
                        fileTags: ["bundle.symlink.executable"]
                    });

                    artifacts.push({
                        filePath: FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, "versionsFolderPath"), "Current"),
                        fileTags: ["bundle.symlink.version"]
                    });
                }

                var headerTypes = ["public", "private"];
                for (var h in headerTypes) {
                    var sources = ModUtils.moduleProperties(product, headerTypes[h] + "Headers");
                    var destination = FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, headerTypes[h] + "HeadersFolderPath"));
                    for (i in sources) {
                        artifacts.push({
                            filePath: FileInfo.joinPaths(destination, FileInfo.fileName(sources[i])),
                            fileTags: ["bundle.hpp"]
                        });
                    }
                }

                sources = ModUtils.moduleProperties(product, "resources");
                for (i in sources) {
                    destination = BundleTools.destinationDirectoryForResource(product, {baseDir: FileInfo.path(sources[i]), fileName: FileInfo.fileName(sources[i])});
                    artifacts.push({
                        filePath: FileInfo.joinPaths(destination, FileInfo.fileName(sources[i])),
                        fileTags: ["bundle.resource"]
                    });
                }
            }
            return artifacts;
        }

        prepare: {
            var i, cmd, commands = [];
            var packageType = ModUtils.moduleProperty(product, "packageType");

            var bundleType = "bundle";
            if (packageType === "APPL")
                bundleType = "application";
            if (packageType === "FMWK")
                bundleType = "framework";

            var bundles = outputs.bundle;
            for (i in bundles) {
                cmd = new Command("mkdir", ["-p", bundles[i].filePath]);
                cmd.description = "creating " + bundleType + " " + product.targetName;
                commands.push(cmd);

                cmd = new Command("touch", ["-c", bundles[i].filePath]);
                cmd.silent = true;
                commands.push(cmd);
            }

            // Product is unbundled
            if (commands.length === 0) {
                cmd = new JavaScriptCommand();
                cmd.silent = true;
                cmd.sourceCode = function () { };
                commands.push(cmd);
            }

            var symlinks = outputs["bundle.symlink.version"];
            for (i in symlinks) {
                cmd = new Command("ln", ["-sfn", ModUtils.moduleProperty(product, "frameworkVersion"),
                                  symlinks[i].filePath]);
                cmd.silent = true;
                commands.push(cmd);
            }

            var publicHeaders = outputs["bundle.symlink.headers"];
            for (i in publicHeaders) {
                cmd = new Command("ln", ["-sfn", "Versions/Current/Headers",
                                         publicHeaders[i].filePath]);
                cmd.silent = true;
                commands.push(cmd);
            }

            var privateHeaders = outputs["bundle.symlink.private-headers"];
            for (i in privateHeaders) {
                cmd = new Command("ln", ["-sfn", "Versions/Current/PrivateHeaders",
                                         privateHeaders[i].filePath]);
                cmd.silent = true;
                commands.push(cmd);
            }

            var resources = outputs["bundle.symlink.resources"];
            for (i in resources) {
                cmd = new Command("ln", ["-sfn", "Versions/Current/Resources",
                                         resources[i].filePath]);
                cmd.silent = true;
                commands.push(cmd);
            }

            var executables = outputs["bundle.symlink.executable"];
            for (i in executables) {
                cmd = new Command("ln", ["-sf", FileInfo.joinPaths("Versions", "Current", product.targetName),
                                         executables[i].filePath]);
                cmd.silent = true;
                commands.push(cmd);
            }

            var provisioningProfiles = outputs["bundle.provisioningprofile"];
            for (i in provisioningProfiles) {
                cmd = new JavaScriptCommand();
                cmd.description = "copying provisioning profile";
                cmd.highlight = "filegen";
                cmd.source = inputs["xcode.provisioningprofile.main"][i].filePath;
                cmd.destination = provisioningProfiles[i].filePath;
                cmd.sourceCode = function() {
                    File.copy(source, destination);
                };
                commands.push(cmd);
            }

            cmd = new JavaScriptCommand();
            cmd.description = "copying public headers";
            cmd.highlight = "filegen";
            cmd.sources = ModUtils.moduleProperties(product, "publicHeaders");
            cmd.destination = FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, "publicHeadersFolderPath"));
            cmd.sourceCode = function() {
                var i;
                for (var i in sources) {
                    File.copy(sources[i], FileInfo.joinPaths(destination, FileInfo.fileName(sources[i])));
                }
            };
            if (cmd.sources && cmd.sources.length)
                commands.push(cmd);

            cmd = new JavaScriptCommand();
            cmd.description = "copying private headers";
            cmd.highlight = "filegen";
            cmd.sources = ModUtils.moduleProperties(product, "privateHeaders");
            cmd.destination = FileInfo.joinPaths(product.destinationDirectory, ModUtils.moduleProperty(product, "privateHeadersFolderPath"));
            cmd.sourceCode = function() {
                var i;
                for (var i in sources) {
                    File.copy(sources[i], FileInfo.joinPaths(destination, FileInfo.fileName(sources[i])));
                }
            };
            if (cmd.sources && cmd.sources.length)
                commands.push(cmd);

            cmd = new JavaScriptCommand();
            cmd.description = "copying resources";
            cmd.highlight = "filegen";
            cmd.sources = ModUtils.moduleProperties(product, "resources");
            cmd.sourceCode = function() {
                var i;
                for (var i in sources) {
                    var destination = BundleTools.destinationDirectoryForResource(product, {baseDir: FileInfo.path(sources[i]), fileName: FileInfo.fileName(sources[i])});
                    File.copy(sources[i], FileInfo.joinPaths(destination, FileInfo.fileName(sources[i])));
                }
            };
            if (cmd.sources && cmd.sources.length)
                commands.push(cmd);

            if (product.moduleProperty("qbs", "hostOS").contains("darwin")) {
                for (i in bundles) {
                    var actualSigningIdentity = product.moduleProperty("xcode", "actualSigningIdentity");
                    var codesignDisplayName = product.moduleProperty("xcode", "actualSigningIdentityDisplayName");
                    if (actualSigningIdentity) {
                        // If this is a framework, we need to sign its versioned directory
                        var subpath = "";
                        var frameworkVersion = ModUtils.moduleProperty(product, "frameworkVersion");
                        if (frameworkVersion) {
                            subpath = ModUtils.moduleProperty(product, "contentsFolderPath");
                            subpath = subpath.substring(subpath.indexOf(ModUtils.moduleProperty("qbs", "pathSeparator")));
                        }

                        var args = product.moduleProperty("xcode", "codesignFlags") || [];
                        args.push("--force");
                        args.push("--sign", actualSigningIdentity);
                        args = args.concat(DarwinTools._codeSignTimestampFlags(product));

                        for (var j in inputs.xcent) {
                            args.push("--entitlements", inputs.xcent[j].filePath);
                            break; // there should only be one
                        }
                        args.push(bundles[i].filePath + subpath);

                        cmd = new Command(product.moduleProperty("xcode", "codesignPath"), args);
                        cmd.description = "codesign "
                                + ModUtils.moduleProperty(product, "bundleName")
                                + " using " + codesignDisplayName
                                + " (" + actualSigningIdentity + ")";
                        commands.push(cmd);
                    }

                    if (product.type.contains("application")
                            && product.moduleProperty("qbs", "targetOS").contains("osx")) {
                        cmd = new Command(ModUtils.moduleProperty(product, "lsregisterPath"),
                                          ["-f", bundles[i].filePath]);
                        cmd.description = "register " + ModUtils.moduleProperty(product, "bundleName");
                        commands.push(cmd);
                    }
                }
            }

            return commands;
        }
    }
}