forked from onnovalkering/brane
-
Notifications
You must be signed in to change notification settings - Fork 8
/
make.py
executable file
·3918 lines (3067 loc) · 150 KB
/
make.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
# MAKE.py
# by Lut99
#
# Created:
# 09 Jun 2022, 12:20:28
# Last edited:
# 08 Aug 2024, 14:17:26
# Auto updated?
# Yes
#
# Description:
# Python script that implements the (more advanced) make script for the
# Brane infrastructure.
#
from __future__ import annotations
import abc
import argparse
import hashlib
import json
import os
import pathlib
import platform
import shutil
import subprocess
import sys
import tarfile
import typing
##### CONSTANTS #####
# List of services that live in the central part of an instance
CENTRAL_SERVICES = [ "prx", "api", "drv", "plr" ]
# List of auxillary services in the central part of an instance
# At least, the ones we have to build.
AUX_CENTRAL_SERVICES = []
# List of services that live in a worker node in an instance
WORKER_SERVICES = [ "prx", "job", "reg", "chk" ]
# List of auxillary services in a worker node in an instance
AUX_WORKER_SERVICES = []
# The directory where we compile OpenSSL to
OPENSSL_DIR = "./target/openssl/$ARCH"
# The desired source files that we want to build against for OpenSSL
OPENSSL_FILES = [
OPENSSL_DIR + "/lib/libcrypto.a", OPENSSL_DIR + "/lib/libssl.a",
OPENSSL_DIR + "/lib/pkgconfig/libcrypto.pc", OPENSSL_DIR + "/lib/pkgconfig/libssl.pc", OPENSSL_DIR + "/lib/pkgconfig/openssl.pc",
OPENSSL_DIR + "/include/openssl/aes.h", OPENSSL_DIR + "/include/openssl/asn1err.h", OPENSSL_DIR + "/include/openssl/asn1.h",
OPENSSL_DIR + "/include/openssl/asn1_mac.h", OPENSSL_DIR + "/include/openssl/asn1t.h", OPENSSL_DIR + "/include/openssl/asyncerr.h",
OPENSSL_DIR + "/include/openssl/async.h", OPENSSL_DIR + "/include/openssl/bioerr.h", OPENSSL_DIR + "/include/openssl/bio.h",
OPENSSL_DIR + "/include/openssl/blowfish.h", OPENSSL_DIR + "/include/openssl/bnerr.h", OPENSSL_DIR + "/include/openssl/bn.h",
OPENSSL_DIR + "/include/openssl/buffererr.h", OPENSSL_DIR + "/include/openssl/buffer.h", OPENSSL_DIR + "/include/openssl/camellia.h",
OPENSSL_DIR + "/include/openssl/cast.h", OPENSSL_DIR + "/include/openssl/cmac.h", OPENSSL_DIR + "/include/openssl/cmserr.h",
OPENSSL_DIR + "/include/openssl/cms.h", OPENSSL_DIR + "/include/openssl/comperr.h", OPENSSL_DIR + "/include/openssl/comp.h",
OPENSSL_DIR + "/include/openssl/conf_api.h", OPENSSL_DIR + "/include/openssl/conferr.h", OPENSSL_DIR + "/include/openssl/conf.h",
OPENSSL_DIR + "/include/openssl/cryptoerr.h", OPENSSL_DIR + "/include/openssl/crypto.h", OPENSSL_DIR + "/include/openssl/cterr.h",
OPENSSL_DIR + "/include/openssl/ct.h", OPENSSL_DIR + "/include/openssl/des.h", OPENSSL_DIR + "/include/openssl/dherr.h",
OPENSSL_DIR + "/include/openssl/dh.h", OPENSSL_DIR + "/include/openssl/dsaerr.h", OPENSSL_DIR + "/include/openssl/dsa.h",
OPENSSL_DIR + "/include/openssl/dtls1.h", OPENSSL_DIR + "/include/openssl/ebcdic.h", OPENSSL_DIR + "/include/openssl/ecdh.h",
OPENSSL_DIR + "/include/openssl/ecdsa.h", OPENSSL_DIR + "/include/openssl/ecerr.h", OPENSSL_DIR + "/include/openssl/ec.h",
OPENSSL_DIR + "/include/openssl/engineerr.h", OPENSSL_DIR + "/include/openssl/engine.h", OPENSSL_DIR + "/include/openssl/e_os2.h",
OPENSSL_DIR + "/include/openssl/err.h", OPENSSL_DIR + "/include/openssl/evperr.h", OPENSSL_DIR + "/include/openssl/evp.h",
OPENSSL_DIR + "/include/openssl/hmac.h", OPENSSL_DIR + "/include/openssl/idea.h", OPENSSL_DIR + "/include/openssl/kdferr.h",
OPENSSL_DIR + "/include/openssl/kdf.h", OPENSSL_DIR + "/include/openssl/lhash.h", OPENSSL_DIR + "/include/openssl/md2.h",
OPENSSL_DIR + "/include/openssl/md4.h", OPENSSL_DIR + "/include/openssl/md5.h", OPENSSL_DIR + "/include/openssl/mdc2.h",
OPENSSL_DIR + "/include/openssl/modes.h", OPENSSL_DIR + "/include/openssl/objectserr.h", OPENSSL_DIR + "/include/openssl/objects.h",
OPENSSL_DIR + "/include/openssl/obj_mac.h", OPENSSL_DIR + "/include/openssl/ocsperr.h", OPENSSL_DIR + "/include/openssl/ocsp.h",
OPENSSL_DIR + "/include/openssl/opensslconf.h", OPENSSL_DIR + "/include/openssl/opensslv.h", OPENSSL_DIR + "/include/openssl/ossl_typ.h",
OPENSSL_DIR + "/include/openssl/pem2.h", OPENSSL_DIR + "/include/openssl/pemerr.h", OPENSSL_DIR + "/include/openssl/pem.h",
OPENSSL_DIR + "/include/openssl/pkcs12err.h", OPENSSL_DIR + "/include/openssl/pkcs12.h", OPENSSL_DIR + "/include/openssl/pkcs7err.h",
OPENSSL_DIR + "/include/openssl/pkcs7.h", OPENSSL_DIR + "/include/openssl/rand_drbg.h", OPENSSL_DIR + "/include/openssl/randerr.h",
OPENSSL_DIR + "/include/openssl/rand.h", OPENSSL_DIR + "/include/openssl/rc2.h", OPENSSL_DIR + "/include/openssl/rc4.h",
OPENSSL_DIR + "/include/openssl/rc5.h", OPENSSL_DIR + "/include/openssl/ripemd.h", OPENSSL_DIR + "/include/openssl/rsaerr.h",
OPENSSL_DIR + "/include/openssl/rsa.h", OPENSSL_DIR + "/include/openssl/safestack.h", OPENSSL_DIR + "/include/openssl/seed.h",
OPENSSL_DIR + "/include/openssl/sha.h", OPENSSL_DIR + "/include/openssl/srp.h", OPENSSL_DIR + "/include/openssl/srtp.h",
OPENSSL_DIR + "/include/openssl/ssl2.h", OPENSSL_DIR + "/include/openssl/ssl3.h", OPENSSL_DIR + "/include/openssl/sslerr.h",
OPENSSL_DIR + "/include/openssl/ssl.h", OPENSSL_DIR + "/include/openssl/stack.h", OPENSSL_DIR + "/include/openssl/storeerr.h",
OPENSSL_DIR + "/include/openssl/store.h", OPENSSL_DIR + "/include/openssl/symhacks.h", OPENSSL_DIR + "/include/openssl/tls1.h",
OPENSSL_DIR + "/include/openssl/tserr.h", OPENSSL_DIR + "/include/openssl/ts.h", OPENSSL_DIR + "/include/openssl/txt_db.h",
OPENSSL_DIR + "/include/openssl/uierr.h", OPENSSL_DIR + "/include/openssl/ui.h", OPENSSL_DIR + "/include/openssl/whrlpool.h",
OPENSSL_DIR + "/include/openssl/x509err.h", OPENSSL_DIR + "/include/openssl/x509.h", OPENSSL_DIR + "/include/openssl/x509v3err.h",
OPENSSL_DIR + "/include/openssl/x509v3.h", OPENSSL_DIR + "/include/openssl/x509_vfy.h"
]
##### HELPER FUNCTIONS #####
def supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
From: https://stackoverflow.com/a/22254892
"""
plat = sys.platform
supported_platform = plat != 'Pocket PC' and (plat != 'win32' or
'ANSICON' in os.environ)
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
return supported_platform and is_a_tty
def wrap_description(text: str, indent: int, max_width: int, skip_first_indent: bool = False) -> str:
"""
Wraps the given piece of text to be at most (but not including) `max_width` characters wide.
The `indent` indicates some arbitrary amount of indent to add before each line. This is included in the total width of the line.
"""
# Sanity check the indent
if indent >= max_width:
raise ValueError(f"indent must be lower than max_width (assertion {indent} < {max_width} fails)")
# Go through the text word-by-word
result = f"{(' ' * indent) if not skip_first_indent else ''}"
w = indent
for word in text.split():
# Get the length of the word minus the ansi escaped codes
word_len = 0
i = 0
while i < len(word):
# Get the char
c = word[i]
# Switch on ansi escape character or not
if c == '\033':
c = word[i + 1]
if c == '[':
# It is ansi; skip until and including the 'm'
j = 0
while i + j < len(word) and word[i + j] != 'm':
j += 1
i += 1 + j + 1
# Go to the next char
word_len += 1
i += 1
# Check if this word fits as a whole
if w + word_len < max_width:
# It does, add it
result += word
w += word_len
else:
# Otherwise, always go to a new line
result += f"\n{' ' * indent}"
w = indent
# Now pop entire lines off the word if it's always too long
while w + word_len >= max_width:
# Write the front line worth of characters
result += f"{word[:max_width - w]}\n{' ' * indent}"
w = indent
# Shrink the word
word = word[max_width - w:]
word_len -= max_width - w
# The word *must* fit now, so write it
result += word
w += word_len
# If it still fits, add a space
if w + 1 < max_width:
result += ' '
w += 1
# Done
return result
def to_bytes(val: int) -> str:
"""
Pretty-prints the given value to some byte count.
"""
if val < 1000:
return f"{val:.2f} bytes"
elif val < 1000000:
return f"{val / 1000:.2f} KB"
elif val < 1000000000:
return f"{val / 1000000:.2f} MB"
elif val < 1000000000000:
return f"{val / 1000000000:.2f} GB"
elif val < 1000000000000000:
return f"{val / 1000000000000:.2f} TB"
else:
return f"{val / 1000000000000000:.2f} PB"
def perror(text: str = "", colour: bool = True):
"""
Writes text to stderr, as an Error.
"""
# Get colours
start = "\033[91;1m" if colour and supports_color() else ""
end = "\033[0m" if colour and supports_color() else ""
# Print it
print(f"{start}[ERROR] {text}{end}", file=sys.stderr)
def pwarning(text: str = "", colour: bool = True):
"""
Writes text to srderr, as a warning string.
"""
# Get colours
start = "\033[93;1m" if colour and supports_color() else ""
end = "\033[0m" if colour and supports_color() else ""
# Print it
print(f"{start}[warning] {text}{end}", file=sys.stderr)
def pdebug(text: str = "", colour: bool = True):
"""
Writes text to stdout, as a debug string.
"""
# Skip if not debugging
if not debug: return
# Get colours
start = "\033[90m" if colour and supports_color() else ""
end = "\033[0m" if colour and supports_color() else ""
# Print it
print(f"{start}[debug] {text}{end}")
def cancel(text: str = "", code = 1, colour: bool = True) -> typing.NoReturn:
"""
Prints some error message to stderr, then quits the program by calling exit().
"""
perror(text, colour=colour)
exit(code)
def resolve_args(text: str, args: argparse.Namespace) -> str:
"""
Returns the same string, but with a couple of values replaced:
- `$RELEASE` with 'release' or 'debug' (depending on the '--dev' flag)
- `$OS` with a default identifier for the OS (see '$RUST_OS')
- `$RUST_OS` with a Rust-appropriate identifier for the OS (based on the '--os' flag)
- `$ARCH` with a default identifier for the architecture (see '$RUST_ARCH')
- `$RUST_ARCH` with a Rust-appropriate identifier for the architecture (based on the '--arch' flag)
- `$DOCKER_ARCH` with a Docker-appropriate identifier for the architecture (based on the '--arch' flag)
- `$JUICEFS_ARCH` with a JuiceFS-appropriate identifier for the architecture (based on the '--arch' flag)
- `$CWD` with the current working directory (based on what `os.getcwd()` reports)
"""
return text \
.replace("$RELEASE", "release" if not args.dev else "debug") \
.replace("$OS", args.os.to_rust()) \
.replace("$RUST_OS", args.os.to_rust()) \
.replace("$ARCH", args.arch.to_rust()) \
.replace("$RUST_ARCH", args.arch.to_rust()) \
.replace("$DOCKER_ARCH", args.arch.to_docker()) \
.replace("$JUICEFS_ARCH", args.arch.to_juicefs()) \
.replace("$REASONER", args.reasoner) \
.replace("$CWD", os.getcwd())
def cache_outdated(args: argparse.Namespace, file: str, is_src: bool) -> bool:
"""
Checks if the given source file/directory exists and needs
recompilation.
It needs recompilation if:
- It's a directory:
- Any of its source files (recursively) needs to be recompiled
- It's a file:
- The file's hash wasn't cached yet
- The hashes of the file & directory do not match
Additionally, the user will be warned if the source doesn't exist.
"""
# Get absolute version of the hash_cache
hash_cache = os.path.abspath(args.cache + ("/srcs" if is_src else "/dsts"))
# Match the type of the source file
if os.path.isfile(file):
# It's a file; check if we know its hash
hsrc = os.path.abspath(hash_cache + f"/{file}")
if hsrc[:len(hash_cache)] != hash_cache: raise ValueError(f"Hash source '{hsrc}' is not in the hash cache ({hash_cache}); please do not escape it")
if not os.path.exists(hsrc):
pdebug(f"Cached file '{file}' marked as outdated because it has no cache entry (missing '{hsrc}')")
return True
# Compute the hash of the file
try:
with open(file, "rb") as h:
src_hash = hashlib.md5()
while True:
data = h.read(65536)
if not data: break
src_hash.update(h.read())
except IOError as e:
pwarning(f"Failed to read source file '{file}' for hashing: {e} (assuming target needs to be rebuild)")
return True
# Compare it with that in the file
try:
with open(hsrc, "r") as h:
cache_hash = h.read()
except IOError as e:
pwarning(f"Failed to read hash cache file '{hsrc}': {e} (assuming target needs to be rebuild)")
return True
if src_hash.hexdigest() != cache_hash:
pdebug(f"Cached file '{file}' marked as outdated because its hash does not match that in the cache (cache file: '{hsrc}')")
return True
# Otherwise, no recompilation needed
return False
elif os.path.isdir(file):
# It's a dir; recurse
for nested_file in os.listdir(file):
if cache_outdated(args, os.path.join(file, nested_file), is_src):
pdebug(f"Cached directory '{file}' marked as outdated because one of its children ('{nested_file}') is outdated")
return True
return False
else:
# In this case, we're sure rebuilding needs to happen (since they may be as a result from a dependency)
pwarning(f"Cached file '{file}' is not a file or directory (is the sources/results list up-to-date?)")
return True
def update_cache(args: argparse.Namespace, file: str, is_src: bool):
"""
Updates the hash of the given source file in the given hash cache.
If the src is a file, then we simply compute the hash.
We recurse if it's a directory.
"""
# Get absolute version of the hash_cache
hash_cache = os.path.abspath(args.cache + ("/srcs" if is_src else "/dsts"))
# Match the type of the source file
if os.path.isfile(file):
# Attempt to compute the hash
try:
with open(file, "rb") as h:
src_hash = hashlib.md5()
while True:
data = h.read(65536)
if not data: break
src_hash.update(h.read())
except IOError as e:
pwarning(f"Failed to read source file '{file}' to compute hash: {e} (compilation will likely always happen until fixed)")
return
# Check if the target directory exists
hsrc = os.path.abspath(hash_cache + f"/{file}")
if hsrc[:len(hash_cache)] != hash_cache: raise ValueError(f"Hash source '{hsrc}' is not in the hash cache ({hash_cache}); please do not escape it")
os.makedirs(os.path.dirname(hsrc), exist_ok=True)
# Write the hash to it
try:
with open(hsrc, "w") as h:
h.write(src_hash.hexdigest())
except IOError as e:
pwarning(f"Failed to write hash cache to '{hsrc}': {e} (compilation will likely always happen until fixed)")
elif os.path.isdir(file):
# It's a dir; recurse
for nested_file in os.listdir(file):
update_cache(args, os.path.join(file, nested_file), is_src)
else:
# Warn the user
pwarning(f"Path '{file}' not found (are the source and destination lists up-to-date?)")
def flags_changed(args: argparse.Namespace, name: str) -> bool:
"""
Given the list of arguments, examines if the last time the given Target was compiled any relevant flags were different.
Flags examined are:
- `--dev`
- `--con`
"""
# Get absolute version of the hash_cache
flags_cache = os.path.abspath(args.cache + "/flags")
fsrc = flags_cache + f"/{name}"
# If the file does not exist, then we always go on
if not os.path.exists(fsrc):
pdebug(f"Flags file '{fsrc}' not found; assuming target is outdated")
return True
# Attempt to read the cache file
cached: dict[str, typing.Any] = {
"dev": None,
"con": None,
}
try:
with open(fsrc, "r") as h:
# Read line-by-line
l = 0
for line in h.readlines():
l += 1
# Attempt to split into flag/value pair
parts = [p.strip() for p in line.split("=")]
if len(parts) != 2:
pwarning(f"Line {l} in flags cache file '{fsrc}' is not a valid flag/value pair (skipping line)")
continue
(flag, value) = (parts[0].lower(), parts[1])
# See if we now this flag
if flag not in cached:
pwarning(f"Line {l} in flags cache file '{fsrc}' has unknown flag '{flag}' (ignoring)")
continue
# Split on the flag to parse further
if flag == "dev":
cached["dev"] = value.lower() == "true"
elif flag == "con":
cached["con"] = value.lower() == "true"
except IOError as e:
pwarning(f"Could not read flags cache file '{fsrc}': {e} (assuming target is outdated)")
return True
# Now compare
for flag in cached:
# Make sure we parsed this one
if cached[flag] is None:
pwarning(f"Missing flag '{flag}' in flags cache file '{fsrc}' (assuming target is outdated)")
return True
# Check if outdated
if getattr(args, flag) != cached[flag]:
pdebug(f"Flags in flags file '{fsrc}' do not match current flags; assuming target is outdated")
return True
# No outdating occurred
return False
def update_flags(args: argparse.Namespace, name: str):
"""
Updates the flag cache for the given Target to the current args dict.
"""
# Get absolute version of the hash_cache
flags_cache = os.path.abspath(args.cache + "/flags")
# Set the values
cached = {
"dev": args.dev,
"con": args.con,
}
# Write it
fsrc = flags_cache + f"/{name}"
os.makedirs(os.path.dirname(fsrc), exist_ok=True)
try:
with open(fsrc, "w") as h:
for (flag, value) in cached.items():
h.write(f"{flag}={value}\n")
except IOError as e:
pwarning(f"Could not write flags cache file '{fsrc}': {e} (recompilation will occur for this target until fixed)")
def deduce_toml_src_dirs(toml: str) -> typing.List[str] | None:
"""
Given a Cargo.toml file, attempts to deduce the (local) source crates.
Returns a list of the folders that are the crates on which the
Cargo.toml depends, including the one where it lives (i.e., its
directory-part).
"""
res = [ os.path.dirname(toml) ]
# Scan the lines in the file
try:
with open(toml, "r") as h:
# Read it all
text = h.read()
# Parse
parser = CargoTomlParser(text)
(res, errs) = parser.parse()
if len(errs) > 0:
for err in errs:
perror(f"{err}")
return None
# Else, resolve the given paths
for i in range(len(res)):
res[i] = os.path.join(os.path.dirname(toml), res[i])
# Add the cargo path
res.append(os.path.dirname(toml))
# Make all paths absolute
for i in range(len(res)):
res[i] = os.path.abspath(res[i])
# Done
return res
except IOError as e:
cancel(f"Could not read given Cargo.toml '{toml}': {e}")
def get_image_digest(path: str) -> str:
"""
Given a Docker image .tar file, attempts to read the digest and return it.
"""
# Open the tar file
archive = tarfile.open(path)
# Find the manifest file
digest = None
for file in archive.getmembers():
# Skip if not the proper file
if not file.isfile() or file.name != "manifest.json": continue
# Attempt to read it
f = archive.extractfile(file)
if f is None:
cancel(f"Failed to extract archive member '{file}' in '{path}'.")
smanifest = f.read().decode("utf-8")
f.close()
# Read as json
manifest = json.loads(smanifest)
# Extract the config blob (minus prefix)
config = manifest[0]["Config"]
if config[:13] != "blobs/sha256/": cancel("Found Config in manifest.json, but blob had incorrect start (corrupted image .tar?)")
config = config[13:]
# Done
digest = config
# Throw a failure
if digest is None:
cancel(f"Did not find image digest in {path} (is it a valid Docker image file?)")
# Done
archive.close()
return digest
##### HELPER CLASSES #####
class CargoTomlParser:
"""
Parses a given file as if it were a Cargo.toml file.
This is definitely not a TOML compliant-parser, though, not least of
which because it only extracts stuff under the 'dependencies' toplevel
section.
"""
# Baseclasses
class Symbol(abc.ABC):
"""
Baseclass for all the symbols.
"""
is_term : bool
start : typing.Tuple[int, int]
end : typing.Tuple[int, int]
def __init__(self, is_term: bool, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the Symbol.
# Arguments
- `is_term`: Whether this Symbol is a terminal or not (it's a nonterminal).
- `start`: The (inclusive) start position of this symbol in the text.
- `stop`: The (inclusive) stop position of this symbol in the text.
"""
self.is_term = is_term
self.start = start
self.end = end
def __str__(self) -> str:
return "Symbol"
class Terminal(Symbol):
"""
Baseclass for all the parser tokens.
"""
def __init__(self, start: typing.Tuple[int, int], end: typing.Tuple[int, int]):
"""
Constructor for the Terminal.
# Arguments
- `start`: The (inclusive) start position of this symbol in the text.
- `end`: The (inclusive) stop position of this symbol in the text.
"""
CargoTomlParser.Symbol.__init__(self, True, start, end)
def __str__(self) -> str:
return "Terminal"
class Nonterminal(Symbol):
"""
Baseclass for all the parser nonterminals.
"""
def __init__(self, start: typing.Tuple[int, int], end: typing.Tuple[int, int]):
"""
Constructor for the Nonterminal.
# Arguments
- `start`: The (inclusive) start position of this symbol in the text.
- `end`: The (inclusive) stop position of this symbol in the text.
"""
CargoTomlParser.Symbol.__init__(self, False, start, end)
def __str__(self) -> str:
return "NonTerminal"
# Terminals
class Identifier(Terminal):
"""
Helper class for the CargoTomlParser which represents a string token.
"""
value : str
def __init__(self, value: str, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the String
Arguments
- `value`: The value of the String.
- `start`: The start position (as (row, col), inclusive) of the token.
- `end`: The end position (as (row, col), inclusive) of the token.
"""
CargoTomlParser.Terminal.__init__(self, start, end)
self.value = value
def __str__(self) -> str:
return f"Identifier({self.value})"
class String(Terminal):
"""
Helper class for the CargoTomlParser which represents a string value.
"""
value : str
def __init__(self, value: str, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the String
Arguments
- `value`: The value of the String.
- `start`: The start position (as (row, col), inclusive) of the token.
- `end`: The end position (as (row, col), inclusive) of the token.
"""
CargoTomlParser.Terminal.__init__(self, start, end)
self.value = value
def __str__(self) -> str:
return f"String({self.value})"
class Boolean(Terminal):
"""
Helper class for the CargoTomlParser which represents a boolean value.
"""
value : bool
def __init__(self, value: bool, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the Boolean
Arguments
- `value`: The value of the Boolean.
- `start`: The start position (as (row, col), inclusive) of the token.
- `end`: The end position (as (row, col), inclusive) of the token.
"""
CargoTomlParser.Terminal.__init__(self, start, end)
self.value = value
def __str__(self) -> str:
return f"Boolean({self.value})"
class Equals(Terminal):
"""
Helper class for the CargoTomlParser which represents an equals sign.
"""
def __init__(self, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the Equals
Arguments
- `start`: The start position (as (row, col), inclusive) of the token.
- `end`: The end position (as (row, col), inclusive) of the token.
"""
CargoTomlParser.Terminal.__init__(self, start, end)
def __str__(self) -> str:
return "Equals"
class Comma(Terminal):
"""
Helper class for the CargoTomlParser which represents a comma.
"""
def __init__(self, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the Comma
Arguments
- `start`: The start position (as (row, col), inclusive) of the token.
- `end`: The end position (as (row, col), inclusive) of the token.
"""
CargoTomlParser.Terminal.__init__(self, start, end)
def __str__(self) -> str:
return "Comma"
class LCurly(Terminal):
"""
Helper class for the CargoTomlParser which represents a left curly bracket.
"""
def __init__(self, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the LCurly
Arguments
- `start`: The start position (as (row, col), inclusive) of the token.
- `end`: The end position (as (row, col), inclusive) of the token.
"""
CargoTomlParser.Terminal.__init__(self, start, end)
def __str__(self) -> str:
return "LCurly"
class RCurly(Terminal):
"""
Helper class for the CargoTomlParser which represents a right curly bracket.
"""
def __init__(self, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the RCurly
Arguments
- `start`: The start position (as (row, col), inclusive) of the token.
- `end`: The end position (as (row, col), inclusive) of the token.
"""
CargoTomlParser.Terminal.__init__(self, start, end)
def __str__(self) -> str:
return "RCurly"
class LSquare(Terminal):
"""
Helper class for the CargoTomlParser which represents a left square bracket.
"""
def __init__(self, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the LSquare
Arguments
- `start`: The start position (as (row, col), inclusive) of the token.
- `end`: The end position (as (row, col), inclusive) of the token.
"""
CargoTomlParser.Terminal.__init__(self, start, end)
def __str__(self) -> str:
return "LSquare"
class RSquare(Terminal):
"""
Helper class for the CargoTomlParser which represents a right square bracket.
"""
def __init__(self, start: typing.Tuple[int, int], end: typing.Tuple[int, int]) -> None:
"""
Constructor for the RSquare
Arguments
- `start`: The start position (as (row, col), inclusive) of the token.
- `end`: The end position (as (row, col), inclusive) of the token.
"""
CargoTomlParser.Terminal.__init__(self, start, end)
def __str__(self) -> str:
return "RSquare"
# Nonterminals
class Section(Nonterminal):
"""
Represents a section in the TOML file.
"""
header : CargoTomlParser.SectionHeader
pairs : typing.List[CargoTomlParser.KeyValuePair]
def __init__(self, header: CargoTomlParser.SectionHeader, pairs: typing.List[CargoTomlParser.KeyValuePair], start: typing.Tuple[int, int], end: typing.Tuple[int, int]):
"""
Constructor for the SectionHeader nonterminal.
# Arguments
- `header`: The header of the section.
- `pairs`: The key/value pairs in this section.
- `start`: The (inclusive) start position of this token.
- `end`: The (inclusive) end position of this token.
"""
CargoTomlParser.Nonterminal.__init__(self, start, end)
self.header = header
self.pairs = pairs
def __str__(self) -> str:
return f"Section({self.header}, ...)"
class SectionHeader(Nonterminal):
"""
Represents a section header.
"""
name : str
def __init__(self, name: str, start: typing.Tuple[int, int], end: typing.Tuple[int, int]):
"""
Constructor for the SectionHeader nonterminal.
# Arguments
- `name`: The name of the section.
- `start`: The (inclusive) start position of this token.
- `end`: The (inclusive) end position of this token.
"""
CargoTomlParser.Nonterminal.__init__(self, start, end)
self.name = name
def __str__(self) -> str:
return f"SectionHeader({self.name})"
class KeyValuePair(Nonterminal):
"""
Represents a Key/Value pair in the stack.
"""
key : CargoTomlParser.Identifier
value : CargoTomlParser.Value
def __init__(self, key: CargoTomlParser.Identifier, value: CargoTomlParser.Value, start: typing.Tuple[int, int], end: typing.Tuple[int, int]):
"""
Constructor for the SectionHeader nonterminal.
# Arguments
- `key`: The key of the pair (which is an Identifier).
- `value`: The value of the pair (which is a Value).
- `start`: The (inclusive) start position of this token.
- `end`: The (inclusive) end position of this token.
"""
CargoTomlParser.Nonterminal.__init__(self, start, end)
self.key = key
self.value = value
def __str__(self) -> str:
return f"KeyValuePair({self.key}, {self.value})"
class Value(Nonterminal):
"""
Abstracts away over the specific value.
"""
value : CargoTomlParser.String | CargoTomlParser.Boolean | CargoTomlParser.List | CargoTomlParser.Dict
def __init__(self, value: CargoTomlParser.String | CargoTomlParser.Boolean | CargoTomlParser.List | CargoTomlParser.Dict, start: typing.Tuple[int, int], end: typing.Tuple[int, int]):
"""
Constructor for the SectionHeader nonterminal.
# Arguments
- `value`: The value of the Value.
- `start`: The (inclusive) start position of this token.
- `end`: The (inclusive) end position of this token.
"""
CargoTomlParser.Nonterminal.__init__(self, start, end)
self.value = value
def __str__(self) -> str:
return f"Value({self.value})"
class Dict(Nonterminal):
"""
Represents a dictionary of key/value pairs.
"""
pairs : typing.List[CargoTomlParser.KeyValuePair]
def __init__(self, pairs: typing.List[CargoTomlParser.KeyValuePair], start: typing.Tuple[int, int], end: typing.Tuple[int, int]):
"""
Constructor for the SectionHeader nonterminal.
# Arguments
- `pairs`: The list of KeyValuePairs in this dictionary.
- `start`: The (inclusive) start position of this token.
- `end`: The (inclusive) end position of this token.
"""
CargoTomlParser.Nonterminal.__init__(self, start, end)
self.pairs = pairs
def __str__(self) -> str:
res = "Dict({\n"
for p in self.pairs:
res += f" {p},\n"
return res + "})"
class List(Nonterminal):
"""
Represents a list of values.
"""
values : typing.List[CargoTomlParser.Value]
def __init__(self, values: typing.List[CargoTomlParser.Value], start: typing.Tuple[int, int], end: typing.Tuple[int, int]):
"""
Constructor for the SectionHeader nonterminal.
# Arguments
- `values`: The list of Values in this list.
- `start`: The (inclusive) start position of this token.
- `end`: The (inclusive) end position of this token.
"""
CargoTomlParser.Nonterminal.__init__(self, start, end)
self.values = values
def __str__(self) -> str:
res = "List(["
for i, v in enumerate(self.values):
if i > 0: res += ", "
res += f"{v}"
return res + "])"
_lines : typing.List[str]
_col : int
_line : int
def __init__(self, raw: str) -> None:
"""
Constructor for the CargoTomlParser.
Arguments:
- `raw`: The raw text to parse as a Cargo.toml file.
"""
# Initialize stuff
self._lines = raw.split('\n')
self._col = 0