-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathauto2cmake.py
More file actions
executable file
·2105 lines (1735 loc) · 88.2 KB
/
auto2cmake.py
File metadata and controls
executable file
·2105 lines (1735 loc) · 88.2 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
#!/usr/bin/python3
########################################################################################################################
# Application Description #
########################################################################################################################
# script to convert an autotools project to more or less corresponding CMakeLists.txt structure
# Interpret the linker flags
# interpret the programs, generate add_executable
# specify the target link dependencies
# the gather the files mode
# include directory generation based on parsing the file for #include
########################################################################################################################
# Application Imports #
########################################################################################################################
import sys, getopt, time, os, re, glob, shutil, subprocess
from difflib import SequenceMatcher
from enum import Enum
from os.path import join as pjoin
from urllib import request # urllib is chosen over requests to maintain portability
from json import loads
from typing import List, Optional # Used for explicit type declarations. (helpful for analyzing types without an IDE)
########################################################################################################################
# Classes used by the application #
########################################################################################################################
########################################################################################################################
# Represents a CMake file that will be generated at a later stage.
########################################################################################################################
class CMakeFile:
def __init__(self, directory):
self.directory = directory # The directory where this can be found
self.contained_libraries_content = [] # All the content of the libraries that are created in here
self.libraries = [] # All the libraries that are created by this file
self.extra_content = "" # Extra stuff such as add_subdriectory
########################################################################################################################
# Represents a CMake version object that will be utilized prior to, and during the generation stages.
########################################################################################################################
class CMakeVersion:
def __init__(self, version_string: str):
self.full_version: str = version_string
self.major: int = None
self.minor: int = None
# Since the build version is not always specified, defaulting it to 0 will avoid AttributeError(s)
self.build: int = 0
# Initializing the major, minor, and build versions
self.__parse__(version_string)
def __parse__(self, version_string: Optional[str]):
if version_string is None:
print("No CMake version string provided. Expected format: 'X.X' or 'X.X.X'")
exit(1)
version_parts: List[int] = [int(part) for part in version_string.split('.') if part.isdigit()]
number_of_parts: int = len(version_parts)
if number_of_parts in [0, 1] or number_of_parts > 3:
print("Unable to parse the provided CMake version string. Expected format: 'X.X' or 'X.X.X'")
exit(1)
# Covering the major and minor version numbers
if number_of_parts >= 2:
self.major = version_parts[0]
self.minor = version_parts[1]
# Since this class will not be called more than a handful of times, this additional check:
# - Covers the build version number
# - Uses a neglible amount of memory
# - Improves readability for future maintainers
if number_of_parts == 3:
self.build = version_parts[2]
def __str__(self):
return self.full_version
########################################################################################################################
# Whether a target is a Library (noinst_LIBRARIES) or an Application (bin_PROGRAMS)
########################################################################################################################
class TargetType(Enum):
LIBRARY = 1
PROGRAM = 2
########################################################################################################################
# Represents a library that will be built by a specific make command.
########################################################################################################################
class Library:
def __init__(self, name, directory):
self.name = name
self.dependant = False
self.filelist = [] # the list of files of this library
self.condition = [] # the list of conditions on which this library is built if any
self.link_with_libs = [] # the list of libraries that were built by the script. target_link_libraries
self.compiler_flags = [] # the compiler options
self.linker_flags = [] # the linker flags. the -l flags will be parsed out into link_with_libs
self.conditional_appends = {}
self.just_variables = {}
self.added_subdirectories = []
self.target_type = TargetType.LIBRARY
self.ttype = ""
self.referred_name = name
if '$' in self.name:
self.name = self.name.replace('$', '')
self.name = self.name.replace('(', '')
self.name = self.name.replace(')', '')
self.dependant = True
self.canonic_name = canonicalize(self.name)
self.directory = directory
if not self.dependant:
if self.name.endswith(".a"):
self.type = "STATIC"
self.referred_name = self.name[3:]
self.referred_name = self.referred_name[:-2]
else:
self.type = "DYNAMIC"
self.referred_name = self.name[3:]
self.referred_name = self.referred_name[:-3]
else:
self.type = "STATIC"
self.referred_name = self.name
########################################################################################################################
# Represents an option that will go in the CMakeLists.txt and also in the generated header if a define is present.
########################################################################################################################
class Option:
def __init__(self, name, description, status, define, define_value, define_description):
name = name.replace("-", "_")
if upcase_identifiers:
self.name = name.upper()
else:
self.name = name
self.description = description
self.status = status
self.define = define
define_value = define_value.replace(']', '')
define_value = define_value.replace(',', '')
define_value = define_value.replace('[', '')
self.define_value = define_value
self.define_description = define_description
self.extra_defines = []
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def set_description(self, description):
self.description = description
def get_description(self):
return self.description
def set_status(self, status):
self.status = status
def get_status(self):
return self.status
def set_define(self, define):
self.define = define
def get_define(self):
return self.define
def set_define_value(self, define_value):
if '[' in define_value:
define_value = define_value.replace(']', '')
define_value = define_value.replace('[', '')
self.define_value = define_value
def get_define_value(self):
return self.define_value
def set_define_description(self, define_description):
self.define_description = define_description
def get_define_description(self):
return self.define_description
def finalize(self):
if len(self.description) <= 1:
self.description = "Enable " + self.name
if len(self.status) <= 1:
self.status = "OFF"
if len(self.define_description) <= 1:
self.define_description = self.description
def add_extra_define(self, extra_define):
self.extra_defines.append(extra_define)
def get_extra_defines(self):
return self.extra_defines
########################################################################################################################
# Global variables used by the application, specified on command line #
########################################################################################################################
# Whether auto2cmake should utilize its "Quick Mode" for the next conversion.
quick = False
# Whether "Quick Mode" should utilize recursive directory walking for the next conversion.
recursive = False
# Whether "Quick Mode should generate a library or an executable.
# True => Library
# False => Executable
quick_gen_lib = True
# Whether auto2cmake should use CMakes AUTOMOC.
# If set to False, auto2cmake will use QT source wrapping to manually generate these moc files.
cmake_automoc = True
# Whether auto2cmake should use uppercase identifers for option objects.
upcase_identifiers = 1
# Whether the generated "CMakeLists.txt" files should contain optional comments.
# This can be disabled by passing either "-c" or "--disable-comments"
# It is recommended to leave this enabled.
# 0 => Disable Comments
# 1 => Enable Comments
generate_comments = 1
# Whether the generated "CMakeLists.txt" files should append more new than one newline char (\n) after each generated line.
# 0 => Don't add an extra new line character (\n) after each generated line.
# 1 => Add an extra new line character (\n) after each generated line.
more_newlines = 1
# The working directory for the conversion operations attempted by auto2cmake.
# By default, auto2cmake will search the same directory the script is ran from.
# This can be changed by passing either "-d <dir>" or "--directory=<dir>"
working_directory = "."
# The directories auto2cmake should exclude when searching for Makefile.am(s) and during any other processing.
# By default, auto2cmake does not exclude any directories.
# This can be changed by passing any of the following:
# "-e <dir>"
# "--exclude=<dir>"
# "--exclude=<dir1>:<dir2>:<dir3>"
exclude_directories = []
#######################################################################################################################
# CMake Version Info #
# These values will be updated in update_version_info() #
#######################################################################################################################
# The minimum version of CMake the converted project will support
# The default version for conversion operations is CMake 2.8
# This can be changed by passing either "-v <version>" or "--version=<version>"
cmake_minimum_version: CMakeVersion = CMakeVersion("2.8")
# The maximimum version of CMake currently released.
# Utilized in validate_cmake_version()
cmake_maximum_version: Optional[CMakeVersion] = None
# The currently installed version of CMake on the current machine.
# Currently this has no impact on execution, despite being declared in update_version_info().
# T-007 in TODO seeks to address this.
cmake_installed_version: Optional[CMakeVersion] = None
########################################################################################################################
# The application logic structures #
########################################################################################################################
# the list of libraries that will be built. contains Library objects
libraries = []
# will contain all the options that were gathered from configure.ac in form of Option objects
options = {}
# will contain all the defines from the configure.ac
temp_defines = {}
# will contain the CMakeLists of the converted system. Key is the directory
cmake_files = {}
# will contain all the variables defined in configure.ac
config_ac_variables = {}
# will hold extra content for CMakeLists in specific directories
extra_content = {}
# The list of all the directories that will need a CMakeLists.txt in them
required_directories = []
########################################################################################################################
# Constants
########################################################################################################################
cpp_extensions = [".c", ".cpp", ".cxx", ".c++", ".cc"]
header_extensions = [".h", ".hpp", ".hxx", ".h++", ".hh"]
qrc_extensions = [".qrc"]
########################################################################################################################
# Helper functions used by the application #
########################################################################################################################
########################################################################################################################
# Checks for an installation of CMake and attempts to resolve the version installed.
########################################################################################################################
def get_installed_cmake_version() -> Optional[CMakeVersion]:
print(f"Checking for a CMake installation, please wait.")
print()
# Checking for the existence of "cmake" in the current system's path.
if not shutil.which("cmake"):
print("CMake installation not found. Please install CMake and try again.")
sys.exit()
match = None
try:
result = subprocess.run(
["cmake", "--version"],
capture_output=True,
text=True,
check=True
)
# Checking for the expected output of:
# "cmake version X.X.X" or "cmake3 version X.X.X"
# Upon further research, "cmake" is sometimes a symlink to cmake3 on certain linux distributions.
# https://stackoverflow.com/questions/50989957/whats-the-difference-between-cmake-vs-cmake3
match = re.search(r"version\s+([\d.]+)", result.stdout)
if not match:
print(
f"CMake detected, but the version string could not be parsed.\nOutput: {result.stdout}"
)
exit(1)
print(f"CMake {match.group(1)} is installed.")
except Exception as e:
print("A CMake installation was found, however, an unexpected response was received.")
print(f"Response:\n{e.stderr}")
return None
return CMakeVersion(match.group(1))
########################################################################################################################
# Performs a comparison operation on two CMakeVersion objects.
# Returns True if lower_version_obj is greater than higher_version_obj when both objects are parsed.
# Returns False otherwise.
########################################################################################################################
def cmake_version_is_invalid(lower_version_obj: CMakeVersion, higher_version_obj: CMakeVersion) -> bool:
# Handling the major and minor versions of both CMakeVersion objects passed as parameters.
if (
lower_version_obj.major is None or
higher_version_obj.major is None or
lower_version_obj.minor is None or
higher_version_obj.minor is None
):
return True
elif (
lower_version_obj.major > higher_version_obj.major or
lower_version_obj.major >= higher_version_obj.major and
lower_version_obj.minor > higher_version_obj.minor
):
return True
# Handling the build versions of both CMakeVersion objects passed as parameters.
elif (
lower_version_obj.major >= higher_version_obj.major and
lower_version_obj.minor >= higher_version_obj.minor and
lower_version_obj.build > higher_version_obj.build
):
return True
return False
########################################################################################################################
# Validates the value for the arguments "-v <VERSION>" and --version="<VERSION>"
########################################################################################################################
def validate_cmake_version(provided_version: str, latest_version: Optional[str]):
global cmake_installed_version
global cmake_minimum_version
if latest_version is None:
print("Unable to resolve the latest version of CMake.")
return
try:
provided_version_obj: CMakeVersion = CMakeVersion(provided_version)
latest_version_obj: CMakeVersion = CMakeVersion(latest_version)
# Handles versions that are less than the minimum supported
if (cmake_version_is_invalid(cmake_minimum_version, provided_version_obj)):
print(f"The specified version of CMake (v{provided_version_obj}) is not supported by auto2cmake.")
print(f"Please specify a version at or greater than CMake {cmake_minimum_version}")
exit(1)
# Handles versions that are not released (also handles incorrect input)
elif (cmake_version_is_invalid(provided_version_obj, latest_version_obj)):
print("The specified version of CMake is not currently released.")
print(f"The latest public release is v{latest_version_obj}")
exit(1)
# General null check
elif (not provided_version_obj or not cmake_installed_version):
print("The following parameter has a NoneType in validate_cmake_version:")
print("\tprovided_version_obj" if not provided_version_obj else "\tcmake_installed_version")
exit(1)
# Currently a warning is provided when the installed version of CMake is older than version specified via flag.
elif (cmake_version_is_invalid(provided_version_obj, cmake_installed_version)):
print(f"The specified version of CMake (v{provided_version_obj}) is newer than the installed version on the current system.")
warning(
"This may cause unexpected behavior.\n"
f"It is recommended to specify {cmake_installed_version} instead of {provided_version_obj}"
)
else:
print(f"Validation complete, all processing will be done using CMake {provided_version_obj}")
except Exception as e:
print(f"Error validating the provided version of CMake.")
print(f"Type: {type(e)}")
print(f"Error: {e}")
print("Skipping version validation.")
return
########################################################################################################################
# Resolves the latest version of CMake from https://github.com/Kitware/CMake
########################################################################################################################
def get_latest_cmake_version():
url = "https://api.github.com/repos/Kitware/CMake/releases"
version = None
json_data = None
try:
with request.urlopen(url) as req:
str_data = req.read().decode('utf-8')
json_data = loads(str_data)
version = json_data[0]["tag_name"][1:]
except Exception as e:
print(e)
if not json_data:
print("Unable to resolve the latest version of CMake.")
return CMakeVersion(version)
########################################################################################################################
# Updates the CMake version information used by the application.
########################################################################################################################
def update_version_info():
global cmake_maximum_version
global cmake_installed_version
# The maximimum version of CMake currently released.
cmake_maximum_version = get_latest_cmake_version()
# The currently installed version of CMake on the System. Exits if CMake is not detected.
cmake_installed_version = get_installed_cmake_version()
# prints a warning message
########################################################################################################################
def warning(*s):
print("".join(s))
########################################################################################################################
# Checks if there is already a library called
########################################################################################################################
def has_library(name):
for l in libraries:
if l.canonic_name == name:
return True
return False
########################################################################################################################
# counts the parentheses in the line. Returns 0 if the number of opened parenthesis equals the number of closed ones
########################################################################################################################
def count_parentheses(line):
parco = 0
for char in line:
if char == '(':
parco += 1
if char == ')':
parco -= 1
return parco
########################################################################################################################
# Replaces the quotes with escaped quotes to be put in the CMakeLists.txt
########################################################################################################################
def replace_quotes(value):
value = value.replace('\"', '\\"')
return value
def get_library_for_name(name):
for library in libraries:
if library.canonic_name == name:
return library
return None
########################################################################################################################
# returns the similarity of two strings.
########################################################################################################################
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
########################################################################################################################
# Whether the directory is excluded or not
########################################################################################################################
def should_exclude(dire):
for exc_dir in exclude_directories:
if dire.startswith(exc_dir):
return True
return False
########################################################################################################################
# removes the garbage characters from the given string
########################################################################################################################
def remove_garbage(extra_value):
extra_value = extra_value.replace(']', '')
extra_value = extra_value.replace(',', '')
extra_value = extra_value.replace('[', '')
extra_value = extra_value.replace('$', '')
extra_value = extra_value.replace('(', '')
extra_value = extra_value.replace(')', '')
extra_value = extra_value.strip()
return extra_value
########################################################################################################################
# All characters in the name except for letters, numbers, the strudel (@), and the underscore are turned into underscores
########################################################################################################################
def canonicalize(a):
canonic_name = ""
for c in a:
if c.isdigit() or c.isalpha() or c =='_':
canonic_name += c
else:
canonic_name += "_"
return canonic_name
########################################################################################################################
# Finds a file with the given name
########################################################################################################################
def find_file(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
########################################################################################################################
# processes the given AC_ARG_ENABLE and creates an entry in the global options
########################################################################################################################
def process_argument(line):
s = line[len("AC_ARG_ENABLE("):].strip()
# fetch the name of the argument
arg_name = ""
for c in s:
if c == ',':
break
arg_name += c
# fetch the description of the argument
description = ""
for i in range(len(s)):
if s[i] == '[':
# after the [ come spaces
i += 1
while s[i] == ' ' and i < len(s):
i += 1
# then comes the option names, skip that
while s[i] != ' ' and i < len(s):
i += 1
# and then again a lot of spaces
while s[i] == ' ' and i < len(s):
i += 1
# then finally the description, till the closing ]
while s[i] != ']' and i < len(s):
description += s[i]
i += 1
# we have the description, just break out from here
break
# now see if this is on or off
on_off = "OFF"
if "=yes" in s:
on_off = "ON"
arg_name = arg_name.replace("-", "_")
# and add to the big options structure above
if not (arg_name in options):
options[arg_name] = Option(arg_name, description, on_off, "", "", "")
else:
options[arg_name].set_name(arg_name)
options[arg_name].set_description(description)
options[arg_name].set_status(on_off)
########################################################################################################################
# Checks whether this line os processable by the script or not
########################################################################################################################
def processable_line(line):
possible_starts = ["AC_ARG_ENABLE(", "AM_CONDITIONAL(", "AC_DEFINE(", "AC_CONFIG_FILES("]
for start in possible_starts:
if line.startswith(start):
return start[:-1]
return ""
########################################################################################################################
# processes the AM_CONDITIONAL lines
########################################################################################################################
def process_conditional(line):
s = line[len("AM_CONDITIONAL("):].strip()
define_name = ""
for c in s:
if c == ',':
break
define_name += c
bound_option = ""
stage = 1 # 1 - skipping, 2 - adding
for c in s:
if (c == '"' or c == ' ' or c == '=') and stage == 2:
break
if stage == 2:
bound_option += c
if c == '$':
stage = 2
bound_option = bound_option.replace("-", "_")
if bound_option in options:
options[bound_option].set_define(define_name)
else:
options[bound_option] = Option(bound_option, "", "", define_name, "", "")
########################################################################################################################
# this will process the defines from the configure.ac, but puts them in a separate list, with the comments
########################################################################################################################
def process_a_define(line):
s = line[len("AC_DEFINE("):].strip()
# now parse out the define data from s
define_string = ""
defined_to_value = ""
define_description = ""
stage = 1 # 1 - parsing the define name, 2 parsing the define value, 3 - parsing the define description
sqp = 0
roup = 1
for c in s:
if c == '[':
sqp += 1
if c == ']':
sqp -= 1
if c == '(':
roup += 1
if c == ')':
roup -= 1
# Did we close the parentheses for AC_DEFINE( ?
if roup == 0:
break
if c == ',' and sqp == 0:
stage += 1
if stage == 4:
break
if stage == 1 and c != ',':
define_string += c
elif stage == 2 and c != ',':
defined_to_value += c
elif stage == 3:
define_description += c
# and finding the variable name (option name in later stages here)
variable_name = ""
stage = 1 # 1 - skipping, 2 - adding
for c in s:
if c == '"' and stage == 2:
break
if stage == 2:
variable_name += c
if c == '$':
stage = 2
temp_defines[define_string] = {}
temp_defines[define_string]["name"] = define_string
temp_defines[define_string]["option_name"] = variable_name.upper()
temp_defines[define_string]["description"] = define_description
temp_defines[define_string]["value"] = defined_to_value
temp_defines[define_string]["used"] = 0
########################################################################################################################
# processes a Makefile.am
########################################################################################################################
def process_makefile_am(file):
# the content of the outgoing CMakeLists.txt
if not os.path.isfile(file):
warning("File not found:", file)
return
current_directory = os.path.dirname(file)
if should_exclude(current_directory):
return
# Will recurse into these dires
dirs_to_go_in = []
defined_variables = {}
libraries_in_this_file = []
with open(file) as f:
content = f.readlines()
# First run: parse out all the libraries
for line in content:
line = line.strip()
# is this a valid line? ie. no comments?
if line.startswith("#"):
continue
# Yes, valid line
if line.find("_LIBRARIES") != -1 or line.find("_PROGRAMS") != -1:
elements = line.split()
library_names = elements[2:]
makefiles_directory = current_directory
process_it = True
for excluded_dir in exclude_directories:
if makefiles_directory.startswith(excluded_dir) and excluded_dir:
process_it = False
if process_it:
for library_name in library_names:
library = Library(library_name, makefiles_directory)
# program or library?
if line.find("_PROGRAMS") != -1:
library.target_type = TargetType.PROGRAM
library.referred_name = library.canonic_name
if not has_library(library.canonic_name):
libraries.append(library)
# Next run: gather the source codes for all the libraries created in this file. Parse "if"'s also
if_condition = ""
for i in range(len(content)):
line = content[i].strip()
# is this a valid line? ie. no comments?
if line.startswith("#"):
continue
if line.startswith("if"):
elements = line.split()
if_condition = elements[1]
if line.startswith("endif"):
if_condition = ""
# see if this is an assignment or not
if '=' in line or "+=" in line:
# simple assignment
# read in the line as long as we don't have ending \\
while line.endswith('\\'):
i += 1
line += content[i].strip()
line = line.replace("\\", "")
line = ''.join('%-1s' % item for item in line.split('\t '))
used = False
elements = line.split("=")
variable = elements[0].strip()
if '+' in variable:
variable = variable.replace('+', '').strip()
# see if this is a SOURCE identifier for a specific library
if variable.endswith("_SOURCES"):
# find the lib name
target_lib_name = variable[:-len("_SOURCES")]
# now find the library from the libraries list, built in the previous step
library = get_library_for_name(target_lib_name)
if library:
used = True
libraries_in_this_file.append(target_lib_name)
# do we have a condition for this library?
if if_condition:
library.condition += if_condition
if "+=" in line:
library.filelist += elements[1].split()
else:
library.filelist = elements[1].split()
if variable.endswith("_LDADD"):
# find the lib name
target_lib_name = variable[:-len("_LDADD")]
library = get_library_for_name(target_lib_name)
if library in libraries:
used = True
libraries_in_this_file.append(target_lib_name)
# do we have a condition for this library?
if if_condition:
library.condition += if_condition
if "+=" in line:
library.link_with_libs += elements[1].split()
else:
library.link_with_libs = elements[1].split()
if variable.endswith("_CXXFLAGS") or variable.endswith("_CPPFLAGS") or variable.endswith("_CFLAGS"):
# find the lib name
if variable.endswith("_CFLAGS"):
target_lib_name = variable[:-len("_CFLAGS")]
else:
target_lib_name = variable[:-len("_CXXFLAGS")]
library = get_library_for_name(target_lib_name)
if library in libraries:
used = True
libraries_in_this_file.append(target_lib_name)
# do we have a condition for this library?
if if_condition:
library.condition += if_condition
defines = line.replace(variable, "", 1)
defines = defines.replace("=", "", 1)
defines = defines.strip()
if "+=" in line:
library.compiler_flags += defines
else:
library.compiler_flags = defines
if variable.endswith("_LDFLAGS"):
# find the lib name
target_lib_name = variable[:-len("_LDFLAGS")]
library = get_library_for_name(target_lib_name)
if library in libraries:
used = True
libraries_in_this_file.append(target_lib_name)
# do we have a condition for this library?
if if_condition:
library.condition += if_condition
if "+=" in line:
library.linker_flags += elements[1].split()
else:
library.linker_flags = elements[1].split()
if not used:
if variable == "SUBDIRS":
dirs_to_go_in = elements[1]
# This is possibly just a "simple" variable. Highly possible just gathers
# stuff and uses it at a later stage with $(varname)
if variable.find("_LIBRARIES") == -1 and variable.find("_PROGRAMS") == -1:
if not variable in defined_variables:
defined_variables[variable] = {}
defined_variables[variable]["value"] = []
defined_variables[variable]["value"].append(elements[1].split())
defined_variables[variable]["condition"] = []
defined_variables[variable]["condition"].append(if_condition)
else:
defined_variables[variable]["value"].append(elements[1].split())
defined_variables[variable]["condition"].append(if_condition)
# now the entire file is parsed. See if we can make any replacement of values
# from $(variable) to the actual definition of the variable
# Identifying the conditional variables
if defined_variables:
# Iterating through the defined variables.
# Searches for the presence of any library.filelist element starting with $.
# If any elements are found matching the criteria above, they are replaced.
for var_name in defined_variables:
for defined_lib_name in set(libraries_in_this_file):
found = False
library = get_library_for_name(defined_lib_name)
for file in library.filelist:
inside_varname = "$(" + var_name + ")"
if file.find(inside_varname) != -1:
# Now, we have a list of #ifdef condition, append $source like stuff
condition_iterable = zip(defined_variables[var_name]["condition"], defined_variables[var_name]["value"])
for condition, value in condition_iterable:
condition_name = remove_garbage(condition)
if condition_name in library.conditional_appends:
library.conditional_appends[condition_name].append(' '.join(value))
else:
library.conditional_appends[condition_name] = value
found = True
break
if not found:
library.just_variables[var_name] = defined_variables[var_name]["value"]
if dirs_to_go_in:
# These stuff will go in a directory -> add_subdirectory map above
extra_dir = ""
for subdir in dirs_to_go_in.split():
if not should_exclude(current_directory + "/" + subdir):
if "$(" in subdir or "${" in subdir:
subdir = subdir.replace("$(", "${")
extra_dir += "\nif( " + subdir + " )\n add_subdirectory( " + subdir + " )\nendif()"
else:
extra_dir += "\nadd_subdirectory( " + subdir + " )"
required_directories.append(current_directory + "/" + subdir)
extra_content[current_directory] = extra_dir
########################################################################################################################
# processes all the libraries, creates the requested CMakeFile list of the application
########################################################################################################################
def process_libraries():
for library in libraries:
current_content = ""
added_files = []
if generate_comments:
current_content += "# Generating the library " + library.name + "\n"
current_content += "set(project \"" + library.referred_name + "\")\n\n"
current_content += "set(${project} \"\")\n"
condition_required = ""
# Iterating through the conditional appends for the current library in the iteration sequence
for condition in library.conditional_appends:
conditional_append = library.conditional_appends[condition]
if condition:
# If the condition is true, the options are iterated through.
# now find the condition from option, having define set to this "condition"
used_condition = False
for opt_name in options:
option = options[opt_name]
if option.get_define() == condition:
used_condition = True
# and of course parse out the "conditional_append" from the simple variables of the library
# and generate cmake code which updates a list :)... also should be valid
current_content += "\nif(" + option.get_name() + ")\n"
unfolded_conditionals = ""
condition_required = option.get_name()
for cond_append in conditional_append:
if '$' in cond_append:
nice_var_name = remove_garbage(cond_append)
if nice_var_name in library.just_variables:
l = [item for sublist in library.just_variables[nice_var_name] for item in sublist]
unfolded_conditionals = filelist_to_string(l, library.directory, 8)
if unfolded_conditionals:
current_content += " list(APPEND ${project}_SOURCES" + unfolded_conditionals
added_files.append(unfolded_conditionals)
else:
file_list = "\n ".join(conditional_append)
current_content += " list(APPEND ${project}_SOURCES\n " + file_list
added_files.append(file_list)
current_content += "\n )\nendif()\n"
if not used_condition:
# We did not find this above, regardless generate an if() for it and a source of files
condition_required = condition
current_content += "\nif(" + condition + ")\n"
file_list = "\n ".join(conditional_append)
current_content += " list(APPEND ${project}_SOURCES\n " + file_list
current_content += "\n )\nendif()\n"
added_files.append(file_list)
else:
add_regardless = []
unfolded_conditionals = ""
for cond_append in conditional_append:
if '$' in cond_append:
nice_var_name = remove_garbage(cond_append)
if nice_var_name in library.just_variables:
l = [item for sublist in library.just_variables[nice_var_name] for item in sublist]
unfolded_conditionals = filelist_to_string(l, library.directory, 8)
else:
add_regardless.append(cond_append)