forked from kronenthaler/mod-pbxproj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod_pbxproj3.py
1327 lines (964 loc) · 42.2 KB
/
mod_pbxproj3.py
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
# Copyright 2012 Calvin Rien
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# A pbxproj file is an OpenStep format plist
# {} represents dictionary of key=value pairs delimited by ;
# () represents list of values delimited by ,
# file starts with a comment specifying the character type
# // !$*UTF8*$!
# when adding a file to a project, create the PBXFileReference
# add the PBXFileReference's guid to a group
# create a PBXBuildFile with the PBXFileReference's guid
# add the PBXBuildFile to the appropriate build phase
# when adding a header search path add
# HEADER_SEARCH_PATHS = "path/**";
# to each XCBuildConfiguration object
# Xcode4 will read either a OpenStep or XML plist.
# this script uses `plutil` to validate, read and write
# the pbxproj file. Plutil is available in OS X 10.2 and higher
# Plutil can't write OpenStep plists, so I save as XML
import datetime
import json
import ntpath
import os
import plistlib
import re
import shutil
import subprocess
import uuid
from collections import UserDict
from collections import UserList
regex = '[a-zA-Z0-9\\._/-]*'
class PBXEncoder(json.JSONEncoder):
def default(self, obj):
"""Tests the input object, obj, to encode as JSON."""
if isinstance(obj, (PBXList, PBXDict)):
return obj.data
return json.JSONEncoder.default(self, obj)
class PBXDict(UserDict):
def __init__(self, d=None):
if d:
d = dict([(PBXType.Convert(k), PBXType.Convert(v)) for k, v in list(d.items())])
UserDict.__init__(self, d)
def __setitem__(self, key, value):
UserDict.__setitem__(self, PBXType.Convert(key), PBXType.Convert(value))
def remove(self, key):
self.data.pop(PBXType.Convert(key), None)
class PBXList(UserList):
def __init__(self, l=None):
if isinstance(l, str):
UserList.__init__(self)
self.add(l)
return
elif l:
l = [PBXType.Convert(v) for v in l]
UserList.__init__(self, l)
def add(self, value):
value = PBXType.Convert(value)
if value in self.data:
return False
self.data.append(value)
return True
def remove(self, value):
value = PBXType.Convert(value)
if value in self.data:
self.data.remove(value)
def __setitem__(self, key, value):
UserList.__setitem__(self, PBXType.Convert(key), PBXType.Convert(value))
class PBXType(PBXDict):
def __init__(self, d=None):
PBXDict.__init__(self, d)
if 'isa' not in self:
self['isa'] = self.__class__.__name__
self.id = None
@staticmethod
def Convert(o):
if isinstance(o, list):
return PBXList(o)
elif isinstance(o, dict):
isa = o.get('isa')
if not isa:
return PBXDict(o)
cls = globals().get(isa)
if cls and issubclass(cls, PBXType):
return cls(o)
print('warning: unknown PBX type: %s' % isa)
return PBXDict(o)
else:
return o
@staticmethod
def IsGuid(o):
return re.match('^[A-F0-9]{24}$', str(o))
@classmethod
def GenerateId(cls):
return ''.join(str(uuid.uuid4()).upper().split('-')[1:])
@classmethod
def Create(cls, *args, **kwargs):
return cls(*args, **kwargs)
class PBXFileReference(PBXType):
def __init__(self, d=None):
PBXType.__init__(self, d)
self.build_phase = None
types = {
'.a': ('archive.ar', 'PBXFrameworksBuildPhase'),
'.app': ('wrapper.application', None),
'.s': ('sourcecode.asm', 'PBXSourcesBuildPhase'),
'.c': ('sourcecode.c.c', 'PBXSourcesBuildPhase'),
'.cpp': ('sourcecode.cpp.cpp', 'PBXSourcesBuildPhase'),
'.framework': ('wrapper.framework', 'PBXFrameworksBuildPhase'),
'.h': ('sourcecode.c.h', None),
'.icns': ('image.icns', 'PBXResourcesBuildPhase'),
'.m': ('sourcecode.c.objc', 'PBXSourcesBuildPhase'),
'.j': ('sourcecode.c.objc', 'PBXSourcesBuildPhase'),
'.mm': ('sourcecode.cpp.objcpp', 'PBXSourcesBuildPhase'),
'.nib': ('wrapper.nib', 'PBXResourcesBuildPhase'),
'.plist': ('text.plist.xml', 'PBXResourcesBuildPhase'),
'.json': ('text.json', 'PBXResourcesBuildPhase'),
'.png': ('image.png', 'PBXResourcesBuildPhase'),
'.rtf': ('text.rtf', 'PBXResourcesBuildPhase'),
'.tiff': ('image.tiff', 'PBXResourcesBuildPhase'),
'.txt': ('text', 'PBXResourcesBuildPhase'),
'.xcodeproj': ('wrapper.pb-project', None),
'.xib': ('file.xib', 'PBXResourcesBuildPhase'),
'.strings': ('text.plist.strings', 'PBXResourcesBuildPhase'),
'.bundle': ('wrapper.plug-in', 'PBXResourcesBuildPhase'),
'.dylib': ('compiled.mach-o.dylib', 'PBXFrameworksBuildPhase')
}
trees = [
'<absolute>',
'<group>',
'BUILT_PRODUCTS_DIR',
'DEVELOPER_DIR',
'SDKROOT',
'SOURCE_ROOT',
]
def guess_file_type(self, ignore_unknown_type=False):
self.remove('explicitFileType')
self.remove('lastKnownFileType')
ext = os.path.splitext(self.get('name', ''))[1]
if os.path.isdir(self.get('path')) and ext != '.framework':
f_type = 'folder'
build_phase = None
ext = ''
else:
f_type, build_phase = PBXFileReference.types.get(ext, ('?', 'PBXResourcesBuildPhase'))
self['lastKnownFileType'] = f_type
self.build_phase = build_phase
if f_type == '?' and not ignore_unknown_type:
print('unknown file extension: %s' % ext)
print('please add extension and Xcode type to PBXFileReference.types')
return f_type
def set_file_type(self, ft):
self.remove('explicitFileType')
self.remove('lastKnownFileType')
self['explicitFileType'] = ft
@classmethod
def Create(cls, os_path, tree='SOURCE_ROOT', ignore_unknown_type=False):
if tree not in cls.trees:
print('Not a valid sourceTree type: %s' % tree)
return None
fr = cls()
fr.id = cls.GenerateId()
fr['path'] = os_path
fr['name'] = os.path.split(os_path)[1]
fr['sourceTree'] = '<absolute>' if os.path.isabs(os_path) else tree
fr.guess_file_type(ignore_unknown_type=ignore_unknown_type)
return fr
class PBXBuildFile(PBXType):
def set_weak_link(self, weak=False):
k_settings = 'settings'
k_attributes = 'ATTRIBUTES'
s = self.get(k_settings)
if not s:
if weak:
self[k_settings] = PBXDict({k_attributes: PBXList(['Weak'])})
return True
atr = s.get(k_attributes)
if not atr:
if weak:
atr = PBXList()
else:
return False
if weak:
atr.add('Weak')
else:
atr.remove('Weak')
self[k_settings][k_attributes] = atr
return True
def add_compiler_flag(self, flag):
k_settings = 'settings'
k_attributes = 'COMPILER_FLAGS'
if k_settings not in self:
self[k_settings] = PBXDict()
if k_attributes not in self[k_settings]:
self[k_settings][k_attributes] = flag
return True
flags = self[k_settings][k_attributes].split(' ')
if flag in flags:
return False
flags.append(flag)
self[k_settings][k_attributes] = ' '.join(flags)
@classmethod
def Create(cls, file_ref, weak=False):
if isinstance(file_ref, PBXFileReference):
file_ref = file_ref.id
bf = cls()
bf.id = cls.GenerateId()
bf['fileRef'] = file_ref
if weak:
bf.set_weak_link(True)
return bf
class PBXGroup(PBXType):
def add_child(self, ref):
if not isinstance(ref, PBXDict):
return None
isa = ref.get('isa')
if isa != 'PBXFileReference' and isa != 'PBXGroup':
return None
if 'children' not in self:
self['children'] = PBXList()
self['children'].add(ref.id)
return ref.id
def remove_child(self, id):
if 'children' not in self:
self['children'] = PBXList()
return
if not PBXType.IsGuid(id):
id = id.id
self['children'].remove(id)
def has_child(self, id):
if 'children' not in self:
self['children'] = PBXList()
return False
if not PBXType.IsGuid(id):
id = id.id
return id in self['children']
def get_name(self):
path_name = os.path.split(self.get('path', ''))[1]
return self.get('name', path_name)
@classmethod
def Create(cls, name, path=None, tree='SOURCE_ROOT'):
grp = cls()
grp.id = cls.GenerateId()
grp['name'] = name
grp['children'] = PBXList()
if path:
grp['path'] = path
grp['sourceTree'] = tree
else:
grp['sourceTree'] = '<group>'
return grp
class PBXNativeTarget(PBXType):
pass
class PBXProject(PBXType):
pass
class PBXContainerItemProxy(PBXType):
pass
class PBXReferenceProxy(PBXType):
pass
class PBXVariantGroup(PBXType):
pass
class PBXTargetDependency(PBXType):
pass
class PBXBuildPhase(PBXType):
def add_build_file(self, bf):
if bf.get('isa') != 'PBXBuildFile':
return False
if 'files' not in self:
self['files'] = PBXList()
self['files'].add(bf.id)
return True
def remove_build_file(self, id):
if 'files' not in self:
self['files'] = PBXList()
return
self['files'].remove(id)
def has_build_file(self, id):
if 'files' not in self:
self['files'] = PBXList()
return False
if not PBXType.IsGuid(id):
id = id.id
return id in self['files']
class PBXFrameworksBuildPhase(PBXBuildPhase):
pass
class PBXResourcesBuildPhase(PBXBuildPhase):
pass
class PBXShellScriptBuildPhase(PBXBuildPhase):
pass
class PBXSourcesBuildPhase(PBXBuildPhase):
pass
class PBXCopyFilesBuildPhase(PBXBuildPhase):
pass
class XCBuildConfiguration(PBXType):
def add_search_paths(self, paths, base, key, recursive=True, escape=True):
modified = False
if not isinstance(paths, list):
paths = [paths]
if base not in self:
self[base] = PBXDict()
for path in paths:
if recursive and not path.endswith('/**'):
path = os.path.join(path, '**')
if key not in self[base]:
self[base][key] = PBXList()
elif isinstance(self[base][key], str):
self[base][key] = PBXList(self[base][key])
if escape:
if self[base][key].add('"%s"' % path): # '\\"%s\\"' % path
modified = True
else:
if self[base][key].add(path): # '\\"%s\\"' % path
modified = True
return modified
def add_header_search_paths(self, paths, recursive=True):
return self.add_search_paths(paths, 'buildSettings', 'HEADER_SEARCH_PATHS', recursive=recursive)
def add_library_search_paths(self, paths, recursive=True):
return self.add_search_paths(paths, 'buildSettings', 'LIBRARY_SEARCH_PATHS', recursive=recursive)
def add_framework_search_paths(self, paths, recursive=True):
return self.add_search_paths(paths, 'buildSettings', 'FRAMEWORK_SEARCH_PATHS', recursive=recursive)
def add_other_cflags(self, flags):
modified = False
base = 'buildSettings'
key = 'OTHER_CFLAGS'
if isinstance(flags, str):
flags = PBXList(flags)
if base not in self:
self[base] = PBXDict()
for flag in flags:
if key not in self[base]:
self[base][key] = PBXList()
elif isinstance(self[base][key], str):
self[base][key] = PBXList(self[base][key])
if self[base][key].add(flag):
self[base][key] = [e for e in self[base][key] if e]
modified = True
return modified
def add_other_ldflags(self, flags):
modified = False
base = 'buildSettings'
key = 'OTHER_LDFLAGS'
if isinstance(flags, str):
flags = PBXList(flags)
if base not in self:
self[base] = PBXDict()
for flag in flags:
if key not in self[base]:
self[base][key] = PBXList()
elif isinstance(self[base][key], str):
self[base][key] = PBXList(self[base][key])
if self[base][key].add(flag):
self[base][key] = [e for e in self[base][key] if e]
modified = True
return modified
def remove_other_ldflags(self, flags):
modified = False
base = 'buildSettings'
key = 'OTHER_LDFLAGS'
if isinstance(flags, str):
flags = PBXList(flags)
if base in self: # there are flags, so we can "remove" something
for flag in flags:
if key not in self[base]:
return False
elif isinstance(self[base][key], str):
self[base][key] = PBXList(self[base][key])
if self[base][key].remove(flag):
self[base][key] = [e for e in self[base][key] if e]
modified = True
return modified
class XCConfigurationList(PBXType):
pass
class XcodeProject(PBXDict):
plutil_path = 'plutil'
special_folders = ['.bundle', '.framework', '.xcodeproj']
def __init__(self, d=None, path=None):
if not path:
path = os.path.join(os.getcwd(), 'project.pbxproj')
self.pbxproj_path = os.path.abspath(path)
self.source_root = os.path.abspath(os.path.join(os.path.split(path)[0], '..'))
UserDict.__init__(self, d)
self.data = PBXDict(self.data)
self.objects = self.get('objects')
self.modified = False
root_id = self.get('rootObject')
if root_id:
self.root_object = self.objects[root_id]
root_group_id = self.root_object.get('mainGroup')
self.root_group = self.objects[root_group_id]
else:
print("error: project has no root object")
self.root_object = None
self.root_group = None
for k, v in self.objects.items():
v.id = k
def add_other_cflags(self, flags):
build_configs = [b for b in list(self.objects.values()) if b.get('isa') == 'XCBuildConfiguration']
for b in build_configs:
if b.add_other_cflags(flags):
self.modified = True
def add_other_ldflags(self, flags):
build_configs = [b for b in list(self.objects.values()) if b.get('isa') == 'XCBuildConfiguration']
for b in build_configs:
if b.add_other_ldflags(flags):
self.modified = True
def remove_other_ldflags(self, flags):
build_configs = [b for b in list(self.objects.values()) if b.get('isa') == 'XCBuildConfiguration']
for b in build_configs:
if b.remove_other_ldflags(flags):
self.modified = True
def add_header_search_paths(self, paths, recursive=True):
build_configs = [b for b in list(self.objects.values()) if b.get('isa') == 'XCBuildConfiguration']
for b in build_configs:
if b.add_header_search_paths(paths, recursive):
self.modified = True
def add_framework_search_paths(self, paths, recursive=True):
build_configs = [b for b in list(self.objects.values()) if b.get('isa') == 'XCBuildConfiguration']
for b in build_configs:
if b.add_framework_search_paths(paths, recursive):
self.modified = True
def add_library_search_paths(self, paths, recursive=True):
build_configs = [b for b in list(self.objects.values()) if b.get('isa') == 'XCBuildConfiguration']
for b in build_configs:
if b.add_library_search_paths(paths, recursive):
self.modified = True
# TODO: need to return value if project has been modified
def get_obj(self, id):
return self.objects.get(id)
def get_ids(self):
return list(self.objects.keys())
def get_files_by_os_path(self, os_path, tree='SOURCE_ROOT'):
files = [f for f in list(self.objects.values()) if f.get('isa') == 'PBXFileReference'
and f.get('path') == os_path
and f.get('sourceTree') == tree]
return files
def get_files_by_name(self, name, parent=None):
if parent:
files = [f for f in list(self.objects.values()) if f.get('isa') == 'PBXFileReference'
and f.get('name') == name
and parent.has_child(f)]
else:
files = [f for f in list(self.objects.values()) if f.get('isa') == 'PBXFileReference'
and f.get('name') == name]
return files
def get_build_files(self, id):
files = [f for f in list(self.objects.values()) if f.get('isa') == 'PBXBuildFile'
and f.get('fileRef') == id]
return files
def get_groups_by_name(self, name, parent=None):
if parent:
groups = [g for g in list(self.objects.values()) if g.get('isa') == 'PBXGroup'
and g.get_name() == name
and parent.has_child(g)]
else:
groups = [g for g in list(self.objects.values()) if g.get('isa') == 'PBXGroup'
and g.get_name() == name]
return groups
def get_or_create_group(self, name, path=None, parent=None):
if not name:
return None
if not parent:
parent = self.root_group
elif not isinstance(parent, PBXGroup):
# assume it's an id
parent = self.objects.get(parent, self.root_group)
groups = self.get_groups_by_name(name)
for grp in groups:
if parent.has_child(grp.id):
return grp
grp = PBXGroup.Create(name, path)
parent.add_child(grp)
self.objects[grp.id] = grp
self.modified = True
return grp
def get_groups_by_os_path(self, path):
path = os.path.abspath(path)
groups = [g for g in list(self.objects.values()) if g.get('isa') == 'PBXGroup'
and os.path.abspath(g.get('path', '/dev/null')) == path]
return groups
def get_build_phases(self, phase_name):
phases = [p for p in list(self.objects.values()) if p.get('isa') == phase_name]
return phases
def get_relative_path(self, os_path):
return os.path.relpath(os_path, self.source_root)
def verify_files(self, file_list, parent=None):
# returns list of files not in the current project.
if not file_list:
return []
if parent:
exists_list = [f.get('name') for f in list(self.objects.values()) if f.get('isa') == 'PBXFileReference' and f.get('name') in file_list and parent.has_child(f)]
else:
exists_list = [f.get('name') for f in list(self.objects.values()) if f.get('isa') == 'PBXFileReference' and f.get('name') in file_list]
return set(file_list).difference(exists_list)
def add_folder(self, os_path, parent=None, excludes=None, recursive=True, create_build_files=True):
if not os.path.isdir(os_path):
return []
if not excludes:
excludes = []
results = []
if not parent:
parent = self.root_group
elif not isinstance(parent, PBXGroup):
# assume it's an id
parent = self.objects.get(parent, self.root_group)
path_dict = {os.path.split(os_path)[0]: parent}
special_list = []
for (grp_path, subdirs, files) in os.walk(os_path):
parent_folder, folder_name = os.path.split(grp_path)
parent = path_dict.get(parent_folder, parent)
if [sp for sp in special_list if parent_folder.startswith(sp)]:
continue
if folder_name.startswith('.'):
special_list.append(grp_path)
continue
if os.path.splitext(grp_path)[1] in XcodeProject.special_folders:
# if this file has a special extension (bundle or framework mainly) treat it as a file
special_list.append(grp_path)
new_files = self.verify_files([folder_name], parent=parent)
if new_files:
results.extend(self.add_file(grp_path, parent, create_build_files=create_build_files))
continue
# create group
grp = self.get_or_create_group(folder_name, path=self.get_relative_path(grp_path), parent=parent)
path_dict[grp_path] = grp
results.append(grp)
file_dict = {}
for f in files:
if f[0] == '.' or [m for m in excludes if re.match(m, f)]:
continue
kwds = {
'create_build_files': create_build_files,
'parent': grp,
'name': f
}
f_path = os.path.join(grp_path, f)
file_dict[f_path] = kwds
new_files = self.verify_files([n.get('name') for n in list(file_dict.values())], parent=grp)
add_files = [(k, v) for k, v in list(file_dict.items()) if v.get('name') in new_files]
for path, kwds in add_files:
kwds.pop('name', None)
self.add_file(path, **kwds)
if not recursive:
break
for r in results:
self.objects[r.id] = r
return results
def path_leaf(self, path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
def add_file_if_doesnt_exist(self, f_path, parent=None, tree='SOURCE_ROOT', create_build_files=True, weak=False, ignore_unknown_type=False):
for obj in list(self.objects.values()):
if 'path' in obj:
if self.path_leaf(f_path) == self.path_leaf(obj.get('path')):
return []
return self.add_file(f_path, parent, tree, create_build_files, weak, ignore_unknown_type=ignore_unknown_type)
def add_file(self, f_path, parent=None, tree='SOURCE_ROOT', create_build_files=True, weak=False, ignore_unknown_type=False):
results = []
abs_path = ''
if os.path.isabs(f_path):
abs_path = f_path
if not os.path.exists(f_path):
return results
elif tree == 'SOURCE_ROOT':
f_path = os.path.relpath(f_path, self.source_root)
else:
tree = '<absolute>'
if not parent:
parent = self.root_group
elif not isinstance(parent, PBXGroup):
# assume it's an id
parent = self.objects.get(parent, self.root_group)
file_ref = PBXFileReference.Create(f_path, tree, ignore_unknown_type=ignore_unknown_type)
parent.add_child(file_ref)
results.append(file_ref)
# create a build file for the file ref
if file_ref.build_phase and create_build_files:
phases = self.get_build_phases(file_ref.build_phase)
for phase in phases:
build_file = PBXBuildFile.Create(file_ref, weak=weak)
phase.add_build_file(build_file)
results.append(build_file)
if abs_path and tree == 'SOURCE_ROOT' \
and os.path.isfile(abs_path) \
and file_ref.build_phase == 'PBXFrameworksBuildPhase':
library_path = os.path.join('$(SRCROOT)', os.path.split(f_path)[0])
self.add_library_search_paths([library_path], recursive=False)
if abs_path and tree == 'SOURCE_ROOT' \
and not os.path.isfile(abs_path) \
and file_ref.build_phase == 'PBXFrameworksBuildPhase':
framework_path = os.path.join('$(SRCROOT)', os.path.split(f_path)[0])
self.add_framework_search_paths([framework_path, '$(inherited)'], recursive=False)
for r in results:
self.objects[r.id] = r
if results:
self.modified = True
return results
def check_and_repair_framework(self, base):
name = os.path.basename(base)
if ".framework" in name:
basename = name[:-len(".framework")]
finalHeaders = os.path.join(base, "Headers")
finalCurrent = os.path.join(base, "Versions/Current")
finalLib = os.path.join(base, basename)
srcHeaders = "Versions/A/Headers"
srcCurrent = "A"
srcLib = "Versions/A/" + basename
if not os.path.exists(finalHeaders):
os.symlink(srcHeaders, finalHeaders)
if not os.path.exists(finalCurrent):
os.symlink(srcCurrent, finalCurrent)
if not os.path.exists(finalLib):
os.symlink(srcLib, finalLib)
def remove_group(self, grp):
pass
def remove_file(self, id, recursive=True):
if not PBXType.IsGuid(id):
id = id.id
if id in self.objects:
self.objects.remove(id)
if recursive:
groups = [g for g in list(self.objects.values()) if g.get('isa') == 'PBXGroup']
for group in groups:
if id in group['children']:
group.remove_child(id)
self.modified = True
def move_file(self, id, dest_grp=None):
pass
def apply_patch(self, patch_path, xcode_path):
if not os.path.isfile(patch_path) or not os.path.isdir(xcode_path):
print('ERROR: couldn\'t apply "%s" to "%s"' % (patch_path, xcode_path))
return
print('applying "%s" to "%s"' % (patch_path, xcode_path))
return subprocess.call(['patch', '-p1', '--forward', '--directory=%s' % xcode_path, '--input=%s' % patch_path])
def apply_mods(self, mod_dict, default_path=None):
if not default_path:
default_path = os.getcwd()
keys = list(mod_dict.keys())
for k in keys:
v = mod_dict.pop(k)
mod_dict[k.lower()] = v
parent = mod_dict.pop('group', None)
if parent:
parent = self.get_or_create_group(parent)
excludes = mod_dict.pop('excludes', [])
if excludes:
excludes = [re.compile(e) for e in excludes]
compiler_flags = mod_dict.pop('compiler_flags', {})
for k, v in list(mod_dict.items()):
if k == 'patches':
for p in v:
if not os.path.isabs(p):
p = os.path.join(default_path, p)
self.apply_patch(p, self.source_root)
elif k == 'folders':
# get and compile excludes list
# do each folder individually
for folder in v:
kwds = {}
# if path contains ':' remove it and set recursive to False
if ':' in folder:
args = folder.split(':')
kwds['recursive'] = False
folder = args.pop(0)
if os.path.isabs(folder) and os.path.isdir(folder):
pass
else:
folder = os.path.join(default_path, folder)
if not os.path.isdir(folder):
continue
if parent:
kwds['parent'] = parent
if excludes:
kwds['excludes'] = excludes
self.add_folder(folder, **kwds)
elif k == 'headerpaths' or k == 'librarypaths':
paths = []
for p in v:
if p.endswith('/**'):
p = os.path.split(p)[0]
if not os.path.isabs(p):
p = os.path.join(default_path, p)
if not os.path.exists(p):
continue
p = self.get_relative_path(p)
paths.append(os.path.join('$(SRCROOT)', p, "**"))
if k == 'headerpaths':
self.add_header_search_paths(paths)
else:
self.add_library_search_paths(paths)
elif k == 'other_cflags':
self.add_other_cflags(v)
elif k == 'other_ldflags':
self.add_other_ldflags(v)
elif k == 'libs' or k == 'frameworks' or k == 'files':
paths = {}
for p in v:
kwds = {}
if ':' in p:
args = p.split(':')
p = args.pop(0)
if 'weak' in args:
kwds['weak'] = True
file_path = os.path.join(default_path, p)
search_path, file_name = os.path.split(file_path)
if [m for m in excludes if re.match(m, file_name)]:
continue
try: