-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathcooker.py
1374 lines (1056 loc) · 52.7 KB
/
cooker.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
#!/usr/bin/env python3
""" cooker.py: meta build tool for Yocto Project based Linux embedded systems."""
import argparse
import pyjson5
import json
import os
import re
import sys
from urllib.parse import urlparse
import jsonschema
import importlib.resources
import subprocess
import shlex
from abc import ABC, abstractmethod
from collections.abc import Mapping
from typing import List
import cooker
__version__ = '1.4.0'
def debug(*args):
if CookerCall.DEBUG:
print(*args, file=sys.stderr)
def info(*args):
print('# ', end='')
print(*args)
sys.stdout.flush()
def warn(*args):
print('WARN:', *args, file=sys.stderr)
def fatal_error(*args):
print('FATAL:', *args, file=sys.stderr)
sys.exit(1)
def merge_dicts(base, other):
for k, v in other.items():
if isinstance(v, Mapping):
base[k] = merge_dicts(base.get(k, {}), v)
elif isinstance(v, list) and isinstance(base.get(k), list):
base[k] = base[k] + v
else:
base[k] = v
return base
class OsCalls:
def create_directory(self, directory):
os.makedirs(directory, exist_ok=True)
def file_open(self, filename):
return open(filename, 'w')
def file_write(self, file, string):
file.write('{}\n'.format(string))
def file_close(self, file):
file.close()
def file_exists(self, filename):
return os.path.isfile(filename)
def directory_exists(self, dirname):
return os.path.isdir(dirname)
def replace_process(self, shell: str, args: List[str]):
return os.execv(shell, args)
def subprocess_run(self, args, cwd, capture_output=True):
return subprocess.run(args, capture_output=capture_output, cwd=cwd)
class DryRunOsCalls:
def create_directory(self, directory):
print('mkdir {}'.format(directory))
sys.stdout.flush()
def file_open(self, filename):
print('cat > {} <<-EOF'.format(filename))
sys.stdout.flush()
return 0
def file_write(self, file, string):
print('\t{}'.format(string.replace('$', '\$')))
sys.stdout.flush()
def file_close(self, file):
print('EOF')
sys.stdout.flush()
def file_exists(self, filename):
return True
def directory_exists(self, dirname):
return True
def replace_process(self, shell: str, args: List[str]):
print('exec {} {}'.format(shell, ' '.join(args)))
return True
def subprocess_run(self, args, cwd, capture_output=True):
if cwd is not None:
print("cd " + cwd)
print(' '.join(args))
sys.stdout.flush()
return subprocess.CompletedProcess(args, 0, stderr="")
class Config:
DEFAULT_CONFIG_FILENAME = '.cookerconfig'
DEFAULT_CONFIG = {
'menu': '',
'additional_menus': list(),
'layer-dir': 'layers',
'build-dir': 'builds',
'dl-dir': 'downloads',
'sstate-dir': 'sstate-cache',
'cooker-config-version': 2
}
CURRENT_CONFIG_VERSION = 2
def __init__(self):
debug('Looking for', Config.DEFAULT_CONFIG_FILENAME)
self.filename = os.path.join(os.getcwd(), self.DEFAULT_CONFIG_FILENAME)
path = os.getcwd().split(os.sep)
while path:
filename = '/' + os.path.join(*path, self.DEFAULT_CONFIG_FILENAME)
debug(' Trying', filename)
if os.path.isfile(filename):
debug(' Found')
self.filename = filename
found = False
try:
with open(self.filename) as json_file:
self.cfg = json.load(json_file)
found = True
except Exception as e:
fatal_error('configuration load error', e)
if found:
self.check_and_migrate_config()
self.path = "/".join(path)
return
break
path.pop() # cd ..
self.cfg = self.DEFAULT_CONFIG.copy()
self.path = ""
debug('No config-file found. Will be using', self.filename)
def check_and_migrate_config(self):
config_version = self.cfg.get('cooker-config-version', 0)
if config_version == self.CURRENT_CONFIG_VERSION:
return
debug(f'migrating cookerconfig from {config_version} to {self.CURRENT_CONFIG_VERSION}')
## here we add changes incrementally from one version to another (do not elif)
# from 0 to 1 we added the sstate-dir
if config_version == 0:
if 'sstate-dir' not in self.cfg: # intermediate version where sstate-dir was added
self.cfg['sstate-dir'] = self.DEFAULT_CONFIG['sstate-dir']
config_version = 1
if config_version == 1:
if 'additional_menus' not in self.cfg: # intermediate version where sstate-dir was added
self.cfg['additional_menus'] = self.DEFAULT_CONFIG['additional_menus']
config_version = 2
# cooker-config-version is updated
self.cfg['cooker-config-version'] = config_version
self.save()
def project_root(self):
return os.path.dirname(self.filename)
def set_menu(self, menu_file):
if menu_file.startswith('/'):
self.cfg['menu'] = os.path.realpath(menu_file)
else:
self.cfg['menu'] = os.path.relpath(menu_file, self.path)
def set_additional_menus(self, additional_menus):
self.cfg['additional_menus'] = list()
for menu_file in additional_menus:
if menu_file.startswith('/'):
self.cfg['additional_menus'].append(os.path.realpath(menu_file))
else:
self.cfg['additional_menus'].append(os.path.relpath(menu_file, self.path))
def set_layer_dir(self, path):
# paths in the config-file are relative to the project-dir
self.cfg['layer-dir'] = os.path.relpath(path, self.project_root())
def layer_dir(self, name=''):
return os.path.join(self.project_root(), self.cfg['layer-dir'], name)
def set_build_dir(self, path):
self.cfg['build-dir'] = os.path.relpath(path, self.project_root())
def build_dir(self, name=''):
return os.path.join(self.project_root(), self.cfg['build-dir'], name)
def set_dl_dir(self, path):
self.cfg['dl-dir'] = os.path.relpath(path, self.project_root())
def dl_dir(self):
return os.path.join(self.project_root(), self.cfg['dl-dir'])
def set_sstate_dir(self, path):
self.cfg['sstate-dir'] = os.path.relpath(path, self.project_root())
def sstate_dir(self, name=''):
return os.path.join(self.project_root(), self.cfg['sstate-dir'], name)
def menu(self):
menu_path = self.cfg['menu']
if menu_path.startswith('/'):
return menu_path
else:
return self.path + "/" + menu_path
def additional_menus(self):
additional_menus_path = list()
if 'additional_menus' not in self.cfg:
return additional_menus_path
for menu_path in self.cfg['additional_menus']:
if menu_path.startswith('/'):
additional_menus_path.append(menu_path)
else:
additional_menus_path.append(self.path + "/" + menu_path)
return additional_menus_path
def save(self):
debug('Saving configuration file')
with open(self.filename, 'w') as json_file:
json.dump(self.cfg, json_file, indent=4)
def empty(self):
return not self.cfg['menu']
class BuildConfiguration:
ALL = {}
def __init__(self, name, config, layers, local_conf, target, inherit):
self.name_ = name
self.config_ = config
self.layers_ = layers
self.local_conf_ = local_conf
if type(target) == list:
self.targets_ = target
elif target:
self.targets_ = [target]
else:
self.targets_ = []
self.inherit_ = inherit
self.parents_ = [] # first level parents
self.ancestors_ = [] # all ancestors cleaned of duplicates
BuildConfiguration.ALL[name] = self
def targets(self):
if not self.buildable():
return None
for build in [self] + self.ancestors_[::-1]:
if build.targets_:
return build.targets_
def name(self):
return self.name_
def dir(self):
return self.config_.build_dir('build-' + self.name_)
def buildable(self):
if self.name_.startswith('.'): # template
return False
return any(build.targets_ for build in self.ancestors_ + [self])
def layers(self):
layers = []
for build in self.ancestors_ + [self]:
for layer in build.layers_:
if layer not in layers:
layers.append(layer)
else:
debug('ignored - duplicate layer for build "{}": "{}"'
.format(build.name(), layer))
return layers
def local_conf(self):
lines = []
for build in self.ancestors_ + [self]:
for new_line in build.local_conf_:
if new_line in lines:
debug('ignored - duplicate line in local.conf for build "{}": "{}"'
.format(build.name(), new_line))
lines.append(new_line)
return lines
def set_parents(self):
debug('setting first-level-parents of build "{}"'.format(self.name_))
if self.inherit_:
for parent_name in self.inherit_:
if parent_name not in BuildConfiguration.ALL:
fatal_error('build "{}"\'s parent "{}" not found in builds-section'
.format(self.name_, parent_name))
parent_instance = BuildConfiguration.ALL[parent_name]
if parent_instance == self:
fatal_error('"{}" inherits from itself, that is impossible'.format(self.name_))
debug('adding {} as parent to {}'.format(parent_instance.name(), self.name()))
self.parents_.append(parent_instance)
def get_ancestors(self, start, path=None):
if path is None:
path = list()
path.append(self.name())
parents = []
if start in self.parents_:
fatal_error('recursive inheritance detected for "{}" via "{}"'
.format(start.name(), ' -> '.join(path + [start.name()])))
for parent in self.parents_:
new_parents = parent.get_ancestors(start, path) + [parent]
for new_parent in new_parents:
if new_parent in parents:
debug('build "{}" parent "{}" inherited multiple times - ignoring'
.format(self.name(), new_parent.name()))
else:
parents.append(new_parent)
path.pop()
return parents
def resolve_parents():
for _, build in BuildConfiguration.ALL.items():
build.set_parents()
for _, build in BuildConfiguration.ALL.items():
build.ancestors_ = build.get_ancestors(build)
debug('ancestors of build "{}": "{}"'
.format(build.name(), [n.name() for n in build.ancestors_]))
class PokyDistro:
DISTRO_NAME = "poky"
BASE_DIRECTORY = "poky"
BUILD_SCRIPT = "oe-init-build-env"
TEMPLATE_CONF = ("meta-poky/conf", "meta-poky/conf/templates/default")
DEFAULT_CONF_VERSION = "1"
LAYER_CONF_NAME = "POKY_BBLAYERS_CONF_VERSION"
LAYER_CONF_VERSION = "2"
PACKAGE_FORMAT = "package_rpm"
DEFAULT_BITBAKE_MAJOR_VERSION = 2
BITBAKE_INIT_FILE = "bitbake/lib/bb/__init__.py"
class AragoDistro:
DISTRO_NAME = "arago"
BASE_DIRECTORY = "openembedded-core"
BUILD_SCRIPT = "oe-init-build-env"
TEMPLATE_CONF = ("meta/conf",)
DEFAULT_CONF_VERSION = "1"
LAYER_CONF_NAME = "LCONF_VERSION"
LAYER_CONF_VERSION = "7"
PACKAGE_FORMAT = "package_ipk"
DEFAULT_BITBAKE_MAJOR_VERSION = 2
BITBAKE_INIT_FILE = "sources/bitbake/lib/__init__.py"
class LogFormat(ABC):
def __init__(self, changes):
self.changes = changes
self.output = ""
@abstractmethod
def print_history(self, history):
pass
@abstractmethod
def print_added_item(self, source, rev):
pass
def print_modified_item(self, source, data):
if 'history' in data:
self.print_history(data['history'])
@abstractmethod
def print_deleted_item(self, source, rev):
pass
def print_added(self, changes):
for source, data in changes.items():
self.print_added_item(source, data)
def print_modified(self, changes):
for source, data in changes.items():
self.print_modified_item(source, data)
def print_deleted(self, changes):
for source, data in changes.items():
self.print_deleted_item(source, data)
def generate(self):
if self.changes['added']:
self.print_added(self.changes['added'])
if self.changes['modified']:
self.print_modified(self.changes['modified'])
if self.changes['deleted']:
self.print_deleted(self.changes['deleted'])
def add_line(self, line=""):
if self.output:
self.output += "\n"
self.output += line
def display(self):
print(self.output)
class LogTextFormat(LogFormat):
def print_history(self, history):
for line in history:
self.add_line(' {}'.format(line))
def print_added_item(self, source, rev):
self.add_line('A {}: {}'.format(source, rev))
def print_modified_item(self, source, data):
self.add_line('M {}: {} .. {}'.format(source, data['from'], data['to']))
super().print_modified_item(source, data)
def print_deleted_item(self, source, rev):
self.add_line('D {}: {}'.format(source, rev))
class LogMarkdownFormat(LogFormat):
def print_history(self, history):
for line in history:
self.add_line(' - {}'.format(line))
def print_added_item(self, source, rev):
self.add_line('- {} at revision {}'.format(source, rev))
def print_modified_item(self, source, data):
self.add_line('- {} changed from {} to {}'.format(source, data['from'], data['to']))
super().print_modified_item(source, data)
def print_deleted_item(self, source, rev):
self.add_line('- {} at revision {}'.format(source, rev))
def print_added(self, changes):
self.add_line('## Added projects')
super().print_added(changes)
self.add_line()
def print_modified(self, changes):
self.add_line('## Modified projects')
super().print_modified(changes)
self.add_line()
def print_deleted(self, changes):
self.add_line('## Deleted projects')
super().print_deleted(changes)
self.add_line()
class CookerCommands:
""" The class aggregates all functions representing a low-level cooker-command """
def __init__(self, config, menu):
self.config = config
self.menu = menu
if menu is not None:
distros = {
'poky': PokyDistro,
'arago': AragoDistro,
}
name = menu.setdefault('base-distribution', 'poky')
try:
self.distro = distros[name.lower()]
except:
fatal_error('base-distribution {} is unknown, please add a `base-distribution.py` file next your menu.'.format(name))
# Update distro if custom distro is defined in menu
self.update_override_distro()
def init(self, menu_name, layer_dir=None, build_dir=None, dl_dir=None, sstate_dir=None, additional_menus=list()):
""" cooker-command 'init': (re)set the configuration file """
self.config.set_menu(menu_name)
self.config.set_additional_menus(additional_menus)
if layer_dir:
self.config.set_layer_dir(layer_dir)
if build_dir:
self.config.set_build_dir(build_dir)
if dl_dir:
self.config.set_dl_dir(dl_dir)
if sstate_dir:
self.config.set_sstate_dir(sstate_dir)
self.config.save()
def update(self):
info('Update layers in project directory')
for source in self.menu['sources']:
self.update_source(source)
def local_dir_from_source(self, source):
if 'dir' in source:
local_dir = source['dir']
else:
local_dir = None
if 'url' in source:
try:
if '://' in source['url']:
url = urlparse(source['url'])
local_dir = url.path[1:]
elif ':' in source['url']: # must be short URL
_, local_dir = source['url'].split(':', 2)
else:
raise ValueError('invalid source URL given')
except Exception as e:
fatal_error('url-parse-error', source['url'], e)
return os.path.realpath(self.config.layer_dir(local_dir)), source['url']
def update_source(self, source):
method = 'git'
if 'method' in source:
method = source['method']
if method == 'ignore':
return
local_dir, remote_dir = self.local_dir_from_source(source)
branch = source.setdefault('branch', '')
rev = source.setdefault('rev', '')
if not os.path.isdir(local_dir):
self.update_directory_initial(method, local_dir, remote_dir, branch, rev)
if CookerCall.os.directory_exists(local_dir):
self.update_directory(method, local_dir, remote_dir != '', branch, rev)
def update_directory_initial(self, method, local_dir, remote_dir, branch, rev):
info('Downloading source from ', remote_dir)
if CookerCall.VERBOSE:
redirect = ''
else:
redirect = ' >/dev/null 2>&1'
if method == 'git':
complete = CookerCall.os.subprocess_run(["git", "ls-remote", remote_dir ], None)
if complete.stdout is not None:
refs = complete.stdout.decode("utf-8")
else:
refs=""
command = ["git", "clone", "--recurse-submodules", remote_dir, local_dir]
if re.search("refs/tags/" + rev + "$", refs, re.MULTILINE):
command.extend(["--branch", rev])
elif branch != '':
command.extend(["--branch", branch])
complete = CookerCall.os.subprocess_run(command, None)
if complete.returncode != 0:
fatal_error('Unable to clone {}: {}'.format(remote_dir, complete.stderr.decode('ascii')))
def update_directory(self, method, local_dir, has_remote, branch, rev):
if CookerCall.VERBOSE:
redirect = ''
else:
redirect = ' >/dev/null 2>&1'
if method == 'git':
if rev == '':
if branch == '':
warn('WARNING! source "{}" has no "rev" nor "branch" field, '.format(local_dir) +
'the build will not be reproducible at all!')
info('Trying to update source {}... '.format(local_dir))
if has_remote:
complete = CookerCall.os.subprocess_run(["git", "pull"], local_dir)
if complete.returncode != 0:
fatal_error('Unable to pull updates for {}: {}'.format(local_dir, complete.stderr.decode('ascii')))
else:
warn('source "{}" has no "rev" field, the build will not be reproducible!'.format(local_dir))
info('Updating source {}... '.format(local_dir))
complete = CookerCall.os.subprocess_run(["git", "checkout", branch], local_dir)
if complete.returncode != 0:
fatal_error('Unable to checkout branch {} for {}: {}'.format(branch, local_dir, complete.stderr.decode('ascii')))
if has_remote:
complete = CookerCall.os.subprocess_run(["git", "pull"], local_dir)
if complete.returncode != 0:
fatal_error('Unable to pull updates for {}: {}'.format(local_dir, complete.stderr.decode('ascii')))
else:
info('Updating source {}... '.format(local_dir))
complete = CookerCall.os.subprocess_run(["git", "fetch"], local_dir)
if complete.returncode != 0:
fatal_error('Unable to fetch {}: {}'.format(local_dir, complete.stderr.decode('ascii')))
complete = CookerCall.os.subprocess_run(["git", "checkout", rev], local_dir)
if complete.returncode != 0:
fatal_error('Unable to checkout rev {} for {}: {}'.format(rev, local_dir, complete.stderr.decode('ascii')))
complete = CookerCall.os.subprocess_run(["git", "submodule", "update", "--recursive", "--init"], local_dir)
if complete.returncode != 0:
fatal_error('Unable to update submodules in {}: {}'.format(local_dir, complete.stderr.decode('ascii')))
def diff(self):
for source in self.menu['sources']:
local_dir = self.local_dir_from_source(source)[0]
source_name = os.path.basename(local_dir)
debug('check the diff of the source {}'.format(source_name))
if 'rev' not in source:
debug('no revision field in the menu file for source {}'.format(source_name))
continue
menu_rev = source['rev']
if not CookerCall.os.directory_exists(local_dir):
warn('{} directory of source {} does not exist'.format(local_dir, source_name))
continue
complete = CookerCall.os.subprocess_run(["git", "describe", "--abbrev=7", "--tags", "--always", "--dirty"], local_dir)
if complete.returncode != 0:
warn('unable to get the current revision of the local source {}'.format(local_dir))
debug(complete.stderr.decode('ascii'))
continue
local_rev = complete.stdout.strip().decode('ascii')
debug('menu revision: {}, local revision: {}'.format(menu_rev, local_rev))
if menu_rev != local_rev:
print('{}: {} .. {}'.format(source_name, menu_rev, local_rev))
def generate_build_config_from_menu(self, menu, build_name):
"""
Generates the BuildConfiguration classes from the given menu version.
Resolve the parents and returns the BuildConfiguration class of the build.
Backup and restore the ALL BuildConfiguration class variable to avoid
overwriting the existing content.
"""
backup = BuildConfiguration.ALL
BuildConfiguration.ALL = {}
BuildConfiguration('root',
self.config,
menu.setdefault('layers', []),
menu.setdefault('local.conf', []),
None,
None)
for name, build in menu['builds'].items():
BuildConfiguration(name,
self.config,
build.setdefault('layers', []),
build.setdefault('local.conf', []),
build.setdefault('target', None),
build.setdefault('inherit', ['root']))
resolve_parents()
build_config = BuildConfiguration.ALL[build_name]
BuildConfiguration.ALL = backup
return build_config
def get_sources_from_build_layers(self, menu, layers):
"""
Returns a simplistic key/value entry ('source-name: revision') of the
sources from the layers used by the build.
"""
layers_dir = list(dict.fromkeys(list(map(lambda p: p.split('/')[0], layers))))
sources = {}
for source in menu['sources']:
key = os.path.basename(self.local_dir_from_source(source)[0])
value = source['rev']
if key in layers_dir:
sources[key] = value
return sources
def load_and_validate_menu(self, menu_file, schema):
with open(menu_file, "r") as file:
try:
menu = pyjson5.load(file)
except Exception as e:
fatal_error('menu load error:', e)
try:
jsonschema.validate(menu, schema)
except Exception as e:
fatal_error('menu file {} validation failed:'.format(menu_file), e)
debug('menu file {} validation passed'.format(menu_file))
return menu
def log(self, build_name, menu_from_file, menu_to_file, history, log_format):
"""
Generates a log of the build sources revision changes between two menu file version.
"""
schema_file = importlib.resources.files('cooker').joinpath('cooker-menu-schema.json').read_text()
schema = pyjson5.loads(schema_file)
menu_from = self.load_and_validate_menu(menu_from_file, schema)
menu_to = self.menu
if build_name not in menu_from['builds'] or build_name not in menu_to['builds']:
fatal_error('build `{}` does not exist in the menu file'.format(build_name))
# Generates a BuildConfiguration class for the menu since the build layers
# can change between menu version. If 'menu to' is ommitted, use the
# current up-to-date BuildConfiguration class.
build_config_from = self.generate_build_config_from_menu(menu_from, build_name)
build_config_to = BuildConfiguration.ALL[build_name]
if menu_to_file is not None:
menu_to = self.load_and_validate_menu(menu_to_file, schema)
build_config_to = self.generate_build_config_from_menu(menu_to, build_name)
# Gets the sources used by the build from the list of layers.
sources_from = self.get_sources_from_build_layers(menu_from, build_config_from.layers())
sources_to = self.get_sources_from_build_layers(menu_to, build_config_to.layers())
debug('sources `from` menu: {}'.format(sources_from))
debug('sources `to` menu: {}'.format(sources_to))
# Filters the changes from sources. Local directory basename of the source
# as key, source revision as value.
changes = {}
changes['added'] = {s: sources_to[s] for s in sources_to if s not in sources_from}
changes['modified'] = {s: {'from': sources_from[s], 'to': sources_to[s]} for s in sources_to if s in sources_from and sources_to[s] != sources_from[s]}
changes['deleted'] = {s: sources_from[s] for s in sources_from if s not in sources_to}
# Append the git commit history for the filtered modified sources.
if history is not None:
for source, data in changes['modified'].items():
if source in history and CookerCall.os.directory_exists(self.config.layer_dir(source)):
complete = CookerCall.os.subprocess_run(["git", "log", "{}..{}".format(data['from'], data['to']), "--oneline", "--abbrev-commit"], self.config.layer_dir(source))
if complete.returncode != 0:
warn('unable to get the git history of the source {}'.format(source))
debug(complete.stderr.decode('ascii'))
continue
data['history'] = complete.stdout.decode('ascii').splitlines()
# Prints the formatted log output from the changes dict.
if log_format in ['md', 'markdown']:
log = LogMarkdownFormat(changes)
else:
log = LogTextFormat(changes)
log.generate()
log.display()
def generate(self):
info('Generating dirs for all build-configurations')
self.read_local_conf_version()
for build in BuildConfiguration.ALL.values():
if build.buildable():
self.prepare_build_directory(build)
def generate_distro_base_dir_path(self):
"""
This method generates the full path to the distro base directory
"""
return os.path.join(self.config.layer_dir(), self.distro.BASE_DIRECTORY)
def get_template_conf_path(self):
"""
This method returns the relative path to the directory containing the local.conf.sample file
"""
for template_conf in self.distro.TEMPLATE_CONF:
full_path = os.path.join(
self.generate_distro_base_dir_path(),
template_conf,
"local.conf.sample"
)
if os.path.exists(full_path):
return template_conf
return
def get_template_conf_full_path(self):
"""
This method returns the full path to the directory containing the local.conf.sample file
"""
template_conf_path = self.get_template_conf_path()
if template_conf_path is None:
# Raises an Error when we don't find the local.conf.sample in template conf dir
raise FileNotFoundError(f"Can't find local.conf.sample file in any of the following folders: {' '.join(self.distro.TEMPLATE_CONF)}")
else:
full_path = os.path.join(
self.generate_distro_base_dir_path(),
template_conf_path,
"local.conf.sample"
)
return full_path
return
def read_local_conf_version(self):
self.local_conf_version = str(self.distro.DEFAULT_CONF_VERSION)
try:
file = open(self.get_template_conf_full_path())
for line in file:
if line.lstrip().startswith("CONF_VERSION"):
self.local_conf_version = re.search(r'\d+', line).group(0)
return
except:
return
def read_bitbake_version(self):
self.bitbake_major_version = int(self.distro.DEFAULT_BITBAKE_MAJOR_VERSION)
try:
file = open(self.config.layer_dir() + self.distro.BASE_DIRECTORY + "/" + self.distro.BITBAKE_INIT_FILE)
for line in file:
if '__version__' in line:
self.bitbake_major_version = int(line.split('=')[1].strip(' "').split('.')[0])
return
except:
return
def prepare_build_directory(self, build):
debug('Preparing directory:', build.dir())
CookerCall.os.create_directory(build.dir())
conf_path = os.path.join(build.dir(), 'conf')
CookerCall.os.create_directory(conf_path)
dl_dir = '${TOPDIR}/' + os.path.relpath(self.config.dl_dir(), build.dir())
sstate_dir = '${TOPDIR}/' + os.path.relpath(self.config.sstate_dir(), build.dir())
layer_dir = os.path.join('${TOPDIR}', os.path.relpath(self.config.layer_dir(), build.dir()))
self.read_bitbake_version()
halt_verb = "HALT"
if self.bitbake_major_version < 2:
halt_verb = "ABORT"
file = CookerCall.os.file_open(os.path.join(conf_path, 'local.conf'))
CookerCall.os.file_write(file, '# DO NOT EDIT! - This file is automatically created by cooker.\n\n')
CookerCall.os.file_write(file, 'COOKER_LAYER_DIR = "{}"'.format(layer_dir))
CookerCall.os.file_write(file, 'DL_DIR = "{}"'.format(dl_dir))
CookerCall.os.file_write(file, 'SSTATE_DIR = "{}"'.format(sstate_dir))
CookerCall.os.file_write(file, 'COOKER_BUILD_NAME = "{}"'.format(build.name()))
for line in build.local_conf():
CookerCall.os.file_write(file, line)
CookerCall.os.file_write(file, 'DISTRO ?= "{}"'.format(self.distro.DISTRO_NAME))
CookerCall.os.file_write(file, 'PACKAGE_CLASSES ?= "{}"'.format(self.distro.PACKAGE_FORMAT))
CookerCall.os.file_write(file, 'BB_DISKMON_DIRS ??= "\\')
CookerCall.os.file_write(file, '\tSTOPTASKS,${TMPDIR},1G,100K \\')
CookerCall.os.file_write(file, '\tSTOPTASKS,${DL_DIR},1G,100K \\')
CookerCall.os.file_write(file, '\tSTOPTASKS,${SSTATE_DIR},1G,100K \\')
CookerCall.os.file_write(file, '\tSTOPTASKS,/tmp,100M,100K \\')
CookerCall.os.file_write(file, '\t{},${{TMPDIR}},100M,1K \\'.format(halt_verb))
CookerCall.os.file_write(file, '\t{},${{DL_DIR}},100M,1K \\'.format(halt_verb))
CookerCall.os.file_write(file, '\t{},${{SSTATE_DIR}},100M,1K \\'.format(halt_verb))
CookerCall.os.file_write(file, '\t{},/tmp,10M,1K"'.format(halt_verb))
CookerCall.os.file_write(file, 'CONF_VERSION ?= "{}"'.format(self.local_conf_version))
CookerCall.os.file_close(file)
file = CookerCall.os.file_open(os.path.join(conf_path, 'bblayers.conf'))
CookerCall.os.file_write(file, '# DO NOT EDIT! - This file is automatically created by cooker.\n\n')
CookerCall.os.file_write(file, '{} = "{}"'.format(self.distro.LAYER_CONF_NAME, self.distro.LAYER_CONF_VERSION))
CookerCall.os.file_write(file, 'BBPATH = "${TOPDIR}"')
CookerCall.os.file_write(file, 'BBFILES ?= ""')
CookerCall.os.file_write(file, 'BBLAYERS ?= " \\')
for layer in sorted(build.layers()):
layer_path = os.path.relpath(self.config.layer_dir(layer), build.dir())
CookerCall.os.file_write(file, '\t${{TOPDIR}}/{} \\'.format(layer_path))
CookerCall.os.file_write(file, '"\n')
CookerCall.os.file_close(file)
file = CookerCall.os.file_open(os.path.join(conf_path, 'templateconf.cfg'))
CookerCall.os.file_write(file, '{}\n'.format(self.get_template_conf_path()))
CookerCall.os.file_close(file)
def show(self, builds, layers, conf, tree, build_arg, sources):
# show source dirs
if sources:
for source in self.menu['sources']:
l, r = self.local_dir_from_source(source)
info('source URL:', r)
info(' locally: ', l)
# check if selected builds exist
for build in builds:
if build not in BuildConfiguration.ALL:
fatal_error('cannot show infos about build "{}" as it does not exists.'.format(build))
# empty given builds - use all existing ones
if not builds:
builds = BuildConfiguration.ALL.keys()
# print information per build
for build_name in sorted(builds):
build = BuildConfiguration.ALL[build_name]
if build.targets():
build_info = ' (bakes {})'.format(', '.join(build.targets()))
else:
build_info = ''
info('build: {}{}'.format(build.name(), build_info))
if layers:
info(' used layers')
for layer in build.layers():
info(' - {} ({})'.format(layer, self.config.layer_dir(layer)))
if conf:
info(' local.conf entries')
for entry in build.local_conf():
info(' - {}'.format(entry))
if build_arg:
if build.targets():
info(' .',
os.path.relpath(self.config.layer_dir(self.distro.BASE_DIRECTORY + "/" + self.distro.BUILD_SCRIPT), os.getcwd()),
os.path.relpath(build.dir(), os.getcwd()))
else:
info('build', build.name(), 'has no target')
if tree:
if build.ancestors_:
info('builds ancestors:', [n.name() for n in build.ancestors_])
def build(self, builds, sdk, keepgoing, download):