-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmetabase.js
More file actions
1330 lines (1223 loc) · 43.6 KB
/
metabase.js
File metadata and controls
1330 lines (1223 loc) · 43.6 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
/**
* Hyperloop Metabase Generator
* Copyright (c) 2015-2017 by Appcelerator, Inc.
*/
'use strict';
var spawn = require('child_process').spawn,
exec = require('child_process').exec,
path = require('path'),
fs = require('fs-extra'),
plist = require('plist'),
async = require('async'),
semver = require('semver'),
crypto = require('crypto'),
chalk = require('chalk'),
util = require('./util'),
swiftlilb = require('./swift'),
binary = path.join(__dirname, '..', 'bin', 'metabase');
/**
* return the configured SDK path
*/
function getSDKPath (sdkType, callback) {
exec('/usr/bin/xcrun --sdk ' + sdkType + ' --show-sdk-path', function (err, stdout) {
if (err) { return callback(err); }
return callback(null, stdout.trim());
});
}
/**
* convert an apple style version (9.0) to a semver compatible version
*/
function appleVersionToSemver (ver) {
var v = String(ver).split('.');
if (v.length === 1) {
return ver + '.0.0';
}
if (v.length === 2) {
return ver + '.0';
}
return ver;
}
/**
* return a parsed plist for a given framework
*/
function getPlistForFramework (info, callback) {
if (fs.existsSync(info)) {
var child = spawn('/usr/bin/plutil',['-convert', 'xml1', info, '-o', '-']);
var out = '';
child.stdout.on('data', function (buf) {
out += buf.toString();
});
child.on('close', function (ex) {
if (ex) {
return callback(new Error('plistutil cannot convert ' + info));
}
var result = plist.parse(out);
return callback(null, result);
});
} else {
return callback();
}
}
/**
* Creates a MD5 hash from the given string data.
*
* @param {String} data Data the hash will be generated for
* @return {String} The generated MD5 hash
*/
function createHashFromString (data) {
return crypto.createHash('md5').update(data).digest('hex');
}
var implRE = /@interface\s*(.*)/g,
swiftClassRE = /class\s*(\w+)/g;
function extractImplementations (fn, files) {
util.logger.trace('Extracting implementations from ' + fn.cyan);
var content = fs.readFileSync(fn).toString();
var matches;
if (/\.swift$/.test(fn)) {
matches = content.match(swiftClassRE);
if (matches && matches.length) {
matches.forEach(function (match) {
var m = swiftClassRE.exec(match);
if (m && m.length) {
files[m[1]] = fn;
}
});
}
} else {
matches = content.match(implRE);
var found = 0;
if (matches && matches.length) {
matches.forEach(function (match) {
// skip categories
var p = match.indexOf('(');
if (p < 0) {
var m = match.substring(11);
var i = m.indexOf(':');
// make sure this is an actual declaration (vs. comment);
if (i > 0) {
m = m.substring(0, i).trim();
// trim off any qualifiers such as
// @interface NSSet<__covariant ObjectType>
i = m.indexOf('<');
if (i > 0) {
m = m.substring(0, i).trim();
}
files[m] = fn;
found++;
}
} else {
var name = match.substring(11, p).trim();
if (!(name in files)) {
files[name] = fn;
found++;
}
}
});
}
if (!found) {
// convention for user-generated files like Foo+Bar.h where Bar is a
// category of Foo, we exclude those
if (fn.indexOf('+') < 0) {
files[path.basename(fn).replace('.h','').trim()] = fn;
}
}
}
}
/**
* Represents a module, which can be either a static library or a framework.
*/
class ModuleMetadata {
/**
* Constructs a new module metadata object
*
* @param {String} name Module name
* @param {String} path Full path to the module
* @param {String} type Module type, one of the MODULE_TYPE_* constants
*/
constructor(name, path, type) {
this.name = name;
this.path = path;
this.type = type;
this.isFramework = /.(xc)?framework$/.test(this.path);
this.introducedIn = null;
this.umbrellaHeader = null;
this.usesSwift = false;
this.typeMap = {};
}
/**
* Constant for a static module type
* @type {String}
*/
static get MODULE_TYPE_STATIC() {
return 'static';
}
/**
* Constant for a dynamic module type
* @type {String}
*/
static get MODULE_TYPE_DYNAMIC() {
return 'dynamic';
}
/**
* Determines wether this module is available in the given iOS version
*
* @param {String} iOSVersion iOS version identifier to check the availability for
* @return {Boolean} True if this module is available in the given iOS version, false if not
*/
isAvailable(iOSVersion) {
if (semver.valid(this.introducedIn) === null) {
return true;
}
return semver.lte(this.introducedIn, appleVersionToSemver(iOSVersion));
}
/**
* Returns a serializable object representation of this module.
*
* @return {Object} Plain object representation of this class
*/
toJson() {
return {
name: this.name,
path: this.path,
type: this.type,
introducedIn: this.introducedIn,
umbrellaHeader: this.umbrellaHeader,
usesSwift: this.usesSwift,
typeMap: this.typeMap
};
}
/**
* Prases a plain object received from JSON data and converts it back to a
* module metadata instance.
*
* @param {Object} json Object containing data from JSON
* @return {ModuleMetadata} The created module metadata instance
*/
static fromJson(json) {
const metadata = new ModuleMetadata(json.name, json.path, json.type);
metadata.introducedIn = json.introducedIn;
metadata.umbrellaHeader = json.umbrellaHeader;
metadata.usesSwift = json.usesSwift;
metadata.typeMap = json.typeMap;
return metadata;
}
}
/**
* generate system framework includes mapping
*/
function generateSystemFrameworks (sdkPath, iosMinVersion, callback) {
const frameworksPath = path.resolve(path.join(sdkPath, 'System/Library/Frameworks'));
const frameworksEntries = fs.readdirSync(frameworksPath).filter(entryName => /\.framework$/.test(entryName));
const frameworks = new Map();
iosMinVersion = appleVersionToSemver(iosMinVersion),
async.each(frameworksEntries, function (frameworkPackageName, next) {
const frameworkName = frameworkPackageName.replace('.framework', '');
const frameworkPath = path.join(frameworksPath, frameworkPackageName);
const frameworkHeadersPath = path.join(frameworkPath, 'Headers');
const frameworkUmbrellaHeader = path.join(frameworkHeadersPath, `${frameworkName}.h`);
if (fs.existsSync(frameworkUmbrellaHeader)) {
const frameworkMetadata = new ModuleMetadata(frameworkName, frameworkPath, ModuleMetadata.MODULE_TYPE_DYNAMIC);
frameworkMetadata.umbrellaHeader = frameworkUmbrellaHeader;
var mapping = {};
extractImplementationsFromFramework(frameworkName, frameworkPath, mapping);
frameworkMetadata.typeMap = mapping[frameworkName];
frameworks.set(frameworkName, frameworkMetadata);
next();
} else {
util.logger.debug('No framework umbrella header found for ' + frameworkName + '. Skipping ...');
return next();
}
}, function (err) {
return callback(err, frameworks);
});
}
/**
* Extracts Objective-C interface implementations from all available header
* files inside the given framework.
*
* This will include implementations from nested sub-frameworks that will be
* mapped to the parent framework.
*
* @param {String} frameworkName Name of the framework
* @param {String} frameworkPath Full path to the framwork
* @param {Object} includes Object with all include mappings
*/
function extractImplementationsFromFramework(frameworkName, frameworkPath, includes) {
var implementationToHeaderFileMap = includes[frameworkName] || {};
var headerFiles = collectFrameworkHeaders(frameworkPath);
headerFiles.forEach(function(headerFile) {
extractImplementations(headerFile, implementationToHeaderFileMap);
});
includes[frameworkName] = implementationToHeaderFileMap;
}
/**
* Iterates over a framework's Headers directory and any nested frameworks to
* collect the paths to all available header files of a framework.
*
* @param {String} frameworkPath Full path to the framwork
* @return {Array} List with paths to all found header files
*/
function collectFrameworkHeaders(frameworkPath) {
var frameworkHeadersPath = path.join(frameworkPath, 'Headers');
// Skip frameworks that do not have public headers set (like FirebaseNanoPB)
if (!fs.existsSync(frameworkHeadersPath)) {
return [];
}
var headerFiles = getAllHeaderFiles([frameworkHeadersPath]);
var nestedFrameworksPath = path.join(frameworkPath, 'Frameworks');
if (fs.existsSync(nestedFrameworksPath)) {
fs.readdirSync(nestedFrameworksPath).forEach(function (subFrameworkEntry) {
var nestedFrameworkPath = path.join(nestedFrameworksPath, subFrameworkEntry);
headerFiles = headerFiles.concat(collectFrameworkHeaders(nestedFrameworkPath));
});
}
return headerFiles;
}
/**
* generate a metabase
*
* @param {String} buildDir cache directory to write the files
* @param {String} sdk the sdk type such as iphonesimulator
* @param {String} sdk path the path to the SDK
* @param {String} iosMinVersion the min version such as 9.0
* @param {Array} includes array of header paths (should be absolute paths)
* @param {Boolean} excludeSystem if true, will exclude any system libraries in the generated output
* @param {Function} callback function to receive the result which will be (err, json, json_file, header_file)
* @param {Boolean} force if true, will not use cache
* @param {Array} extraHeaders Array of extra header search paths passed to the metabase parser
* @param {Array} extraFrameworks Array of extra framework search paths passed to the metabase parser
*/
function generateMetabase (buildDir, sdk, sdkPath, iosMinVersion, includes, excludeSystem, callback, force, extraHeaders, extraFrameworks) {
var cacheToken = createHashFromString(sdkPath + iosMinVersion + excludeSystem + JSON.stringify(includes));
var header = path.join(buildDir, 'metabase-' + iosMinVersion + '-' + sdk + '-' + cacheToken + '.h');
var outfile = path.join(buildDir, 'metabase-' + iosMinVersion + '-' + sdk + '-' + cacheToken + '.json');
// Foundation header always needs to be included
var absoluteFoundationHeaderRegex = /Foundation\.framework\/Headers\/Foundation\.h$/;
var systemFoundationHeaderRegex = /^[<"]Foundation\/Foundation\.h[>"]$/;
var isFoundationIncluded = includes.some(function(header) {
return systemFoundationHeaderRegex.test(header) || absoluteFoundationHeaderRegex.test(header);
});
if (!isFoundationIncluded) {
includes.unshift(path.join(sdkPath, 'System/Library/Frameworks/Foundation.framework/Headers/Foundation.h'));
}
// check for cached version and attempt to return if found
if (!force && fs.existsSync(header) && fs.existsSync(outfile)) {
try {
var json = JSON.parse(fs.readFileSync(outfile));
json.$includes = includes;
return callback(null, json, path.resolve(outfile), path.resolve(header), true);
}
catch (e) {
// fall through and re-generate again
}
}
force && util.logger.trace('forcing generation of metabase to', outfile);
var contents = '/**\n' +
' * HYPERLOOP GENERATED - DO NOT MODIFY\n' +
' */\n' +
includes.map(function (fn) {
if (fn) {
if (fn.charAt(0) === '<') {
return '#import ' + fn;
} else {
return '#import "' + fn + '"';
}
}
}).join('\n') +
'\n';
fs.writeFileSync(header, contents);
var args = [
'-i', path.resolve(header),
'-o', path.resolve(outfile),
'-sim-sdk-path', sdkPath,
'-min-ios-ver', iosMinVersion,
'-pretty'
];
if (excludeSystem) {
args.push('-x');
}
if (extraHeaders && extraHeaders.length > 0) {
args.push('-hsp');
args.push('"' + extraHeaders.join(',') + '"');
}
if (extraFrameworks && extraFrameworks.length > 0) {
args.push('-fsp');
args.push('"' + extraFrameworks.join(',') + '"');
}
util.logger.trace('running', binary, 'with', args.join(' '));
var ts = Date.now();
var triedToFixPermissions = false;
(function runMetabase(binary, args) {
try {
var child = spawn(binary, args);
} catch (e) {
if (e.code === 'EACCES') {
if (!triedToFixPermissions) {
fs.chmodSync(binary, '755');
triedToFixPermissions = true;
return runMetabase(binary, args);
} else {
return callback(new Error('Incorrect permissions for metabase binary ' + binary + '. Could not fix permissions automatically, please make sure it has execute permissions by running: chmod +x ' + binary))
}
}
throw e;
}
child.stdout.on('data', function (buf) {
util.logger.debug(String(buf).replace(/\n$/,''));
});
child.stderr.on('data', function (buf) {
// Without this, for whatever reason, the metabase parser never returns
});
child.on('error', callback);
child.on('exit', function (ex) {
util.logger.trace('metabase took', (Date.now()-ts), 'ms to generate');
if (ex) {
return callback(new Error('Metabase generation failed'));
}
var json = JSON.parse(fs.readFileSync(outfile));
json.$includes = includes;
return callback(null, json, path.resolve(outfile), path.resolve(header), false);
});
})(binary, args);
}
/**
* return the system frameworks mappings as JSON for a given sdkType and minVersion
*/
function getSystemFrameworks (cacheDir, sdkType, minVersion, callback) {
var fn = 'metabase-mappings-' + sdkType + '-' + minVersion + '.json';
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir);
}
var cacheFilename = path.join(cacheDir, fn);
var cachedMetadata = readModulesMetadataFromCache(cacheFilename);
if (cachedMetadata !== null) {
return callback(null, cachedMetadata);
}
getSDKPath(sdkType, function (err, sdkPath) {
if (err) { return callback(err); }
generateSystemFrameworks(sdkPath, minVersion, function (err, frameworks) {
if (err) { return callback(err); }
frameworks.set('$metadata', {
sdkType: sdkType,
minVersion: minVersion,
sdkPath: sdkPath
});
writeModulesMetadataToCache(frameworks, cacheFilename);
callback(null, frameworks);
});
});
}
function recursiveReadDir (dir, result) {
result = result || [];
var files = fs.readdirSync(dir);
files.forEach(function (fn) {
var fp = path.join(dir, fn);
if (fs.statSync(fp).isDirectory()) {
recursiveReadDir(fp, result);
} else {
result.push(fp);
}
});
return result;
}
/**
* for an array of directories, return all validate header files
*/
function getAllHeaderFiles (directories) {
var files = [];
directories.forEach(function (dir) {
recursiveReadDir(dir).forEach(function (fn) {
if (/\.(h(pp)?|swift)$/.test(fn)) {
files.push(fn);
}
});
});
return files;
}
/**
* Processes all header files under the given directories and creates a mapping
* of all implemented classes and their header file.
*
* Used for custom user source code configured via the hyperloop.ios.thirdparty
* setting in appc.js. Both Objective-C and Swift code is supported.
*
* @param {String} cacheDir Full path to the cache directory
* @param {Array} directories Array of directories to scan for header files
* @param {Function} callback Callback function
* @param {String} frameworkName Name of the framework the scanned headers belong to
*/
function generateUserSourceMappings (cacheDir, directories, callback, frameworkName) {
var files = getAllHeaderFiles(directories);
var cacheToken = createHashFromString(frameworkName + JSON.stringify(files));
var cachePathAndFilename = path.join(cacheDir, 'metabase-mappings-user-' + cacheToken + '.json');
var cachedMappings = readFromCache(cachePathAndFilename);
if (cachedMappings !== null) {
util.logger.trace('Using cached include mappings for ' + frameworkName + '.');
return callback(null, cachedMappings);
}
var result = {};
files.forEach(function (fn) {
var f = result[frameworkName] || {};
extractImplementations(fn, f);
result[frameworkName] = f;
});
writeToCache(cachePathAndFilename, result);
return callback(null, result, false);
}
/**
* Generates metadata for all frameworks known to the iOS builder.
*
* @param {Object} frameworks Object containing base info on all frameworks from the iOS builder
* @param {String} cacheDir Path to cache directory
* @param {Function} callback Callback function
*/
function generateUserFrameworksMetadata (frameworks, cacheDir, callback) {
const frameworkNames = Object.keys(frameworks);
const cacheToken = createHashFromString(frameworkNames.join(''));
var cachePathAndFilename = path.join(cacheDir, 'metabase-user-frameworks-' + cacheToken + '.json');
var cachedMetadata = readModulesMetadataFromCache(cachePathAndFilename);
if (cachedMetadata !== null) {
util.logger.trace('Using cached frameworks metadata.');
return callback(null, cachedMetadata);
}
const modules = new Map();
async.eachSeries(frameworkNames, (frameworkName, next) => {
const frameworkInfo = frameworks[frameworkName];
var metadata = new ModuleMetadata(frameworkInfo.name, frameworkInfo.path, frameworkInfo.type);
var includes = {};
generateFrameworkIncludeMap(metadata, includes, function (err) {
if (err) {
return next(err);
}
metadata.typeMap = includes[frameworkInfo.name];
modules.set(metadata.name, metadata);
next();
});
}, (err) => {
if (err) {
callback(err);
}
writeModulesMetadataToCache(modules, cachePathAndFilename);
callback(null, modules);
});
}
/**
* Parses all headers under the given path and creates a mapping of all
* implemented classes and their header file.
*
* This works for CocoaPods ObjC static libraries only
*
* @param {String} staticLibrariesHeaderPath Path to directory with static library headers
* @param {Object} includes Map of interface names and their header file for each library
* @param {Function} callback Callback function
*/
function generateStaticLibrariesIncludeMap (staticLibrariesHeaderPath, includes, callback) {
var files = getAllHeaderFiles([staticLibrariesHeaderPath]);
files.forEach(function (fn) {
var fw;
var pos = fn.lastIndexOf('/');
fw = fn;
if (pos > 0) {
var ppos = fn.lastIndexOf('/', pos - 1);
if (ppos) {
fw = fn.substring(ppos + 1, pos);
} else {
fw = fn.substring(0, pos);
}
}
var f = includes[fw] || {};
extractImplementations(fn, f);
includes[fw] = f;
});
return callback(null, includes, false);
}
/**
* Parses the given framework and creates a mapping of all implemented classes
* and their header file.
*
* Frameworks written in Swift are currently only supported if they provide an
* ObjC interface header.
*
* @param {ModuleMetadata} frameworkMetadata Metadata object containing all framework related info
* @param {Object} includes Map of class names and their header file
* @param {Function} callback Callback function
*/
function generateFrameworkIncludeMap (frameworkMetadata, includes, callback) {
const frameworkName = frameworkMetadata.name;
let basePath = frameworkMetadata.path;
let frameworkPath = basePath;
let frameworkHeadersPath;
if (basePath.endsWith('.xcframework')) {
const infoPlistPath = path.join(basePath, 'Info.plist');
const infoPlist = plist.parse(fs.readFileSync(infoPlistPath, 'utf-8'));
const {
LibraryPath: libPath,
LibraryIdentifier: libIdentifier,
HeadersPath: headersPath = 'Headers'
} = infoPlist.AvailableLibraries[0];
if (libPath.endsWith('.framework')) {
frameworkPath = path.join(basePath, libIdentifier, libPath);
} else {
frameworkPath = path.join(basePath, libIdentifier);
}
frameworkHeadersPath = path.join(frameworkPath, headersPath);
} else {
frameworkHeadersPath = path.join(frameworkPath, 'Headers');
}
// There are some rare frameworks (like FirebaseNanoPB) that do not have a Headers/ directory
if (!fs.existsSync(frameworkHeadersPath)) {
includes[frameworkName] = {};
return callback();
}
util.logger.trace('Generating includes for ' + frameworkMetadata.type + ' framework ' + frameworkName.green + ' (' + frameworkPath + ')');
if (frameworkMetadata.type === 'dynamic') {
// Skip if we don't have a "Modules" folder
var modulesPath = path.join(frameworkPath, 'Modules');
if (!fs.existsSync(modulesPath)) {
includes[frameworkName] = {};
return callback();
}
var moduleMapPathAndFilename = path.join(modulesPath, 'module.modulemap');
if (!fs.existsSync(moduleMapPathAndFilename)) {
return callback(new Error('Modulemap for ' + frameworkName + ' not found at expected path ' + moduleMapPathAndFilename + '. All dynamic frameworks need a module map to be usable with Hyperloop.'));
}
var moduleMap = fs.readFileSync(moduleMapPathAndFilename).toString();
if (fs.readdirSync(modulesPath).length > 1) {
// Dynamic frameworks containing Swift modules need to have an Objective-C
// interface header defined to be usable
frameworkMetadata.usesSwift = true;
var objcInterfaceHeaderRegex = /header\s"(.+-Swift\.h)"/i;
var objcInterfaceHeaderMatch = moduleMap.match(objcInterfaceHeaderRegex);
if (objcInterfaceHeaderMatch !== null) {
var objcInterfaceHeaderFilename = objcInterfaceHeaderMatch[1];
var headerPathAndFilename = path.join(frameworkHeadersPath, objcInterfaceHeaderFilename);
if (!fs.existsSync(headerPathAndFilename)) {
return callback(new Error('Objective-C interface header for Swift-based framework ' + frameworkName.green + ' not found at expected path ' + headerPathAndFilename.cyan + '.'));
}
util.logger.trace('Swift based framework detected, parsing Objective-C interface header ' + objcInterfaceHeaderFilename.cyan);
frameworkMetadata.umbrellaHeader = headerPathAndFilename;
var implementationToHeaderFileMap = includes[frameworkName] || {};
extractImplementations(headerPathAndFilename, implementationToHeaderFileMap);
includes[frameworkName] = implementationToHeaderFileMap;
} else {
// TODO: New Swift metabase generator required to support pure Swift frameworks
return callback(new Error('Incompatible framework ' + frameworkName + ' detected. Frameworks with Swift modules are only supported if they contain an Objective-C interface header.'));
}
} else {
var umbrellaHeaderRegex = /umbrella header\s"(.+\.h)"/i;
var umbrellaHeaderMatch = moduleMap.match(umbrellaHeaderRegex);
if (umbrellaHeaderMatch !== null) {
frameworkMetadata.umbrellaHeader = path.join(frameworkMetadata.path, 'Headers', umbrellaHeaderMatch[1]);
}
util.logger.trace('Objective-C only framework, parsing all header files');
extractImplementationsFromFramework(frameworkName, frameworkPath, includes);
}
} else if (frameworkMetadata.type === 'static') {
frameworkMetadata.umbrellaHeader = path.join(frameworkPath, 'Headers', `${frameworkMetadata.name}.h`);
util.logger.trace('Static framework, parsing all header files');
extractImplementationsFromFramework(frameworkName, frameworkPath, includes);
} else {
return callback(new Error('Invalid framework metadata, unknown type: ' + frameworkMetadata.type));
}
callback();
}
/**
* Generates a mapping of symbols for CocoaPods third-party libraries and
* frameworks.
*
* This can process both static libraries and frameworks (dynamic frameworks
* need to expose an ObjC Interface Header).
*
* @param {String} cacheDir Path to the cache directory
* @param {Object} builder iOSBuilder instance
* @param {Function} callback Callback function
*/
function generateCocoaPodsMetadata (cacheDir, builder, settings, callback) {
var podLockfilePathAndFilename = path.join(builder.projectDir, 'Podfile.lock');
var cacheToken = calculateCacheTokenFromPodLockfile(podLockfilePathAndFilename);
var cachePathAndFilename = path.join(cacheDir, 'metabase-cocoapods-' + cacheToken + '.json');
var cachedMetadata = readModulesMetadataFromCache(cachePathAndFilename);
if (cachedMetadata !== null) {
util.logger.trace('Using cached CocoaPods metadata.');
return callback(null, cachedMetadata);
}
var modules = new Map();
var tasks = [];
var includes = {};
// Check static libraries
var podDir = path.join(builder.projectDir, 'Pods');
if (fs.existsSync(podDir)) {
var staticLibrariesHeaderPath = path.join(podDir, 'Headers', 'Public');
if (fs.existsSync(staticLibrariesHeaderPath)) {
tasks.push(function (next) {
generateStaticLibrariesIncludeMap(staticLibrariesHeaderPath, includes, () => {
Object.keys(includes).forEach(libraryName => {
const libraryPath = path.join(staticLibrariesHeaderPath, libraryName);
const moduleMetadata = new ModuleMetadata(libraryName, libraryPath, ModuleMetadata.MODULE_TYPE_STATIC);
moduleMetadata.umbrellaHeader = path.join(moduleMetadata.path, `${moduleMetadata.name}.h`);
moduleMetadata.typeMap = includes[libraryName];
modules.set(moduleMetadata.name, moduleMetadata);
});
next();
});
});
}
}
// check for any frameworks under the CocoaPods FRAMEWORK_SEARCH_PATHS
var cocoaPodsConfigurationBuildDir = getBuiltProductsRootPath(builder.projectDir, builder.xcodeTarget, builder.xcodeTargetOS);
var frameworkSearchPaths = (settings.FRAMEWORK_SEARCH_PATHS || '').split(' ');
tasks.push(function(next) {
async.each(frameworkSearchPaths, function(frameworkSearchPath, done) {
frameworkSearchPath = frameworkSearchPath.replace('${PODS_ROOT}', settings.PODS_ROOT);
// TIMOB-25829: CocoaPods < 1.4.0 uses $PODS_CONFIGURATION_BUILD_DIR, 1.4.0+ uses ${PODS_CONFIGURATION_BUILD_DIR}
// Remove regex once we bump the minimum version to 1.4.0+
frameworkSearchPath = frameworkSearchPath.replace(/\$(\{)?(PODS_CONFIGURATION_BUILD_DIR)(\})?/, cocoaPodsConfigurationBuildDir);
frameworkSearchPath = frameworkSearchPath.replace(/"/g, '');
if (!fs.existsSync(frameworkSearchPath)) {
return done();
}
detectFrameworks(frameworkSearchPath, function(err, frameworks) {
if (err) {
return done(err);
}
async.each(Array.from(frameworks.values()), function(frameworkMetadata, nextFramework) {
if (modules.has(frameworkMetadata.name)) {
// If no use_frameworks! flag is set in the Podfile it is possible
// that we have a dummy static library whose headers are symlinked to
// it's backing dynamic framework (e.g. Localytics). Skip parsing the
// framework for now in those cases.
return nextFramework();
}
generateFrameworkIncludeMap(frameworkMetadata, includes, () => {
frameworkMetadata.typeMap = includes[frameworkMetadata.name];
modules.set(frameworkMetadata.name, frameworkMetadata);
nextFramework();
});
}, done);
});
}, next);
});
async.series(tasks, function(err) {
if (err) {
return callback(err);
}
writeModulesMetadataToCache(modules, cachePathAndFilename);
callback(err, modules);
});
}
/**
* Detects all frameworks that are under the given search path and returns
* basic metadata about their location and type
*
* @param {String} frameworkSearchPath Path where to search for frameworks
* @param {Function} done Callback function
*/
function detectFrameworks(frameworkSearchPath, done) {
var frameworks = new Map();
async.each(fs.readdirSync(frameworkSearchPath), function(searchPathEntry, next) {
var frameworkMatch = /([^/]+)\.framework$/.exec(searchPathEntry);
if (frameworkMatch === null) {
return next();
}
var frameworkName = frameworkMatch[1];
var frameworkPath = path.join(frameworkSearchPath, searchPathEntry);
var frameworkType = 'static';
var binaryPathAndFilename = path.join(frameworkPath, frameworkName);
var child = spawn('file', ['-b', binaryPathAndFilename]);
child.stdout.on('data', function(data) {
if (data.toString().indexOf('dynamically linked shared library') !== -1) {
frameworkType = 'dynamic';
}
});
child.stderr.on('data', function(data) {
util.logger.error(data.toString());
});
child.on('close', function(code) {
if (code !== 0) {
return next(new Error('Could not detect framework type, command exited with code ' + code));
}
frameworks.set(frameworkName, new ModuleMetadata(frameworkName, frameworkPath, frameworkType));
next();
});
}, function(err) {
if (err) {
done(err);
}
done(null, frameworks);
});
}
/**
* Calculates a cache token based on the Podfile checksum and all installed pod
* specs checksums.
*
* If one of these checksums change, either the Podfile changed or a Pod was
* updated/installed/removed, resulting in a changed cache token and the
* CocoaPods symbol mapping will be regenerated.
*
* @param {string} podLockfilePathAndFilename Path and filename of the Pod lockfile
* @return {string} The generated cache token
*/
function calculateCacheTokenFromPodLockfile (podLockfilePathAndFilename) {
if (!fs.existsSync(podLockfilePathAndFilename)) {
throw new Error('No Podfile.lock found in your project root. ');
}
var cacheTokenData = {podfile: '', specs: []};
var podLockfileContent = fs.readFileSync(podLockfilePathAndFilename).toString();
var specChecksumRegex = /[ ]{2}[^.][^\s/]*:\s(.*)/ig;
var checksumMatches = specChecksumRegex.exec(podLockfileContent);
if (checksumMatches === null) {
throw new Error('Could not read sepc checksums from Podfile.lock');
}
while (checksumMatches !== null) {
cacheTokenData.specs.push(checksumMatches[1]);
checksumMatches = specChecksumRegex.exec(podLockfileContent);
}
var podfileChecksumMatch = podLockfileContent.match(/PODFILE CHECKSUM: (.*)/);
if (podfileChecksumMatch === null) {
throw new Error('Could not read Podfile checksum from Podfile.lock');
}
cacheTokenData.podfile = podfileChecksumMatch[1];
return createHashFromString(JSON.stringify(cacheTokenData));
}
/**
* Gets the full path to the built products directory for the current Xcode build
* configuration name and SDK type.
*
* @param {String} basePath Project root path
* @param {String} configurationName Active configuration name, i.e. Debug, Release
* @param {String} sdkType Active SDK type, i.e. iphone or iphonesimulator
* @return {String} Full path the the products directory
*/
function getBuiltProductsRootPath (basePath, configurationName, sdkType) {
return path.join(basePath, 'build/iphone/build/Products', configurationName + '-' + sdkType);
}
/**
* Gets JSON encoded data from a cache file.
*
* @param {String} cacheDir Path to the cache directory
* @param {String} cacheToken Hash to identifiy the required cache file
* @return {Object} The CocoaPods metabase mappings
*/
function readFromCache (cachePathAndFilename) {
if (!fs.existsSync(cachePathAndFilename)) {
return null;
}
try {
return JSON.parse(fs.readFileSync(cachePathAndFilename).toString());
} catch (e) {
util.logger.debug(e);
util.logger.warn('Could not parse cached metabase mappings from ' + cachePathAndFilename + ', regenerating...');
}
return null;
}
/**
* Stores the given data in a cache file as JSON.
*
* @param {String} cacheDir Path of the cache file to write to
* @param {Object} data The include mappings to store
*/
function writeToCache (cachePathAndFilename, data) {
var cacheDir = path.dirname(cachePathAndFilename);
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir);
}
fs.writeFileSync(cachePathAndFilename, JSON.stringify(data));
}
function writeModulesMetadataToCache(modules, cachePathAndFilename) {
const modulesObject = {};
modules.forEach((entry, key) => {
if (entry instanceof ModuleMetadata) {
modulesObject[entry.name] = entry.toJson();
}
if (key === '$metadata') {
modulesObject.$metadata = entry;
}
});
const cacheDir = path.dirname(cachePathAndFilename);
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir);
}
fs.writeFileSync(cachePathAndFilename, JSON.stringify(modulesObject));
}
function readModulesMetadataFromCache(cachePathAndFilename) {
if (!fs.existsSync(cachePathAndFilename)) {
return null;
}
let json = {};
try {
json = JSON.parse(fs.readFileSync(cachePathAndFilename));
} catch (e) {
return null;
}
const modules = new Map();
Object.keys(json).forEach(entryName => {
if (entryName === '$metadata') {
modules.set('$metadata', json[entryName]);
return;
}
modules.set(entryName, ModuleMetadata.fromJson(json[entryName]));
});
return modules;
}
/**
* handle buffer output
*/
function createLogger (obj, fn) {
return (function () {
var cur = '';
obj.on('data', function (buf) {
cur += buf;
if (cur.charAt(cur.length - 1) === '\n') {
cur.split(/\n/).forEach(function (line) {
line && fn(chalk.green('CocoaPods') + ' ' + line);
});
cur = '';
}
});
obj.on('exit', function () {
// flush
if (cur) {
cur.split(/\n/).forEach(function (line) {
line && fn(chalk.green('CocoaPods') + ' ' + line);
});
}
});
})();
}
/**
* run the ibtool
*/
function runIBTool (runDir, args, callback) {
var spawn = require('child_process').spawn,
child = spawn('/usr/bin/ibtool', args, {cwd: runDir});
util.logger.debug('running /usr/bin/ibtool ' + args.join(' ') + ' ' + runDir);
createLogger(child.stdout, util.logger.trace);
createLogger(child.stderr, util.logger.warn);
child.on('error', callback);
child.on('exit', function (ec) {
if (ec !== 0) {
return callback(new Error('the ibtool failed running from ' + runDir));
}
callback();
});
}
function runMomcTool (runDir, sdk, args, callback) {
var spawn = require('child_process').spawn,
child = spawn('/usr/bin/xcrun', ['--sdk', sdk, 'momc'].concat(args), {cwd: runDir});
util.logger.debug('running /usr/bin/xcrun momc' + args.join(' ') + ' ' + runDir);
createLogger(child.stdout, util.logger.trace);
createLogger(child.stderr, util.logger.warn);
child.on('error', callback);
child.on('exit', function (ec) {
if (ec !== 0) {
return callback(new Error('the xcrun momc failed running from ' + runDir));
}
callback();
});
}