/
gnome.py
2171 lines (1941 loc) · 101 KB
/
gnome.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 2015-2016 The Meson development team
# 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.
'''This module provides helper functions for Gnome/GLib related
functionality such as gobject-introspection, gresources and gtk-doc'''
from __future__ import annotations
import copy
import itertools
import functools
import os
import subprocess
import textwrap
import typing as T
from . import ExtensionModule, ModuleInfo
from . import ModuleReturnValue
from .. import build
from .. import interpreter
from .. import mesonlib
from .. import mlog
from ..build import CustomTarget, CustomTargetIndex, Executable, GeneratedList, InvalidArguments
from ..dependencies import Dependency, PkgConfigDependency, InternalDependency
from ..interpreter.type_checking import DEPENDS_KW, DEPEND_FILES_KW, INSTALL_DIR_KW, INSTALL_KW, NoneType, SOURCES_KW, in_set_validator
from ..interpreterbase import noPosargs, noKwargs, FeatureNew, FeatureDeprecated
from ..interpreterbase import typed_kwargs, KwargInfo, ContainerTypeInfo
from ..interpreterbase.decorators import typed_pos_args
from ..mesonlib import (
MachineChoice, MesonException, OrderedSet, Popen_safe, join_args,
)
from ..programs import OverrideProgram
from ..scripts.gettext import read_linguas
if T.TYPE_CHECKING:
from typing_extensions import Literal, TypedDict
from . import ModuleState
from ..build import BuildTarget
from ..compilers import Compiler
from ..interpreter import Interpreter
from ..interpreterbase import TYPE_var, TYPE_kwargs
from ..mesonlib import FileOrString
from ..programs import ExternalProgram
class PostInstall(TypedDict):
glib_compile_schemas: bool
gio_querymodules: T.List[str]
gtk_update_icon_cache: bool
update_desktop_database: bool
update_mime_database: bool
class CompileSchemas(TypedDict):
build_by_default: bool
depend_files: T.List[FileOrString]
class Yelp(TypedDict):
languages: T.List[str]
media: T.List[str]
sources: T.List[str]
symlink_media: bool
class CompileResources(TypedDict):
build_by_default: bool
c_name: T.Optional[str]
dependencies: T.List[T.Union[mesonlib.File, build.CustomTarget, build.CustomTargetIndex]]
export: bool
extra_args: T.List[str]
gresource_bundle: bool
install: bool
install_dir: T.Optional[str]
install_header: bool
source_dir: T.List[str]
class GenerateGir(TypedDict):
build_by_default: bool
dependencies: T.List[Dependency]
export_packages: T.List[str]
extra_args: T.List[str]
fatal_warnings: bool
header: T.List[str]
identifier_prefix: T.List[str]
include_directories: T.List[T.Union[build.IncludeDirs, str]]
includes: T.List[T.Union[str, GirTarget]]
install: bool
install_dir_gir: T.Optional[str]
install_dir_typelib: T.Optional[str]
link_with: T.List[T.Union[build.SharedLibrary, build.StaticLibrary]]
namespace: str
nsversion: str
sources: T.List[T.Union[FileOrString, build.GeneratedTypes]]
symbol_prefix: T.List[str]
class GtkDoc(TypedDict):
src_dir: T.List[T.Union[str, build.IncludeDirs]]
main_sgml: str
main_xml: str
module_version: str
namespace: str
mode: Literal['xml', 'smgl', 'auto', 'none']
html_args: T.List[str]
scan_args: T.List[str]
scanobjs_args: T.List[str]
fixxref_args: T.List[str]
mkdb_args: T.List[str]
content_files: T.List[T.Union[build.GeneratedTypes, FileOrString]]
ignore_headers: T.List[str]
install_dir: T.List[str]
check: bool
install: bool
gobject_typesfile: T.List[FileOrString]
html_assets: T.List[FileOrString]
expand_content_files: T.List[FileOrString]
c_args: T.List[str]
include_directories: T.List[T.Union[str, build.IncludeDirs]]
dependencies: T.List[T.Union[Dependency, build.SharedLibrary, build.StaticLibrary]]
class GdbusCodegen(TypedDict):
sources: T.List[FileOrString]
extra_args: T.List[str]
interface_prefix: T.Optional[str]
namespace: T.Optional[str]
object_manager: bool
build_by_default: bool
annotations: T.List[T.List[str]]
install_header: bool
install_dir: T.Optional[str]
docbook: T.Optional[str]
autocleanup: Literal['all', 'none', 'objects', 'default']
class GenMarshal(TypedDict):
build_always: T.Optional[str]
build_always_stale: T.Optional[bool]
build_by_default: T.Optional[bool]
depend_files: T.List[mesonlib.File]
extra_args: T.List[str]
install_dir: T.Optional[str]
install_header: bool
internal: bool
nostdinc: bool
prefix: T.Optional[str]
skip_source: bool
sources: T.List[FileOrString]
stdinc: bool
valist_marshallers: bool
class GenerateVapi(TypedDict):
sources: T.List[T.Union[str, GirTarget]]
install_dir: T.Optional[str]
install: bool
vapi_dirs: T.List[str]
metadata_dirs: T.List[str]
gir_dirs: T.List[str]
packages: T.List[T.Union[str, InternalDependency]]
class _MkEnumsCommon(TypedDict):
sources: T.List[T.Union[FileOrString, build.GeneratedTypes]]
install_header: bool
install_dir: T.Optional[str]
identifier_prefix: T.Optional[str]
symbol_prefix: T.Optional[str]
class MkEnumsSimple(_MkEnumsCommon):
header_prefix: str
decorator: str
function_prefix: str
body_prefix: str
class MkEnums(_MkEnumsCommon):
c_template: T.Optional[FileOrString]
h_template: T.Optional[FileOrString]
comments: T.Optional[str]
eprod: T.Optional[str]
fhead: T.Optional[str]
fprod: T.Optional[str]
ftail: T.Optional[str]
vhead: T.Optional[str]
vprod: T.Optional[str]
vtail: T.Optional[str]
depends: T.List[T.Union[BuildTarget, CustomTarget, CustomTargetIndex]]
# Differs from the CustomTarget version in that it straight defaults to True
_BUILD_BY_DEFAULT: KwargInfo[bool] = KwargInfo(
'build_by_default', bool, default=True,
)
_EXTRA_ARGS_KW: KwargInfo[T.List[str]] = KwargInfo(
'extra_args',
ContainerTypeInfo(list, str),
default=[],
listify=True,
)
_MK_ENUMS_COMMON_KWS: T.List[KwargInfo] = [
INSTALL_KW.evolve(name='install_header'),
INSTALL_DIR_KW,
KwargInfo(
'sources',
ContainerTypeInfo(list, (str, mesonlib.File, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)),
listify=True,
required=True,
),
KwargInfo('identifier_prefix', (str, NoneType)),
KwargInfo('symbol_prefix', (str, NoneType)),
]
def annotations_validator(annotations: T.List[T.Union[str, T.List[str]]]) -> T.Optional[str]:
"""Validate gdbus-codegen annotations argument"""
badlist = 'must be made up of 3 strings for ELEMENT, KEY, and VALUE'
if not annotations:
return None
elif all(isinstance(annot, str) for annot in annotations):
if len(annotations) == 3:
return None
else:
return badlist
elif not all(isinstance(annot, list) for annot in annotations):
for c, annot in enumerate(annotations):
if not isinstance(annot, list):
return f'element {c+1} must be a list'
else:
for c, annot in enumerate(annotations):
if len(annot) != 3 or not all(isinstance(i, str) for i in annot):
return f'element {c+1} {badlist}'
return None
class GResourceTarget(build.CustomTarget):
pass
class GResourceHeaderTarget(build.CustomTarget):
pass
class GirTarget(build.CustomTarget):
pass
class TypelibTarget(build.CustomTarget):
pass
class VapiTarget(build.CustomTarget):
pass
# gresource compilation is broken due to the way
# the resource compiler and Ninja clash about it
#
# https://github.com/ninja-build/ninja/issues/1184
# https://bugzilla.gnome.org/show_bug.cgi?id=774368
gresource_dep_needed_version = '>= 2.51.1'
class GnomeModule(ExtensionModule):
INFO = ModuleInfo('gnome')
def __init__(self, interpreter: 'Interpreter') -> None:
super().__init__(interpreter)
self.gir_dep: T.Optional[Dependency] = None
self.giscanner: T.Optional[T.Union[ExternalProgram, build.Executable, OverrideProgram]] = None
self.gicompiler: T.Optional[T.Union[ExternalProgram, build.Executable, OverrideProgram]] = None
self.install_glib_compile_schemas = False
self.install_gio_querymodules: T.List[str] = []
self.install_gtk_update_icon_cache = False
self.install_update_desktop_database = False
self.install_update_mime_database = False
self.devenv: T.Optional[build.EnvironmentVariables] = None
self.native_glib_version: T.Optional[str] = None
self.methods.update({
'post_install': self.post_install,
'compile_resources': self.compile_resources,
'generate_gir': self.generate_gir,
'compile_schemas': self.compile_schemas,
'yelp': self.yelp,
'gtkdoc': self.gtkdoc,
'gtkdoc_html_dir': self.gtkdoc_html_dir,
'gdbus_codegen': self.gdbus_codegen,
'mkenums': self.mkenums,
'mkenums_simple': self.mkenums_simple,
'genmarshal': self.genmarshal,
'generate_vapi': self.generate_vapi,
})
def _get_native_glib_version(self, state: 'ModuleState') -> str:
if self.native_glib_version is None:
glib_dep = PkgConfigDependency('glib-2.0', state.environment,
{'native': True, 'required': False})
if glib_dep.found():
self.native_glib_version = glib_dep.get_version()
else:
mlog.warning('Could not detect glib version, assuming 2.54. '
'You may get build errors if your glib is older.')
self.native_glib_version = '2.54'
return self.native_glib_version
@mesonlib.run_once
def __print_gresources_warning(self, state: 'ModuleState') -> None:
if not mesonlib.version_compare(self._get_native_glib_version(state),
gresource_dep_needed_version):
mlog.warning('GLib compiled dependencies do not work reliably with \n'
'the current version of GLib. See the following upstream issue:',
mlog.bold('https://bugzilla.gnome.org/show_bug.cgi?id=774368'),
once=True, fatal=False)
@staticmethod
def _print_gdbus_warning() -> None:
mlog.warning('Code generated with gdbus_codegen() requires the root directory be added to\n'
' include_directories of targets with GLib < 2.51.3:',
mlog.bold('https://github.com/mesonbuild/meson/issues/1387'),
once=True, fatal=False)
@typed_kwargs(
'gnome.post_install',
KwargInfo('glib_compile_schemas', bool, default=False),
KwargInfo('gio_querymodules', ContainerTypeInfo(list, str), default=[], listify=True),
KwargInfo('gtk_update_icon_cache', bool, default=False),
KwargInfo('update_desktop_database', bool, default=False, since='0.59.0'),
KwargInfo('update_mime_database', bool, default=False, since='0.64.0'),
)
@noPosargs
@FeatureNew('gnome.post_install', '0.57.0')
def post_install(self, state: 'ModuleState', args: T.List['TYPE_var'], kwargs: 'PostInstall') -> ModuleReturnValue:
rv: T.List['build.ExecutableSerialisation'] = []
datadir_abs = os.path.join(state.environment.get_prefix(), state.environment.get_datadir())
if kwargs['glib_compile_schemas'] and not self.install_glib_compile_schemas:
self.install_glib_compile_schemas = True
prog = state.find_tool('glib-compile-schemas', 'gio-2.0', 'glib_compile_schemas')
schemasdir = os.path.join(datadir_abs, 'glib-2.0', 'schemas')
script = state.backend.get_executable_serialisation([prog, schemasdir])
script.skip_if_destdir = True
rv.append(script)
for d in kwargs['gio_querymodules']:
if d not in self.install_gio_querymodules:
self.install_gio_querymodules.append(d)
prog = state.find_tool('gio-querymodules', 'gio-2.0', 'gio_querymodules')
moduledir = os.path.join(state.environment.get_prefix(), d)
script = state.backend.get_executable_serialisation([prog, moduledir])
script.skip_if_destdir = True
rv.append(script)
if kwargs['gtk_update_icon_cache'] and not self.install_gtk_update_icon_cache:
self.install_gtk_update_icon_cache = True
prog = state.find_program('gtk4-update-icon-cache', required=False)
found = isinstance(prog, build.Executable) or prog.found()
if not found:
prog = state.find_program('gtk-update-icon-cache')
icondir = os.path.join(datadir_abs, 'icons', 'hicolor')
script = state.backend.get_executable_serialisation([prog, '-q', '-t', '-f', icondir])
script.skip_if_destdir = True
rv.append(script)
if kwargs['update_desktop_database'] and not self.install_update_desktop_database:
self.install_update_desktop_database = True
prog = state.find_program('update-desktop-database')
appdir = os.path.join(datadir_abs, 'applications')
script = state.backend.get_executable_serialisation([prog, '-q', appdir])
script.skip_if_destdir = True
rv.append(script)
if kwargs['update_mime_database'] and not self.install_update_mime_database:
self.install_update_mime_database = True
prog = state.find_program('update-mime-database')
appdir = os.path.join(datadir_abs, 'mime')
script = state.backend.get_executable_serialisation([prog, appdir])
script.skip_if_destdir = True
rv.append(script)
return ModuleReturnValue(None, rv)
@typed_pos_args('gnome.compile_resources', str, (str, mesonlib.File, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList))
@typed_kwargs(
'gnome.compile_resources',
_BUILD_BY_DEFAULT,
_EXTRA_ARGS_KW,
INSTALL_KW,
INSTALL_KW.evolve(name='install_header', since='0.37.0'),
INSTALL_DIR_KW,
KwargInfo('c_name', (str, NoneType)),
KwargInfo('dependencies', ContainerTypeInfo(list, (mesonlib.File, build.CustomTarget, build.CustomTargetIndex)), default=[], listify=True),
KwargInfo('export', bool, default=False, since='0.37.0'),
KwargInfo('gresource_bundle', bool, default=False, since='0.37.0'),
KwargInfo('source_dir', ContainerTypeInfo(list, str), default=[], listify=True),
)
def compile_resources(self, state: 'ModuleState', args: T.Tuple[str, 'FileOrString'],
kwargs: 'CompileResources') -> 'ModuleReturnValue':
self.__print_gresources_warning(state)
glib_version = self._get_native_glib_version(state)
glib_compile_resources = state.find_program('glib-compile-resources')
cmd: T.List[T.Union[ExternalProgram, Executable, OverrideProgram, str]] = [glib_compile_resources, '@INPUT@']
source_dirs = kwargs['source_dir']
dependencies = kwargs['dependencies']
target_name, input_file = args
# Validate dependencies
subdirs: T.List[str] = []
depends: T.List[T.Union[build.CustomTarget, build.CustomTargetIndex]] = []
for dep in dependencies:
if isinstance(dep, mesonlib.File):
subdirs.append(dep.subdir)
else:
depends.append(dep)
subdirs.append(dep.get_subdir())
if not mesonlib.version_compare(glib_version, gresource_dep_needed_version):
m = 'The "dependencies" argument of gnome.compile_resources() can not\n' \
'be used with the current version of glib-compile-resources due to\n' \
'<https://bugzilla.gnome.org/show_bug.cgi?id=774368>'
raise MesonException(m)
if not mesonlib.version_compare(glib_version, gresource_dep_needed_version):
# Resource xml files generated at build-time cannot be used with
# gnome.compile_resources() because we need to scan the xml for
# dependencies. Use configure_file() instead to generate it at
# configure-time
if isinstance(input_file, mesonlib.File):
# glib-compile-resources will be run inside the source dir,
# so we need either 'src_to_build' or the absolute path.
# Absolute path is the easiest choice.
if input_file.is_built:
ifile = os.path.join(state.environment.get_build_dir(), input_file.subdir, input_file.fname)
else:
ifile = os.path.join(input_file.subdir, input_file.fname)
elif isinstance(input_file, (build.CustomTarget, build.CustomTargetIndex, build.GeneratedList)):
raise MesonException('Resource xml files generated at build-time cannot be used with '
'gnome.compile_resources() in the current version of glib-compile-resources '
'because we need to scan the xml for dependencies due to '
'<https://bugzilla.gnome.org/show_bug.cgi?id=774368>\nUse '
'configure_file() instead to generate it at configure-time.')
else:
ifile = os.path.join(state.subdir, input_file)
depend_files, depends, subdirs = self._get_gresource_dependencies(
state, ifile, source_dirs, dependencies)
# Make source dirs relative to build dir now
source_dirs = [os.path.join(state.build_to_src, state.subdir, d) for d in source_dirs]
# Ensure build directories of generated deps are included
source_dirs += subdirs
# Always include current directory, but after paths set by user
source_dirs.append(os.path.join(state.build_to_src, state.subdir))
for source_dir in OrderedSet(source_dirs):
cmd += ['--sourcedir', source_dir]
if kwargs['c_name']:
cmd += ['--c-name', kwargs['c_name']]
if not kwargs['export']:
cmd += ['--internal']
cmd += ['--generate', '--target', '@OUTPUT@']
cmd += kwargs['extra_args']
gresource = kwargs['gresource_bundle']
if gresource:
output = f'{target_name}.gresource'
name = f'{target_name}_gresource'
else:
if 'c' in state.environment.coredata.compilers.host:
output = f'{target_name}.c'
name = f'{target_name}_c'
elif 'cpp' in state.environment.coredata.compilers.host:
output = f'{target_name}.cpp'
name = f'{target_name}_cpp'
else:
raise MesonException('Compiling GResources into code is only supported in C and C++ projects')
if kwargs['install'] and not gresource:
raise MesonException('The install kwarg only applies to gresource bundles, see install_header')
install_header = kwargs['install_header']
if install_header and gresource:
raise MesonException('The install_header kwarg does not apply to gresource bundles')
if install_header and not kwargs['export']:
raise MesonException('GResource header is installed yet export is not enabled')
depfile: T.Optional[str] = None
target_cmd: T.List[T.Union[ExternalProgram, Executable, OverrideProgram, str]]
if not mesonlib.version_compare(glib_version, gresource_dep_needed_version):
# This will eventually go out of sync if dependencies are added
target_cmd = cmd
else:
depfile = f'{output}.d'
depend_files = []
target_cmd = copy.copy(cmd) + ['--dependency-file', '@DEPFILE@']
target_c = GResourceTarget(
name,
state.subdir,
state.subproject,
state.environment,
target_cmd,
[input_file],
[output],
build_by_default=kwargs['build_by_default'],
depfile=depfile,
depend_files=depend_files,
extra_depends=depends,
install=kwargs['install'],
install_dir=[kwargs['install_dir']] if kwargs['install_dir'] else [],
install_tag=['runtime'],
)
if gresource: # Only one target for .gresource files
return ModuleReturnValue(target_c, [target_c])
install_dir = kwargs['install_dir'] or state.environment.coredata.get_option(mesonlib.OptionKey('includedir'))
assert isinstance(install_dir, str), 'for mypy'
target_h = GResourceHeaderTarget(
f'{target_name}_h',
state.subdir,
state.subproject,
state.environment,
cmd,
[input_file],
[f'{target_name}.h'],
build_by_default=kwargs['build_by_default'],
extra_depends=depends,
install=install_header,
install_dir=[install_dir],
install_tag=['devel'],
)
rv = [target_c, target_h]
return ModuleReturnValue(rv, rv)
@staticmethod
def _get_gresource_dependencies(
state: 'ModuleState', input_file: str, source_dirs: T.List[str],
dependencies: T.Sequence[T.Union[mesonlib.File, build.CustomTarget, build.CustomTargetIndex]]
) -> T.Tuple[T.List[mesonlib.FileOrString], T.List[T.Union[build.CustomTarget, build.CustomTargetIndex]], T.List[str]]:
cmd = ['glib-compile-resources',
input_file,
'--generate-dependencies']
# Prefer generated files over source files
cmd += ['--sourcedir', state.subdir] # Current build dir
for source_dir in source_dirs:
cmd += ['--sourcedir', os.path.join(state.subdir, source_dir)]
try:
pc, stdout, stderr = Popen_safe(cmd, cwd=state.environment.get_source_dir())
except (FileNotFoundError, PermissionError):
raise MesonException('Could not execute glib-compile-resources.')
if pc.returncode != 0:
m = f'glib-compile-resources failed to get dependencies for {cmd[1]}:\n{stderr}'
mlog.warning(m)
raise subprocess.CalledProcessError(pc.returncode, cmd)
raw_dep_files: T.List[str] = stdout.split('\n')[:-1]
depends: T.List[T.Union[build.CustomTarget, build.CustomTargetIndex]] = []
subdirs: T.List[str] = []
dep_files: T.List[mesonlib.FileOrString] = []
for resfile in raw_dep_files.copy():
resbasename = os.path.basename(resfile)
for dep in dependencies:
if isinstance(dep, mesonlib.File):
if dep.fname != resbasename:
continue
raw_dep_files.remove(resfile)
dep_files.append(dep)
subdirs.append(dep.subdir)
break
elif isinstance(dep, (build.CustomTarget, build.CustomTargetIndex)):
fname = None
outputs = {(o, os.path.basename(o)) for o in dep.get_outputs()}
for o, baseo in outputs:
if baseo == resbasename:
fname = o
break
if fname is not None:
raw_dep_files.remove(resfile)
depends.append(dep)
subdirs.append(dep.get_subdir())
break
else:
# In generate-dependencies mode, glib-compile-resources doesn't raise
# an error for missing resources but instead prints whatever filename
# was listed in the input file. That's good because it means we can
# handle resource files that get generated as part of the build, as
# follows.
#
# If there are multiple generated resource files with the same basename
# then this code will get confused.
try:
f = mesonlib.File.from_source_file(state.environment.get_source_dir(),
".", resfile)
except MesonException:
raise MesonException(
f'Resource "{resfile}" listed in "{input_file}" was not found. '
'If this is a generated file, pass the target that generates '
'it to gnome.compile_resources() using the "dependencies" '
'keyword argument.')
raw_dep_files.remove(resfile)
dep_files.append(f)
dep_files.extend(raw_dep_files)
return dep_files, depends, subdirs
def _get_link_args(self, state: 'ModuleState',
lib: T.Union[build.SharedLibrary, build.StaticLibrary],
depends: T.Sequence[T.Union[build.BuildTarget, 'build.GeneratedTypes', 'FileOrString', build.StructuredSources]],
include_rpath: bool = False,
use_gir_args: bool = False
) -> T.Tuple[T.List[str], T.List[T.Union[build.BuildTarget, 'build.GeneratedTypes', 'FileOrString', build.StructuredSources]]]:
link_command: T.List[str] = []
new_depends = list(depends)
# Construct link args
if isinstance(lib, build.SharedLibrary):
libdir = os.path.join(state.environment.get_build_dir(), state.backend.get_target_dir(lib))
link_command.append('-L' + libdir)
if include_rpath:
link_command.append('-Wl,-rpath,' + libdir)
new_depends.append(lib)
# Needed for the following binutils bug:
# https://github.com/mesonbuild/meson/issues/1911
# However, g-ir-scanner does not understand -Wl,-rpath
# so we need to use -L instead
for d in state.backend.determine_rpath_dirs(lib):
d = os.path.join(state.environment.get_build_dir(), d)
link_command.append('-L' + d)
if include_rpath:
link_command.append('-Wl,-rpath,' + d)
if use_gir_args and self._gir_has_option('--extra-library'):
link_command.append('--extra-library=' + lib.name)
else:
link_command.append('-l' + lib.name)
return link_command, new_depends
def _get_dependencies_flags_raw(
self, deps: T.Sequence[T.Union['Dependency', build.BuildTarget, build.CustomTarget, build.CustomTargetIndex]],
state: 'ModuleState',
depends: T.Sequence[T.Union[build.BuildTarget, 'build.GeneratedTypes', 'FileOrString', build.StructuredSources]],
include_rpath: bool,
use_gir_args: bool,
) -> T.Tuple[OrderedSet[str], OrderedSet[T.Union[str, T.Tuple[str, str]]], OrderedSet[T.Union[str, T.Tuple[str, str]]], OrderedSet[str],
T.List[T.Union[build.BuildTarget, 'build.GeneratedTypes', 'FileOrString', build.StructuredSources]]]:
cflags: OrderedSet[str] = OrderedSet()
# External linker flags that can't be de-duped reliably because they
# require two args in order, such as -framework AVFoundation will be stored as a tuple.
internal_ldflags: OrderedSet[T.Union[str, T.Tuple[str, str]]] = OrderedSet()
external_ldflags: OrderedSet[T.Union[str, T.Tuple[str, str]]] = OrderedSet()
gi_includes: OrderedSet[str] = OrderedSet()
deps = mesonlib.listify(deps)
depends = list(depends)
for dep in deps:
if isinstance(dep, Dependency):
girdir = dep.get_variable(pkgconfig='girdir', internal='girdir', default_value='')
if girdir:
assert isinstance(girdir, str), 'for mypy'
gi_includes.update([girdir])
if isinstance(dep, InternalDependency):
cflags.update(dep.get_compile_args())
cflags.update(state.get_include_args(dep.include_directories))
for lib in dep.libraries:
if isinstance(lib, build.SharedLibrary):
_ld, depends = self._get_link_args(state, lib, depends, include_rpath)
internal_ldflags.update(_ld)
libdepflags = self._get_dependencies_flags_raw(lib.get_external_deps(), state, depends, include_rpath,
use_gir_args)
cflags.update(libdepflags[0])
internal_ldflags.update(libdepflags[1])
external_ldflags.update(libdepflags[2])
gi_includes.update(libdepflags[3])
depends = libdepflags[4]
extdepflags = self._get_dependencies_flags_raw(dep.ext_deps, state, depends, include_rpath,
use_gir_args)
cflags.update(extdepflags[0])
internal_ldflags.update(extdepflags[1])
external_ldflags.update(extdepflags[2])
gi_includes.update(extdepflags[3])
depends = extdepflags[4]
for source in dep.sources:
if isinstance(source, GirTarget):
gi_includes.update([os.path.join(state.environment.get_build_dir(),
source.get_subdir())])
# This should be any dependency other than an internal one.
elif isinstance(dep, Dependency):
cflags.update(dep.get_compile_args())
ldflags = iter(dep.get_link_args(raw=True))
for flag in ldflags:
if (os.path.isabs(flag) and
# For PkgConfigDependency only:
getattr(dep, 'is_libtool', False)):
lib_dir = os.path.dirname(flag)
external_ldflags.update([f'-L{lib_dir}'])
if include_rpath:
external_ldflags.update([f'-Wl,-rpath {lib_dir}'])
libname = os.path.basename(flag)
if libname.startswith("lib"):
libname = libname[3:]
libname = libname.split(".so")[0]
flag = f"-l{libname}"
# FIXME: Hack to avoid passing some compiler options in
if flag.startswith("-W"):
continue
# If it's a framework arg, slurp the framework name too
# to preserve the order of arguments
if flag == '-framework':
external_ldflags.update([(flag, next(ldflags))])
else:
external_ldflags.update([flag])
elif isinstance(dep, (build.StaticLibrary, build.SharedLibrary)):
cflags.update(state.get_include_args(dep.get_include_dirs()))
depends.append(dep)
else:
mlog.log(f'dependency {dep!r} not handled to build gir files')
continue
if use_gir_args and self._gir_has_option('--extra-library'):
def fix_ldflags(ldflags: T.Iterable[T.Union[str, T.Tuple[str, str]]]) -> OrderedSet[T.Union[str, T.Tuple[str, str]]]:
fixed_ldflags: OrderedSet[T.Union[str, T.Tuple[str, str]]] = OrderedSet()
for ldflag in ldflags:
if isinstance(ldflag, str) and ldflag.startswith("-l"):
ldflag = ldflag.replace('-l', '--extra-library=', 1)
fixed_ldflags.add(ldflag)
return fixed_ldflags
internal_ldflags = fix_ldflags(internal_ldflags)
external_ldflags = fix_ldflags(external_ldflags)
return cflags, internal_ldflags, external_ldflags, gi_includes, depends
def _get_dependencies_flags(
self, deps: T.Sequence[T.Union['Dependency', build.BuildTarget, build.CustomTarget, build.CustomTargetIndex]],
state: 'ModuleState',
depends: T.Sequence[T.Union[build.BuildTarget, 'build.GeneratedTypes', 'FileOrString', build.StructuredSources]],
include_rpath: bool = False,
use_gir_args: bool = False,
) -> T.Tuple[OrderedSet[str], T.List[str], T.List[str], OrderedSet[str],
T.List[T.Union[build.BuildTarget, 'build.GeneratedTypes', 'FileOrString', build.StructuredSources]]]:
cflags, internal_ldflags_raw, external_ldflags_raw, gi_includes, depends = self._get_dependencies_flags_raw(deps, state, depends, include_rpath, use_gir_args)
internal_ldflags: T.List[str] = []
external_ldflags: T.List[str] = []
# Extract non-deduplicable argument groups out of the tuples.
for ldflag in internal_ldflags_raw:
if isinstance(ldflag, str):
internal_ldflags.append(ldflag)
else:
internal_ldflags.extend(ldflag)
for ldflag in external_ldflags_raw:
if isinstance(ldflag, str):
external_ldflags.append(ldflag)
else:
external_ldflags.extend(ldflag)
return cflags, internal_ldflags, external_ldflags, gi_includes, depends
def _unwrap_gir_target(self, girtarget: T.Union[build.Executable, build.StaticLibrary, build.SharedLibrary], state: 'ModuleState'
) -> T.Union[build.Executable, build.StaticLibrary, build.SharedLibrary]:
if not isinstance(girtarget, (build.Executable, build.SharedLibrary,
build.StaticLibrary)):
raise MesonException(f'Gir target must be an executable or library but is "{girtarget}" of type {type(girtarget).__name__}')
STATIC_BUILD_REQUIRED_VERSION = ">=1.58.1"
if isinstance(girtarget, (build.StaticLibrary)) and \
not mesonlib.version_compare(
self._get_gir_dep(state)[0].get_version(),
STATIC_BUILD_REQUIRED_VERSION):
raise MesonException('Static libraries can only be introspected with GObject-Introspection ' + STATIC_BUILD_REQUIRED_VERSION)
return girtarget
def _devenv_prepend(self, varname: str, value: str) -> None:
if self.devenv is None:
self.devenv = build.EnvironmentVariables()
self.devenv.prepend(varname, [value])
def get_devenv(self) -> T.Optional[build.EnvironmentVariables]:
return self.devenv
def _get_gir_dep(self, state: 'ModuleState') -> T.Tuple[Dependency, T.Union[build.Executable, 'ExternalProgram', 'OverrideProgram'],
T.Union[build.Executable, 'ExternalProgram', 'OverrideProgram']]:
if not self.gir_dep or not self.gir_dep.found():
for (dep, req) in [('gobject-introspection-no-typelibs-1.0', False), ('gobject-introspection-1.0', True)]:
self.gir_dep = state.dependency(dep, required=req)
self.giscanner = state.find_tool('g-ir-scanner', dep, 'g_ir_scanner', required=req)
self.gicompiler = state.find_tool('g-ir-compiler', dep, 'g_ir_compiler', required=req)
if self.gir_dep.found():
break
return self.gir_dep, self.giscanner, self.gicompiler
@functools.lru_cache(maxsize=None)
def _gir_has_option(self, option: str) -> bool:
exe = self.giscanner
if isinstance(exe, OverrideProgram):
# Handle overridden g-ir-scanner
assert option in {'--extra-library', '--sources-top-dirs'}
return True
p, o, _ = Popen_safe(exe.get_command() + ['--help'], stderr=subprocess.STDOUT)
return p.returncode == 0 and option in o
# May mutate depends and gir_inc_dirs
@staticmethod
def _scan_include(state: 'ModuleState', includes: T.List[T.Union[str, GirTarget]]
) -> T.Tuple[T.List[str], T.List[str], T.List[GirTarget]]:
ret: T.List[str] = []
gir_inc_dirs: T.List[str] = []
depends: T.List[GirTarget] = []
for inc in includes:
if isinstance(inc, str):
ret += [f'--include={inc}']
elif isinstance(inc, GirTarget):
gir_inc_dirs .append(os.path.join(state.environment.get_build_dir(), inc.get_subdir()))
ret.append(f"--include-uninstalled={os.path.join(inc.get_subdir(), inc.get_basename())}")
depends.append(inc)
return ret, gir_inc_dirs, depends
@staticmethod
def _scan_langs(state: 'ModuleState', langs: T.Iterable[str]) -> T.List[str]:
ret: T.List[str] = []
for lang in langs:
link_args = state.environment.coredata.get_external_link_args(MachineChoice.HOST, lang)
for link_arg in link_args:
if link_arg.startswith('-L'):
ret.append(link_arg)
return ret
@staticmethod
def _scan_gir_targets(state: 'ModuleState', girtargets: T.Sequence[build.BuildTarget]) -> T.List[T.Union[str, build.Executable]]:
ret: T.List[T.Union[str, build.Executable]] = []
for girtarget in girtargets:
if isinstance(girtarget, build.Executable):
ret += ['--program', girtarget]
else:
# Because of https://gitlab.gnome.org/GNOME/gobject-introspection/merge_requests/72
# we can't use the full path until this is merged.
libpath = os.path.join(girtarget.get_subdir(), girtarget.get_filename())
# Must use absolute paths here because g-ir-scanner will not
# add them to the runtime path list if they're relative. This
# means we cannot use @BUILD_ROOT@
build_root = state.environment.get_build_dir()
if isinstance(girtarget, build.SharedLibrary):
# need to put our output directory first as we need to use the
# generated libraries instead of any possibly installed system/prefix
# ones.
ret += ["-L{}/{}".format(build_root, os.path.dirname(libpath))]
libname = girtarget.get_basename()
else:
libname = os.path.join(f"{build_root}/{libpath}")
ret += ['--library', libname]
# Needed for the following binutils bug:
# https://github.com/mesonbuild/meson/issues/1911
# However, g-ir-scanner does not understand -Wl,-rpath
# so we need to use -L instead
for d in state.backend.determine_rpath_dirs(girtarget):
d = os.path.join(state.environment.get_build_dir(), d)
ret.append('-L' + d)
return ret
@staticmethod
def _get_girtargets_langs_compilers(girtargets: T.Sequence[build.BuildTarget]) -> T.List[T.Tuple[str, 'Compiler']]:
ret: T.List[T.Tuple[str, 'Compiler']] = []
for girtarget in girtargets:
for lang, compiler in girtarget.compilers.items():
# XXX: Can you use g-i with any other language?
if lang in {'c', 'cpp', 'objc', 'objcpp', 'd'}:
ret.append((lang, compiler))
break
return ret
@staticmethod
def _get_gir_targets_deps(girtargets: T.Sequence[build.BuildTarget]
) -> T.List[T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex, Dependency]]:
ret: T.List[T.Union[build.BuildTarget, build.CustomTarget, build.CustomTargetIndex, Dependency]] = []
for girtarget in girtargets:
ret += girtarget.get_all_link_deps()
ret += girtarget.get_external_deps()
return ret
@staticmethod
def _get_gir_targets_inc_dirs(girtargets: T.Sequence[build.BuildTarget]) -> T.List[build.IncludeDirs]:
ret: T.List[build.IncludeDirs] = []
for girtarget in girtargets:
ret += girtarget.get_include_dirs()
return ret
@staticmethod
def _get_langs_compilers_flags(state: 'ModuleState', langs_compilers: T.List[T.Tuple[str, 'Compiler']]
) -> T.Tuple[T.List[str], T.List[str], T.List[str]]:
cflags: T.List[str] = []
internal_ldflags: T.List[str] = []
external_ldflags: T.List[str] = []
for lang, compiler in langs_compilers:
if state.global_args.get(lang):
cflags += state.global_args[lang]
if state.project_args.get(lang):
cflags += state.project_args[lang]
if mesonlib.OptionKey('b_sanitize') in compiler.base_options:
sanitize = state.environment.coredata.options[mesonlib.OptionKey('b_sanitize')].value
cflags += compiler.sanitizer_compile_args(sanitize)
sanitize = sanitize.split(',')
# These must be first in ldflags
if 'address' in sanitize:
internal_ldflags += ['-lasan']
if 'thread' in sanitize:
internal_ldflags += ['-ltsan']
if 'undefined' in sanitize:
internal_ldflags += ['-lubsan']
# FIXME: Linking directly to lib*san is not recommended but g-ir-scanner
# does not understand -f LDFLAGS. https://bugzilla.gnome.org/show_bug.cgi?id=783892
# ldflags += compiler.sanitizer_link_args(sanitize)
return cflags, internal_ldflags, external_ldflags
@staticmethod
def _make_gir_filelist(state: 'ModuleState', srcdir: str, ns: str,
nsversion: str, girtargets: T.Sequence[build.BuildTarget],
libsources: T.Sequence[T.Union[
str, mesonlib.File, build.GeneratedList,
build.CustomTarget, build.CustomTargetIndex]]
) -> str:
gir_filelist_dir = state.backend.get_target_private_dir_abs(girtargets[0])
if not os.path.isdir(gir_filelist_dir):
os.mkdir(gir_filelist_dir)
gir_filelist_filename = os.path.join(gir_filelist_dir, f'{ns}_{nsversion}_gir_filelist')
with open(gir_filelist_filename, 'w', encoding='utf-8') as gir_filelist:
for s in libsources:
if isinstance(s, (build.CustomTarget, build.CustomTargetIndex)):
for custom_output in s.get_outputs():
gir_filelist.write(os.path.join(state.environment.get_build_dir(),
state.backend.get_target_dir(s),
custom_output) + '\n')
elif isinstance(s, mesonlib.File):
gir_filelist.write(s.rel_to_builddir(state.build_to_src) + '\n')
elif isinstance(s, build.GeneratedList):
for gen_src in s.get_outputs():
gir_filelist.write(os.path.join(srcdir, gen_src) + '\n')
else:
gir_filelist.write(os.path.join(srcdir, s) + '\n')
return gir_filelist_filename
@staticmethod
def _make_gir_target(
state: 'ModuleState',
girfile: str,
scan_command: T.Sequence[T.Union['FileOrString', Executable, ExternalProgram, OverrideProgram]],
generated_files: T.Sequence[T.Union[str, mesonlib.File, build.CustomTarget, build.CustomTargetIndex, build.GeneratedList]],
depends: T.Sequence[T.Union['FileOrString', build.BuildTarget, 'build.GeneratedTypes', build.StructuredSources]],
kwargs: T.Dict[str, T.Any]) -> GirTarget:
install = kwargs['install_gir']
if install is None:
install = kwargs['install']
install_dir = kwargs['install_dir_gir']
if install_dir is None:
install_dir = os.path.join(state.environment.get_datadir(), 'gir-1.0')
elif install_dir is False:
install = False
# g-ir-scanner uses pkg-config to find libraries such as glib. They could
# be built as subproject in which case we need to trick it to use
# -uninstalled.pc files Meson generated. It also must respect pkgconfig
# settings user could have set in machine file, like PKG_CONFIG_LIBDIR,
# SYSROOT, etc.
run_env = PkgConfigDependency.get_env(state.environment, MachineChoice.HOST, uninstalled=True)
return GirTarget(
girfile,
state.subdir,
state.subproject,
state.environment,
scan_command,
generated_files,
[girfile],
build_by_default=kwargs['build_by_default'],
extra_depends=depends,
install=install,
install_dir=[install_dir],
install_tag=['devel'],
env=run_env,
)