forked from play-co/native-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
1474 lines (1239 loc) · 44 KB
/
build.js
File metadata and controls
1474 lines (1239 loc) · 44 KB
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* @license
* This file is part of the Game Closure SDK.
*
* The Game Closure SDK is free software: you can redistribute it and/or modify
* it under the terms of the Mozilla Public License v. 2.0 as published by Mozilla.
* The Game Closure SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Mozilla Public License v. 2.0 for more details.
* You should have received a copy of the Mozilla Public License v. 2.0
* along with the Game Closure SDK. If not, see <http://mozilla.org/MPL/2.0/>.
*/
var path = require("path");
var ff = require("ff");
var clc = require("cli-color");
var wrench = require('wrench');
var async = require('async');
var fs = require('fs');
var plist = require('plist');
var logger;
var rsyncLogger;
//// Addons
var installAddons = function(builder, project, opts, addonConfig, next) {
var paths = builder.common.paths;
var addons = project.getAddonConfig();
if (!Array.isArray(addons)) {
addons = Object.keys(addons);
}
var f = ff(this, function() {
var addonConfigMap = {};
var next = f.slotPlain();
var addonQueue = [];
var checkedAddonMap = {};
if (addons) {
var missingAddons = [];
for (var ii = 0; ii < addons.length; ++ii) {
addonQueue.push(addons[ii]);
}
var processAddonQueue = function() {
var addon = null;
if (addonQueue.length > 0) {
addon = addonQueue.shift();
} else {
if (missingAddons.length > 0) {
logger.error("=========================================================================");
logger.error("Missing addons =>", JSON.stringify(missingAddons));
logger.error("=========================================================================");
process.exit(1);
}
next(addonConfigMap);
return;
}
var addonConfig = paths.addons(addon, 'ios', 'config.json');
if (fs.existsSync(addonConfig)) {
fs.readFile(addonConfig, 'utf8', function(err, data) {
if (!err && data) {
try {
var config = JSON.parse(data);
addonConfigMap[addon] = data;
if (config.addonDependencies && config.addonDependencies.length > 0) {
for (var a in config.addonDependencies) {
var dep = config.addonDependencies[a];
if (!checkedAddonMap[dep]) {
checkedAddonMap[dep] = true;
addonQueue.push(dep);
}
}
}
} catch (err) {
throw new Error("Malformed ios config file (bad JSON?) for addon '" + addon + "'\r\n" + err + "\r\n" + err.stack);
}
}
processAddonQueue();
});
} else {
if (!checkedAddonMap[addon]) {
checkedAddonMap[addon] = true;
}
if (missingAddons.indexOf(addon) == -1) {
missingAddons.push(addon);
logger.warn("Unable to find iOS addon config file", addonConfig);
}
processAddonQueue();
}
};
processAddonQueue();
} else {
next({});
}
}, function(addonConfigMap) {
if (addonConfigMap) {
var configuredAddons = [];
for (var addon in addonConfigMap) {
try {
addonConfig[addon] = JSON.parse(addonConfigMap[addon]);
configuredAddons.push(addon);
} catch (err) {
throw new Error("Unable to parse addon configuration for: " + addon + "\r\nError: " + err + "\r\n" + err.stack);
}
}
logger.log("Configured addons:", JSON.stringify(configuredAddons));
}
}).error(function(err) {
logger.error("Error while installing addons:", err, err.stack);
}).cb(next);
}
var replaceTextBetween = function(text, startToken, endToken, replaceText) {
var newText = "";
var start = text.indexOf(startToken);
var end = text.indexOf(endToken);
if (start == -1 || end == -1) {
return text;
}
var offset = text.substring(start).indexOf("\n") + 1;
var afterStart = start + offset;
newText += text.substring(0, afterStart);
newText += replaceText;
newText += text.substring(end);
return newText;
}
var installAddonsProject = function(builder, opts, next) {
var addonConfig = opts.addonConfig;
var contents = opts.contents;
var destDir = opts.destDir;
var paths = builder.common.paths;
var manifest = opts.manifest;
var userDefined = {};
var f = ff(this, function () {
var frameworks = {}, frameworkPaths = {};
for (var key in addonConfig) {
var config = addonConfig[key];
if (config.frameworks) {
for (var ii = 0; ii < config.frameworks.length; ++ii) {
var framework = config.frameworks[ii];
if (path.extname(framework) === "") {
framework = path.basename(framework);
} else {
framework = paths.addons(key, 'ios', framework);
//var frameworkRelPath = "$(SRCROOT)" + path.relative(path.join(destDir, "tealeaf"), path.dirname(framework));
var frameworkRelPath = path.dirname(framework);
frameworkPaths[frameworkRelPath] = 1;
}
frameworks[framework] = 1;
}
}
if (config.userDefined) {
for (var ii = 0; ii < config.userDefined.length; ++ii) {
var ud = config.userDefined[ii];
userDefined[ud] = 1;
}
}
}
var frameworkId = 1;
var ldFiles = [];
for (var framework in frameworks) {
var fileType, sourceTree, demoKey;
var filename = path.basename(framework);
var fileEncoding = "";
var noWeak = false;
var noName = false;
// If extension is framework,
if (path.extname(framework) === ".a") {
logger.log("Installing library:", framework);
fileType = "archive.ar";
sourceTree = '"<group>"';
framework = path.relative(path.join(destDir, "tealeaf"), framework);
demoKey = "System/Library/Frameworks/UIKit.framework";
if (filename.indexOf("lib") == 0) {
var ldFile = path.basename(filename.substr(3), ".a");
logger.log("Will be adding", ldFile, "to LDFLAGS");
ldFiles.push(ldFile);
}
} else if (path.extname(framework) === ".xib") {
logger.log("Installing xib:", framework);
fileType = 'file.xib'
sourceTree = '"<group>"';
framework = path.relative(path.join(destDir, "tealeaf"), framework);
demoKey = "path = icon144.png";
fileEncoding = "fileEncoding = 4; ";
noWeak = true;
} else if (path.extname(framework) === ".storyboard") {
logger.log("Installing xib:", framework);
fileType = 'file.storyboard'
sourceTree = '"<group>"';
framework = path.relative(path.join(destDir, "tealeaf/platform"), framework);
demoKey = "path = PluginManager.mm";
fileEncoding = "fileEncoding = 4; ";
noWeak = true;
} else if (path.extname(framework) === ".bundle") {
logger.log("Installing resource bundle:", framework);
fileType = '"wrapper.plug-in"'
sourceTree = '"<group>"';
framework = path.relative(path.join(destDir, "tealeaf/resources"), framework);
demoKey = "path = resources.bundle";
} else if (path.extname(framework) === ".png") {
logger.log("Installing resource PNG:", framework);
fileType = 'image.png'
sourceTree = '"<group>"';
framework = path.relative(path.join(destDir, "tealeaf/platform"), framework);
demoKey = "path = PluginManager.mm";
noWeak = true;
noName = true;
} else if (path.extname(framework) === ".framework") {
logger.log("Installing framework:", framework);
fileType = "wrapper.framework";
sourceTree = '"<group>"';
framework = path.relative(path.join(destDir, "tealeaf"), framework);
demoKey = "System/Library/Frameworks/UIKit.framework";
} else if (path.extname(framework) === ".dylib") {
logger.log("Installing dynamic library:", framework);
fileType = "compiled.mach-o.dylib";
sourceTree = 'SDKROOT';
framework = "usr/lib/" + filename;
demoKey = "System/Library/Frameworks/UIKit.framework";
} else if (path.extname(framework) === "") {
logger.log("Installing system framework:", framework);
fileType = "wrapper.framework";
sourceTree = 'SDKROOT';
framework = "System/Library/Frameworks/" + filename + ".framework";
demoKey = "System/Library/Frameworks/UIKit.framework";
}
var uuid1 = "BAADBEEF";
uuid1 += String('00000000' + frameworkId.toString(16).toUpperCase()).slice(-8);
uuid1 += "DEADDEED"; // Unique from TTF installer
var uuid2 = "DEADD00D";
uuid2 += String('00000000' + frameworkId.toString(16).toUpperCase()).slice(-8);
uuid2 += "BAADFEED";
++frameworkId;
// Read out UUID for storekit
var uuid1_storekit, uuid2_storekit;
// Inject PBXFileReference
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
if (line.indexOf(demoKey) > 0) {
uuid1_storekit = line.match(/(?=[ \t]*)([A-F,0-9]+?)(?=[ \t].)/g)[0];
var insertString = "\t\t" + uuid1 + " /* " + filename + " */ = {isa = PBXFileReference; " + fileEncoding + "lastKnownFileType = " + fileType + ";";
if (!noName) {
insertString += " name = " + filename + ";"
}
insertString += ' path = "' + framework + '";';
insertString += " sourceTree = " + sourceTree + "; };";
contents.splice(++ii, 0, insertString);
logger.log(" - Found PBXFileReference template on line", ii, "with uuid", uuid1_storekit);
break;
}
}
// Inject reference to PBXFileReference
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
// If line has the storekit UUID,
if (line.indexOf(uuid1_storekit) > 0 && line.indexOf("PBXFileReference") == -1 && line.indexOf("PBXBuildFile") == -1) {
contents.splice(++ii, 0, "\t\t\t" + uuid1 + " /* " + filename + " */,");
logger.log(" - Found PBXFileReference reference template on line", ii);
break;
}
}
// Inject PBXBuildFile
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
// If line has the storekit UUID,
if (line.indexOf("fileRef = " + uuid1_storekit) > 0) {
uuid2_storekit = line.match(/(?=[ \t]*)([A-F,0-9]+?)(?=[ \t].)/g)[0];
var insertString = "\t\t" + uuid2 + " /* " + filename + " in Frameworks */ = {isa = PBXBuildFile; fileRef = " + uuid1 + " /* " + filename + " */;";
if (!noWeak) {
insertString += " settings = {ATTRIBUTES = (Weak, ); };";
}
insertString += " };";
contents.splice(++ii, 0, insertString);
logger.log(" - Found PBXBuildFile template on line", ii, "with uuid", uuid2_storekit);
break;
}
}
var uuid2_match_regex = new RegExp("/^[ \\t]+" + uuid2_storekit + "/");
// Inject reference to PBXBuildFile
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
// If line has the storekit UUID,
if (line.indexOf(uuid2_storekit) > 0 && line.indexOf("PBXFileReference") == -1 && line.indexOf("PBXBuildFile") == -1) {
contents.splice(++ii, 0, "\t\t\t" + uuid2 + " /* " + filename + " in Frameworks */,");
logger.log(" - Found PBXBuildFile reference template on line", ii);
break;
}
}
}
var searchKeys = ["FRAMEWORK_SEARCH_PATHS", "LIBRARY_SEARCH_PATHS"];
for (var searchKeyIndex = 0; searchKeyIndex < searchKeys.length; ++searchKeyIndex) {
var searchKey = searchKeys[searchKeyIndex];
// Set up framework search paths
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
if (line.indexOf(searchKey) == -1) {
continue;
}
logger.log("Found", searchKey, "property on line", ii);
var iiFw = ii;
var semiIdx = line.indexOf(";");
if (semiIdx > 0) {
// Convert single value field to multi-value field
var startIdx = line.indexOf("= ");
if (startIdx == -1) {
logger.log(" - Invalid", searchKey, "found.");
} else {
contents.splice(ii, 1, line.substring(0, startIdx + 2) + "(");
contents.splice(ii+1, 0, "\t\t\t\t)"+line.substring(semiIdx));
var existingPath = line.substring(startIdx + 2, semiIdx);
if (existingPath != '""') {
contents.splice(ii+1, 0, "\t\t\t\t\t"+existingPath);
}
}
}
// Look for the end to append new paths
for (++ii; ii < contents.length; ++ii) {
line = contents[ii];
if (line.indexOf(";") == -1) {
continue;
}
for (var key in frameworkPaths) {
// Only add the leading comma if there is a value before this line
if (ii-1 != iiFw) {
// If previous line does not already have a comma,
var prevLine = contents[ii-1];
if (prevLine.indexOf(",", prevLine.length - 1) === -1) {
contents[ii-1] = prevLine + ",";
}
}
contents.splice(++ii-1, 0, "\t\t\t\t\t" + '"' + key + '"')
logger.log(" - Installing", key, "search path on line", ii);
}
break;
}
}
}
if (ldFiles.length > 0) {
// Flip order of LDFLAGS
ldFiles.reverse();
var searchKey = "OTHER_LDFLAGS";
// Set up framework search paths
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
if (line.indexOf(searchKey) == -1) {
continue;
}
logger.log("Found", searchKey, "property on line", ii);
var iiFw = ii;
var semiIdx = line.indexOf(";");
if (semiIdx > 0) {
// Convert single value field to multi-value field
var startIdx = line.indexOf("= ");
if (startIdx == -1) {
logger.log(" - Invalid", searchKey, "found.");
} else {
contents.splice(ii, 1, line.substring(0, startIdx + 2) + "(");
contents.splice(ii+1, 0, "\t\t\t\t)"+line.substring(semiIdx));
var existingPath = line.substring(startIdx + 2, semiIdx);
if (existingPath != '""') {
contents.splice(ii+1, 0, "\t\t\t\t\t"+existingPath);
}
}
}
// Look for the end to append new paths
for (++ii; ii < contents.length; ++ii) {
line = contents[ii];
if (line.indexOf(";") == -1) {
continue;
}
for (var jj = 0; jj < ldFiles.length; ++jj) {
// Only add the leading comma if there is a value before this line
if (ii-1 != iiFw) {
// If previous line does not already have a comma,
var prevLine = contents[ii-1];
if (prevLine.indexOf(",", prevLine.length - 1) === -1) {
contents[ii-1] = prevLine + ",";
}
}
contents.splice(++ii-1, 0, "\t\t\t\t\t" + '"-l' + ldFiles[jj] + '"')
logger.log(" - Installing", key, "search path on line", ii);
}
break;
}
}
}
// Install user-defined keys:
var injectOffsets = [];
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
if (line.indexOf("INFOPLIST_FILE") != -1) {
injectOffsets.push(ii + 1);
}
}
if (injectOffsets.length <= 0) {
logger.error("Unable to find INFOPLIST_FILE injection line for user-defined keys for some reason.");
process.exit(1);
}
var extractNestedValue = function(obj, key) {
var i=0;
var parts = key.split('.');
var val = obj;
while(i!=parts.length) {
val = val[parts[i++]];
}
return val;
};
for (var key in userDefined) {
var value = manifest.ios && manifest.ios[key] || manifest.addons && extractNestedValue(manifest.addons, key);
if (!value) {
logger.error("Installing user-defined key", key, "failed: Could not find value in game manifest under ios section.");
process.exit(1);
} else {
var injectLine = '\t\t\t\t' + key + ' = "' + value + '";';
for (var ii = 0; ii < injectOffsets.length; ++ii) {
// Increment offset since the previous splice moved the injection point
injectOffsets[ii] += ii;
contents.splice(injectOffsets[ii], 0, injectLine);
}
logger.log("Installed user-defined key", key, "=", value);
}
}
// groups will store one array per plugin containing the filenames for the plugin
var groups = {};
// codes will store a map between filenames and uuids that we should inject later
var codes = {};
// codeToARCMap will store a map between filenames and boolean: true -> needs ARC
var codeToARCMap = {};
// build the groups object from addonConfig
for (var key in addonConfig) {
var config = addonConfig[key];
var files = [];
if (config.code) {
for (var ii = 0; ii < config.code.length; ++ii) {
var code = config.code[ii];
code = paths.addons(key, 'ios', code);
var file = path.relative(path.join(destDir, "tealeaf/platform"), code);
files.push(file);
}
}
if (config.arccode) {
for (var ii = 0; ii < config.arccode.length; ++ii) {
var code = config.arccode[ii];
code = paths.addons(key, 'ios', code);
var file = path.relative(path.join(destDir, "tealeaf/platform"), code);
files.push(file);
// Flag as needing ARC
codeToARCMap[file] = true;
}
}
if (files.length) {
groups[key] = files;
}
}
// Find the UUID for plugin manager (it's in the plugins group, which
// is where we want to inject our new groups)
var pluginManagerUUID;
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
if (line.indexOf("path = PluginManager.mm") > 0) {
pluginManagerUUID = line.match(/(?=[ \t]*)([A-F,0-9]+?)(?=[ \t].)/g)[0];
break;
}
}
if (!pluginManagerUUID) { throw new Error("Couldn't find PluginManager.mm for injection: looking for string 'path = PluginManager.mm'"); }
// find the group that contains PluginManager.mm UUID and create more groups above it
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
if (line.indexOf(pluginManagerUUID) > 0 && line.indexOf("PBXFileReference") == -1 && line.indexOf("PBXBuildFile") == -1) {
// we found the plugin group at line ii
break;
}
}
// line number where we insert the group ref in the parent group
// (add one since we want to insert *after* the reference to PluginManager.mm)
var insertGroupRefsAt = ii + 1;
// search in reverse to get to the start of the plugins group
while (--ii) {
if (/(?=[ \t]*)([A-F,0-9]+?)\s+.*?=\s+\{/g.test(contents[ii])) {
logger.log(" - Found PBXGroup for PluginManager.mm");
break;
}
}
if (!ii) { throw new Error("Couldn't find a group containing PluginManager.mm"); }
// insert groups for each plugin
var codeId = 1;
Object.keys(groups).forEach(function (groupName, index) {
var groupUUID = "BAAFBEFF"
+ String('00000000' + index.toString(16).toUpperCase()).slice(-8)
+ "DEAFDEED";
// insert the group definition
contents.splice(ii++, 0, "\t\t" + groupUUID + " /* " + groupName + " */ = {\n"
+ "\t\t\tisa = PBXGroup;\n"
+ "\t\t\tchildren = (\n"
+ groups[groupName].map(function (filename) {
var basename = path.basename(filename);
// store UUIDs for insertion later
codes[filename] = {
uuid1: "BAAFBEEF"
+ String('00000000' + codeId.toString(16).toUpperCase()).slice(-8)
+ "DEAFDEED",
uuid2: "DEAFD00D"
+ String('00000000' + codeId.toString(16).toUpperCase()).slice(-8)
+ "BAAFFEED"
};
++codeId; // each file must have a unique ID
return "\t\t\t\t" + codes[filename].uuid1 + " /* " + basename + " */,";
}).join("\n") + "\n"
+ "\t\t\t);\n"
+ "\t\t\tname = " + groupName + ";\n"
+ "\t\t\tsourceTree = \"<group>\";\n"
+ "\t\t};");
// insert a reference to the group definition in the plugin group
++insertGroupRefsAt; // we inserted the full group definition above, so add 1
contents.splice(insertGroupRefsAt, 0, "\t\t\t\t" + groupUUID + " /* " + groupName + " */,");
++insertGroupRefsAt; // next group ref should be inserted on the line below this one
logger.log(" - Injected PBXGroup for " + groupName);
});
for (var code in codes) {
var needARC = codeToARCMap[code];
if (needARC) {
logger.log("Installing code:", code, "(WITH ARC)");
} else {
logger.log("Installing code:", code);
}
var ext = path.extname(code);
var fileType;
var skipBuild = false; // Do not add to build step?
if (ext === ".m") {
fileType = "sourcecode.c.objc";
} else if (ext === ".mm") {
fileType = "sourcecode.cpp.objcpp";
} else if (ext === ".c") {
fileType = "sourcecode.c.c";
} else if (ext === ".cpp" || ext === ".cc") {
fileType = "sourcecode.cpp.cpp";
} else if (ext === ".h" || ext == ".hpp") {
fileType = "sourcecode.c.h";
skipBuild = true;
} else {
throw new Error("Unsupported file type: " + code);
}
var filename = path.basename(code);
var uuid1 = codes[code].uuid1;
var uuid2 = codes[code].uuid2;
// Read out UUID for plugin manager
var uuid1_pm, uuid2_pm;
// Inject PBXFileReference
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
if (line.indexOf("path = PluginManager.mm") > 0) {
uuid1_pm = line.match(/(?=[ \t]*)([A-F,0-9]+?)(?=[ \t].)/g)[0];
contents.splice(++ii, 0, "\t\t" + uuid1 + " /* " + filename + " */ = "
+ "{"
+ "isa = PBXFileReference;"
+ " fileEncoding = 4;"
+ " lastKnownFileType = " + fileType + ";"
+ " path = \"" + code + "\";"
+ " name = \"" + filename + "\";"
+ " sourceTree = \"<group>\";"
+ " };");
logger.log(" - Found PBXFileReference template on line", ii, "with uuid", uuid1_pm);
break;
}
}
// If skipping build step injection,
if (skipBuild) {
logger.log(" - Skipping build step injection");
} else {
// Inject PBXBuildFile
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
// If line has the storekit UUID,
if (line.indexOf("fileRef = " + uuid1_pm) > 0) {
uuid2_pm = line.match(/(?=[ \t]*)([A-F,0-9]+?)(?=[ \t].)/g)[0];
var insertString = "\t\t" + uuid2 + " /* " + filename + " in Sources */ = {isa = PBXBuildFile; fileRef = " + uuid1 + " /* " + filename + " */;";
if (needARC) {
insertString += ' settings = {COMPILER_FLAGS = "-fobjc-arc"; };';
}
insertString += " };";
contents.splice(++ii, 0, insertString);
logger.log(" - Found PBXBuildFile template on line", ii, "with uuid", uuid2_pm);
break;
}
}
var uuid2_match_regex = new RegExp("/^[ \\t]+" + uuid2_pm + "/");
// Inject reference to PBXBuildFile
for (var ii = 0; ii < contents.length; ++ii) {
var line = contents[ii];
// If line has the storekit UUID,
if (line.indexOf(uuid2_pm) > 0 && line.indexOf("PBXFileReference") == -1 && line.indexOf("PBXBuildFile") == -1) {
contents.splice(++ii, 0, "\t\t\t" + uuid2 + " /* " + filename + " in Sources */,");
logger.log(" - Found PBXBuildFile reference template on line", ii);
break;
}
}
}
}
}).error(function(err) {
logger.error("Failure in installing addon project changes:", err, err.stack);
}).cb(next);
}
function installAddonsFiles(builder, opts, next) {
var destPath = opts.destPath;
var addonConfig = opts.addonConfig;
var f = ff(function () {
for (var addon in addonConfig) {
var config = addonConfig[addon];
if (config.resources) {
for (var ii = 0; ii < config.resources.length; ++ii) {
var destFile = builder.common.paths.addons(addon, 'ios', config.resources[ii]);
logger.log("Installing addon resource:", destFile, "for", addon);
builder.common.copyFileSync(destFile, path.join(destPath, path.basename(config.resources[ii])));
}
}
}
}).error(function(err) {
logger.error("Failure in installing addon files:", err, err.stack);
}).cb(next);
}
function installAddonsPList(builder, opts, next) {
var contents = opts.contents;
var f = ff(function () {
// For each addon,
for (var addon in opts.addonConfig) {
var config = opts.addonConfig[addon];
// If addon specifies PList mods,
if (config.plist) {
// For each PList mod,
for (var plistKey in config.plist) {
// Read value to inject
var manifestValue = config.plist[plistKey];
// Find injection point by walking JS object tree
var keys = plistKey.split('.');
var obj = contents;
var wrote = false;
for (var ii = 0; ii < keys.length; ++ii) {
var key = keys[ii];
var subkey = obj[key];
// If key DNE,
if (!subkey) {
if (ii != keys.length - 1) {
throw new Error("Manifest parent key not found:", plistKey);
}
obj[key] = manifestValue;
logger.log("Installing plist new key:", plistKey, "=", manifestValue);
wrote = true;
break;
} else {
var type = typeof subkey;
if (type === "object") {
if (subkey.length === undefined) {
obj = subkey;
} else {
if (ii != keys.length - 1) {
var foundSubKey = false;
for (var jj = 0; jj < keys.length; ++jj) {
if (subkey[jj][keys[ii + 1]]) {
foundSubKey = true;
obj = subkey[jj];
break;
}
}
if (!foundSubKey) {
throw new Error("Manifest array subkey is not found:", plistKey);
}
} else {
subkey.push(manifestValue);
logger.log("Installing plist array key:", plistKey, "=", manifestValue);
wrote = true;
break;
}
}
} else {
if (ii != keys.length - 1) {
throw new Error("Manifest parent key is value:", plistKey);
}
obj[key] = manifestValue;
logger.log("Installing plist object key:", plistKey, "=", manifestValue);
wrote = true;
break;
}
}
}
if (!wrote) {
throw new Error("Manifest key not found:", plistKey);
}
}
}
}
// Push modified contents along
f.pass(contents);
}).error(function(err) {
logger.error("Failure in installing PList keys:", err, err.stack);
}).cb(next);
}
//// Build
function validateSubmodules(next) {
var submodules = [
"tealeaf/core/core.h"
];
// Verify that submodules have been populated
var f = ff(function() {
var group = f.group();
for (var i = 0; i < submodules.length; ++i) {
fs.exists(path.join(__dirname, submodules[i]), group.slotPlain());
}
}, function(results) {
var allGood = results.every(function(element, index) {
if (!element) {
logger.error("Submodule " + path.dirname(submodules[index]) + " not found");
}
return element;
});
if (!allGood) {
f.fail("One of the submodules was not found. Make sure you have run submodule update --init on your clone of the iOS repo");
}
}).cb(next);
}
function removeKeysForObjects(parentObject, objects, keys) {
for (var ii = 0; ii < objects.length; ++ii) {
var objectName = objects[ii];
var obj = parentObject[objectName];
for (var jj = 0; jj < keys.length; ++jj) {
var key = keys[jj];
var index = obj.indexOf(key);
if (index !== -1) {
obj.splice(index, 1);
}
}
}
}
// Updates the given TeaLeafIOS-Info.plist file
function updatePListFile(builder, opts, next) {
var manifest = opts.manifest;
var bundleID = manifest.ios.bundleID;
if (!bundleID) {
throw new Error("Manifest file does not specify a bundleID under the ios section");
}
var f = ff(this, function() {
fs.readFile(opts.plistFilePath, 'utf8', f());
}, function(data) {
logger.log("Updating Info.plist file: ", opts.plistFilePath);
var contents = plist.parseStringSync(data);
// Remove unsupported modes
var orient = manifest.supportedOrientations;
if (orient.indexOf("landscape") == -1) {
logger.log("Orientations: Removing landscape support");
removeKeysForObjects(contents, ["UISupportedInterfaceOrientations", "UISupportedInterfaceOrientations~ipad"],
["UIInterfaceOrientationLandscapeRight", "UIInterfaceOrientationLandscapeLeft"]);
}
if (orient.indexOf("portrait") == -1) {
logger.log("Orientations: Removing portrait support");
removeKeysForObjects(contents, ["UISupportedInterfaceOrientations", "UISupportedInterfaceOrientations~ipad"],
["UIInterfaceOrientationPortrait", "UIInterfaceOrientationPortraitUpsideDown"]);
}
// Update the version numbers
contents.CFBundleShortVersionString = manifest.ios.version;
contents.CFBundleVersion = manifest.ios.version;
// If RenderGloss enabled,
if (manifest.ios.icons && manifest.ios.icons.renderGloss) {
// Note: Default is for Xcode to render it for you
logger.log("RenderGloss: Removing pre-rendered icon flag");
delete contents.UIPrerenderedIcon;
//delete contents.CFBundleIcons.CFBundlePrimaryIcon.UIPrerenderedIcon;
}
contents.CFBundleDisplayName = opts.title;
contents.CFBundleIdentifier = bundleID;
contents.CFBundleName = bundleID;
// For each URLTypes array entry,
var found = 0;
for (var ii = 0; ii < contents.CFBundleURLTypes.length; ++ii) {
var obj = contents.CFBundleURLTypes[ii];
// If it's the URLName one,
if (obj.CFBundleURLName) {
obj.CFBundleURLName = bundleID;
++found;
}
// If it's the URLSchemes one,
if (obj.CFBundleURLSchemes) {
// Note this blows away all the array entries
obj.CFBundleURLSchemes = [bundleID];
++found;
}
}
if (found != 2) {
throw new Error("Unable to update URLTypes");
}
installAddonsPList(builder, {
contents: contents,
addonConfig: opts.addonConfig,
manifest: opts.manifest
}, f());
}, function(contents) {
fs.writeFile(opts.plistFilePath, plist.build(contents).toString(), f());
}).error(function(err) {
logger.error("Failure while updating PList file:", err, err.stack);
process.exit(1);
}).cb(next);
}
// Create the iOS project
var DEFAULT_IOS_PRODUCT = 'TeaLeafIOS';
var NAMES_TO_REPLACE = /(PRODUCT_NAME)|(name = )|(productName = )/;
function updateIOSProjectFile(builder, opts, next) {
fs.readFile(opts.projectFile, 'utf8', function(err, data) {
if (err) {
next(err);
} else {
logger.log("Updating iOS project file:", opts.projectFile);
var contents = data.split('\n');
var i = 0, j = 0; // counters
// For each line,
contents = contents.map(function(line) {
// If it has 'PRODUCT_NAME' in it, replace the name
if (line.match(NAMES_TO_REPLACE)) {
line = line.replace(DEFAULT_IOS_PRODUCT, opts.bundleID);
}
return line;
});
// Run it through the plugin system before writing
installAddonsProject(builder, {
addonConfig: opts.addonConfig,
contents: contents,
destDir: opts.destDir,
manifest: opts.manifest
}, function() {
contents = contents.join('\n');
fs.writeFile(opts.projectFile, contents, 'utf8', function(err) {
next(err);
});
});