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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
|
#!/usr/bin/env python3
import argparse
from contextlib import contextmanager, nullcontext
import fcntl
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import urlopen
CONTAINER_UID = 100000
# Third-party mirror. Its tags describe available build images, not the current
# official SailfishOS release or installed SDK target.
CONTAINER_IMAGE = "coderus/sailfishos-platform-sdk"
HELPER_VERSION = "2.0.0"
LIVE_RELEASE = "live"
DEFAULT_LOCAL_SDK = Path("/srv/mer/sdks/sfossdk/sdk-chroot")
LOCAL_SDK_BUILD_ENGINE_IMAGE_ENV = "SAILFISH_SDK_BUILD_ENGINE_IMAGE"
STATE_DIRNAME = "build-sailfishos-skill"
MANIFEST_NAME = "build-sailfishos-skill-manifest.txt"
BUILD_LOG_NAME = "build-sailfishos-skill-last.log"
BUILD_METADATA_NAME = "build-sailfishos-skill-last-build.json"
BUILD_LOCK_NAME = "build-sailfishos-skill.lock"
LOCAL_RPMS_STAGING_NAME = "local-rpms"
DEFAULT_PERMISSION_FALLBACK = "error"
LOCAL_RPM_EXCLUDED_MARKERS = (
"-debuginfo-",
"-debugsource-",
"-tests-",
"-examples-",
"-doc-",
"-ts-devel-",
)
ROOT_PATTERNS = (
"Makefile",
".qmake.stash",
"*.o",
"*.a",
"*.so",
"*.prl",
"moc_*.cpp",
"moc_*.o",
"qrc_*.cpp",
"qrc_*.o",
"ui_*.h",
"CMakeCache.txt",
"cmake_install.cmake",
"compile_commands.json",
"build.ninja",
"rules.ninja",
"install_manifest.txt",
)
RECURSIVE_PATTERNS = (
"**/Makefile",
"**/.qmake.stash",
"**/moc_*.cpp",
"**/moc_*.o",
"**/qrc_*.cpp",
"**/qrc_*.o",
"**/*.o",
"**/*.a",
"**/*.so",
"**/*.prl",
"**/ui_*.h",
"**/CMakeCache.txt",
"**/cmake_install.cmake",
"**/compile_commands.json",
"**/build.ninja",
"**/rules.ninja",
"**/install_manifest.txt",
"**/CMakeFiles",
)
ROOT_DIRS = (
"installroot",
)
LOCAL_TARGET_ARCHES = ("aarch64", "armv7hl", "i486")
@dataclass(frozen=True)
class LocalSdkTarget:
arch: str
target: str
release: str
version_id: str
flavour: str
@dataclass(frozen=True)
class LocalSdkBuild:
arch: str
target: str
@dataclass(frozen=True)
class BuildContext:
backend: str
release: str
image: str | None
image_id: str | None
local_sdk: str | None
def log(message: str) -> None:
print(message, file=sys.stderr)
def run(cmd: list[str], cwd: Path | None = None, capture_output: bool = False) -> subprocess.CompletedProcess[str]:
return subprocess.run(
cmd,
cwd=str(cwd) if cwd else None,
check=True,
text=True,
capture_output=capture_output,
)
def require_tool(name: str) -> None:
if shutil.which(name):
return
raise SystemExit(f"Required tool not found: {name}")
def project_state_dir(project_dir: Path) -> Path:
return project_dir / ".mb2" / STATE_DIRNAME
def manifest_path(project_dir: Path) -> Path:
return project_dir / ".mb2" / MANIFEST_NAME
def build_log_path(project_dir: Path) -> Path:
return project_dir / ".mb2" / BUILD_LOG_NAME
def build_metadata_path(project_dir: Path) -> Path:
return project_dir / ".mb2" / BUILD_METADATA_NAME
def build_lock_path(project_dir: Path) -> Path:
return project_dir / ".mb2" / BUILD_LOCK_NAME
def default_artifacts_dir(project_dir: Path) -> Path:
return project_dir / "RPMS"
def staging_rpms_dir(project_dir: Path) -> Path:
return project_state_dir(project_dir) / "rpms"
def local_rpms_staging_dir(project_dir: Path) -> Path:
return project_state_dir(project_dir) / LOCAL_RPMS_STAGING_NAME
def write_json_atomic(path: Path, payload: object) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.{os.getpid()}.{time.time_ns()}.tmp")
try:
temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
os.replace(temporary, path)
finally:
try:
temporary.unlink()
except FileNotFoundError:
pass
@contextmanager
def project_build_lock(project_dir: Path):
path = build_lock_path(project_dir)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a+", encoding="utf-8") as lock_file:
try:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as exc:
lock_file.seek(0)
owner = lock_file.read().strip()
detail = f" (owner {owner})" if owner else ""
raise SystemExit(f"Another SailfishOS build is already active for {project_dir}{detail}.") from exc
lock_file.seek(0)
lock_file.truncate()
lock_file.write(f"pid={os.getpid()} started_utc={datetime.now(timezone.utc).isoformat()}\n")
lock_file.flush()
try:
yield
finally:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
def has_spec_files(project_dir: Path) -> bool:
rpm_dir = project_dir / "rpm"
return rpm_dir.is_dir() and any(rpm_dir.glob("*.spec"))
def parse_version(value: str) -> tuple[int, ...]:
return tuple(int(part) for part in value.split("."))
def is_version_release_tag(value: str) -> bool:
return bool(re.fullmatch(r"\d+(?:\.\d+){3}", value))
def fetch_coderus_mirror_tags(prefix: str | None = None) -> list[str]:
name_filter = quote(prefix) if prefix else ""
matches: list[str] = []
next_url = (
"https://registry.hub.docker.com/v2/repositories/"
f"{CONTAINER_IMAGE}/tags?page_size=100"
f"{f'&name={name_filter}' if name_filter else ''}"
)
while next_url:
with urlopen(next_url, timeout=10) as response:
payload = json.load(response)
for result in payload.get("results", []):
name = result.get("name", "").strip()
if prefix:
if not (name == prefix or name.startswith(f"{prefix}.")):
continue
if is_version_release_tag(name):
matches.append(name)
next_url = payload.get("next")
return sorted(dict.fromkeys(matches), key=parse_version)
def latest_coderus_mirror_tag() -> str:
matches = fetch_coderus_mirror_tags()
if not matches:
raise SystemExit(
f"Could not determine the newest available Docker image tag from {CONTAINER_IMAGE}."
)
return matches[-1]
def normalize_release_tag(release: str) -> str:
if release.lower() == LIVE_RELEASE:
return LIVE_RELEASE
if release == "latest":
try:
resolved = latest_coderus_mirror_tag()
except (HTTPError, URLError, TimeoutError, OSError, ValueError, json.JSONDecodeError) as exc:
raise SystemExit(f"Could not resolve Docker image tag 'latest' from {CONTAINER_IMAGE}") from exc
log(f"Resolved newest available {CONTAINER_IMAGE} image tag to {resolved}")
return resolved
if not re.fullmatch(r"\d+(?:\.\d+){2,3}", release):
return release
if release.count(".") >= 3:
return release
try:
matches = fetch_coderus_mirror_tags(release)
except (HTTPError, URLError, TimeoutError, OSError, ValueError, json.JSONDecodeError):
return release
if not matches:
return release
if release in matches:
return release
resolved = max(matches, key=parse_version)
log(f"Resolved release shorthand {release} to {CONTAINER_IMAGE} image tag {resolved}")
return resolved
def infer_release_from_workflows(project_dir: Path) -> str | None:
workflows_dir = project_dir / ".github" / "workflows"
if not workflows_dir.is_dir():
return None
regexes = (
re.compile(r"^\s*RELEASE:\s*([^\s#]+)\s*$"),
re.compile(rf"{re.escape(CONTAINER_IMAGE)}:([^\s'\"#]+)"),
)
for workflow in sorted(workflows_dir.glob("*.y*ml")):
try:
text = workflow.read_text(encoding="utf-8")
except OSError:
continue
for line in text.splitlines():
for regex in regexes:
match = regex.search(line)
if match:
return match.group(1).strip()
return None
def resolve_release(project_dirs: Iterable[Path], explicit_release: str | None) -> str:
if explicit_release:
return normalize_release_tag(explicit_release)
env_release = os.environ.get("SAILFISHOS_RELEASE")
if env_release:
return normalize_release_tag(env_release)
seen: set[Path] = set()
for project_dir in project_dirs:
if project_dir in seen:
continue
seen.add(project_dir)
inferred = infer_release_from_workflows(project_dir)
if inferred:
return normalize_release_tag(inferred)
try:
resolved = latest_coderus_mirror_tag()
except (HTTPError, URLError, TimeoutError, OSError, ValueError, json.JSONDecodeError) as exc:
raise SystemExit(
"Could not determine a build release from arguments, environment, workflows, "
f"or available {CONTAINER_IMAGE} image tags."
) from exc
log(
f"No build release specified; using newest available {CONTAINER_IMAGE} "
f"image tag {resolved}. This does not identify the current SailfishOS release."
)
return resolved
def parse_last_arch(project_dir: Path) -> str | None:
target_file = project_dir / ".mb2" / "target"
if not target_file.is_file():
return None
target = target_file.read_text(encoding="utf-8").strip()
if not target:
return None
if target.startswith("SailfishOS-"):
arch = target.rsplit("-", 1)[-1]
if arch.endswith(".default"):
arch = arch[: -len(".default")]
return arch
prefix = target.split(".", 1)[0].strip()
return prefix or None
def pull_image(release: str) -> None:
image = f"{CONTAINER_IMAGE}:{release}"
log(f"Pulling {image}")
run(["docker", "pull", image])
def docker_image_exists(image: str) -> bool:
result = subprocess.run(
["docker", "image", "inspect", image],
check=False,
text=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
return result.returncode == 0
def docker_image_id(image: str) -> str | None:
try:
result = run(
["docker", "image", "inspect", "--format", "{{.Id}}", image],
capture_output=True,
)
except subprocess.CalledProcessError:
return None
return result.stdout.strip() or None
def ensure_image(release: str, pull_policy: str) -> tuple[str, bool]:
image = f"{CONTAINER_IMAGE}:{release}"
exists = docker_image_exists(image)
should_pull = pull_policy == "always" or (pull_policy == "missing" and not exists)
if should_pull:
pull_image(release)
return image, True
if not exists:
raise SystemExit(
f"Docker image {image} is not available locally and pull policy is '{pull_policy}'."
)
return image, False
def list_supported_arches(release: str) -> list[str]:
image = f"{CONTAINER_IMAGE}:{release}"
result = run(
[
"docker",
"run",
"--rm",
image,
"bash",
"-lc",
"sb2-config -l",
],
capture_output=True,
)
arches: list[str] = []
seen: set[str] = set()
prefix = f"SailfishOS-{release}-"
for line in result.stdout.splitlines():
line = line.strip()
if line.startswith(prefix):
arch = line[len(prefix) :]
if arch.endswith(".default") or arch in seen:
continue
arches.append(arch)
seen.add(arch)
if not arches:
raise SystemExit(f"No supported architectures found in {image}")
return arches
def resolve_arches(requested_arches: list[str], build_all: bool, supported_arches: list[str], project_dir: Path) -> list[str]:
if build_all:
return supported_arches
if requested_arches:
invalid = [arch for arch in requested_arches if arch not in supported_arches]
if invalid:
raise SystemExit(
f"Unsupported architectures: {', '.join(invalid)}. Supported: {', '.join(supported_arches)}"
)
return requested_arches
last_arch = parse_last_arch(project_dir)
if last_arch and last_arch in supported_arches:
return [last_arch]
raise SystemExit(
"No architecture was specified and .mb2/target did not contain a supported one. "
f"Pass --arch or --all. Supported: {', '.join(supported_arches)}"
)
def resolve_local_sdk_arches(requested_arches: list[str], build_all: bool, project_dir: Path) -> list[str]:
if build_all:
raise SystemExit("Local SDK builds use installed SDK targets; pass one or more explicit --arch values.")
if requested_arches:
return requested_arches
last_arch = parse_last_arch(project_dir)
if last_arch:
return [last_arch]
raise SystemExit(
"No architecture was specified and .mb2/target did not contain a previous target. "
"Pass --arch for local SDK builds."
)
def spec_names(project_dir: Path) -> set[str]:
names: set[str] = set()
for spec in sorted((project_dir / "rpm").glob("*.spec")):
try:
text = spec.read_text(encoding="utf-8")
except OSError:
continue
for line in text.splitlines():
match = re.match(r"^\s*Name:\s*(\S+)\s*$", line)
if match:
names.add(match.group(1))
break
return names
def pro_targets(project_dir: Path) -> set[str]:
targets: set[str] = set()
for pro in sorted(project_dir.glob("*.pro")):
try:
text = pro.read_text(encoding="utf-8")
except OSError:
continue
for line in text.splitlines():
match = re.match(r"^\s*TARGET\s*=\s*([^\s#]+)\s*$", line)
if match and "$" not in match.group(1):
targets.add(match.group(1))
break
return targets
def generated_candidate_paths(project_dir: Path) -> set[Path]:
tracked_paths = tracked_git_paths(project_dir)
paths: set[Path] = set()
for dirname in ROOT_DIRS:
path = project_dir / dirname
if path.exists():
paths.add(path)
for pattern in ROOT_PATTERNS:
paths.update(path for path in project_dir.glob(pattern) if path.exists())
for pattern in RECURSIVE_PATTERNS:
paths.update(
path
for path in project_dir.glob(pattern)
if path.exists() and ".git" not in path.parts and ".mb2" not in path.parts
)
for qm in (project_dir / "translations").glob("*.qm") if (project_dir / "translations").is_dir() else []:
if qm.exists():
paths.add(qm)
for name in sorted(spec_names(project_dir) | pro_targets(project_dir)):
candidate = project_dir / name
if candidate.exists():
paths.add(candidate)
state_dir = project_state_dir(project_dir)
if state_dir.exists():
paths.discard(state_dir)
return {
path
for path in paths
if path.exists() and path.resolve() not in tracked_paths
}
def tracked_git_paths(project_dir: Path) -> set[Path]:
try:
repo_roots = git_worktree_roots(project_dir)
except OSError:
return set()
tracked: set[Path] = set()
for root in repo_roots:
try:
result = run(
["git", "-C", str(root), "ls-files", "-z"],
capture_output=True,
)
except (subprocess.CalledProcessError, FileNotFoundError):
continue
for rel_path in result.stdout.split("\0"):
if not rel_path:
continue
tracked.add((root / rel_path).resolve())
return tracked
def git_worktree_roots(project_dir: Path) -> list[Path]:
roots = {project_dir.resolve()}
for git_marker in project_dir.rglob(".git"):
if ".mb2" in git_marker.parts:
continue
repo_root = git_marker.parent.resolve()
roots.add(repo_root)
return sorted(roots)
def load_manifest(project_dir: Path) -> list[Path]:
path = manifest_path(project_dir)
if not path.is_file():
return []
result: list[Path] = []
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line:
continue
candidate = (project_dir / line).resolve()
try:
candidate.relative_to(project_dir.resolve())
except ValueError:
continue
if candidate.exists():
result.append(candidate)
return result
def write_manifest(project_dir: Path, paths: Iterable[Path]) -> None:
manifest = manifest_path(project_dir)
manifest.parent.mkdir(parents=True, exist_ok=True)
rel_paths = []
root = project_dir.resolve()
for path in sorted({p.resolve() for p in paths if p.exists()}):
try:
rel_paths.append(str(path.relative_to(root)))
except ValueError:
continue
manifest.write_text("\n".join(rel_paths) + ("\n" if rel_paths else ""), encoding="utf-8")
def write_build_metadata(
project_dir: Path,
*,
context: BuildContext,
builds: list[dict[str, object]],
debug_build: bool,
artifacts_dir: Path,
status: str,
started_at: datetime,
failure_class: str | None = None,
failure_message: str | None = None,
) -> None:
metadata_file = build_metadata_path(project_dir)
finished_at = datetime.now(timezone.utc)
serialized_builds: list[dict[str, object]] = []
for build in builds:
serialized = dict(build)
serialized["rpms"] = [str(path) for path in build.get("rpms", [])]
serialized_builds.append(serialized)
rpms = [path for build in serialized_builds for path in build.get("rpms", [])]
payload = {
"schema_version": 2,
"helper_version": HELPER_VERSION,
"started_utc": started_at.isoformat(),
"updated_utc": finished_at.isoformat(),
"finished_utc": None if status == "running" else finished_at.isoformat(),
"duration_seconds": round((finished_at - started_at).total_seconds(), 3),
"backend": context.backend,
"release": context.release,
"image": context.image,
"image_id": context.image_id,
"local_sdk": context.local_sdk,
"debug": debug_build,
"status": status,
"failure_class": failure_class,
"failure_message": failure_message,
"artifacts_dir": str(artifacts_dir),
"build_log": str(build_log_path(project_dir)),
"builds": serialized_builds,
"rpms": rpms,
"rpmlint": rpmlint_summary(build_log_path(project_dir)),
}
write_json_atomic(metadata_file, payload)
def write_target_marker(project_dir: Path, arch: str) -> None:
mb2_dir = project_dir / ".mb2"
mb2_dir.mkdir(parents=True, exist_ok=True)
(mb2_dir / "target").write_text(f"{arch}.{STATE_DIRNAME}\n", encoding="utf-8")
def remove_path(path: Path) -> None:
if not path.exists():
return
if path.is_dir() and not path.is_symlink():
shutil.rmtree(path)
else:
path.unlink()
def cleanup_generated_artifacts(project_dir: Path, reason: str) -> list[Path]:
manifest_paths = load_manifest(project_dir)
cleanup_paths = set(manifest_paths) | generated_candidate_paths(project_dir)
removed: list[Path] = []
for path in sorted(cleanup_paths):
if project_state_dir(project_dir) in path.parents or path == project_state_dir(project_dir):
continue
if path == manifest_path(project_dir):
continue
if path.exists():
remove_path(path)
removed.append(path)
log(f"{reason}; removed {len(removed)} stale in-place artifacts")
return removed
def cleanup_in_place_artifacts(project_dir: Path, previous_arch: str, next_arch: str) -> list[Path]:
return cleanup_generated_artifacts(
project_dir,
f"Switched architecture from {previous_arch} to {next_arch}",
)
def ensure_container_write_access(project_dir: Path, permission_fallback: str) -> None:
current_uid = os.getuid()
if shutil.which("setfacl"):
log(
f"Granting read ACLs under {project_dir} and scoped output write ACLs to container uid {CONTAINER_UID}"
)
(project_dir / ".mb2").mkdir(parents=True, exist_ok=True)
run(
[
"find",
str(project_dir),
"-type",
"d",
"-uid",
str(current_uid),
"-exec",
"setfacl",
"-m",
f"u:{CONTAINER_UID}:rX",
"{}",
"+",
]
)
run(
[
"find",
str(project_dir),
"-type",
"f",
"-uid",
str(current_uid),
"-exec",
"setfacl",
"-m",
f"u:{CONTAINER_UID}:rX",
"{}",
"+",
]
)
writable_paths = {project_dir, project_dir / ".mb2"}
translations = project_dir / "translations"
if translations.is_dir():
writable_paths.add(translations)
writable_paths.update(generated_candidate_paths(project_dir))
for path in sorted(writable_paths):
if not path.exists():
continue
run(["setfacl", "-m", f"u:{CONTAINER_UID}:rwX", str(path)])
if path.is_dir():
run(["setfacl", "-m", f"d:u:{CONTAINER_UID}:rwX", str(path)])
return
if permission_fallback == "chmod":
log("setfacl unavailable; falling back to chmod -R a+rwX")
run(["chmod", "-R", "a+rwX", str(project_dir)])
return
raise SystemExit(
"setfacl is unavailable, so the Docker container may not be able to write in place. "
"Install acl utilities or rerun with --permission-fallback chmod."
)
def usable_local_rpms(directory: Path) -> list[Path]:
if not directory.is_dir():
raise SystemExit(f"Local RPM directory not found: {directory}")
return [
rpm
for rpm in sorted(directory.glob("*.rpm"))
if not any(marker in rpm.name for marker in LOCAL_RPM_EXCLUDED_MARKERS)
]
def validate_local_rpm_dirs(directories: list[Path]) -> dict[Path, list[Path]]:
selected: dict[Path, list[Path]] = {}
for directory in directories:
rpms = usable_local_rpms(directory)
if not rpms:
raise SystemExit(f"No installable RPMs found in local RPM directory: {directory}")
selected[directory] = rpms
return selected
@contextmanager
def stage_local_sdk_rpms(project_dir: Path, selected: dict[Path, list[Path]]):
staging_root = local_rpms_staging_dir(project_dir)
if staging_root.exists():
shutil.rmtree(staging_root)
staged_dirs: list[Path] = []
try:
for index, rpms in enumerate(selected.values()):
destination = staging_root / str(index)
destination.mkdir(parents=True, exist_ok=True)
for rpm in rpms:
shutil.copy2(rpm, destination / rpm.name)
staged_dirs.append(destination)
yield staged_dirs
finally:
if staging_root.exists():
shutil.rmtree(staging_root)
def rpmlint_summary(log_file: Path) -> dict[str, int]:
summary = {"errors": 0, "warnings": 0}
if not log_file.is_file():
return summary
try:
text = log_file.read_text(encoding="utf-8", errors="replace")
except OSError:
return summary
final = re.findall(r"(?im);\s*(\d+)\s+errors?,\s*(\d+)\s+warnings?\.?$", text)
if final:
summary["errors"], summary["warnings"] = map(int, final[-1])
return summary
summary["errors"] = len(re.findall(r"(?m)^\S.*:\s+E:\s+", text))
summary["warnings"] = len(re.findall(r"(?m)^\S.*:\s+W:\s+", text))
return summary
def classify_failure(error: BaseException, log_file: Path | None = None) -> str:
text = str(error)
if log_file and log_file.is_file():
try:
text += "\n" + log_file.read_text(encoding="utf-8", errors="replace")[-20000:]
except OSError:
pass
lowered = text.lower()
if "failed build dependencies" in lowered or "is needed by" in lowered:
return "missing-build-requires"
if "no basic authentication credentials" in lowered or "repository" in lowered and "not found" in lowered:
return "repository"
if "signature" in lowered or "gpg" in lowered or "unsigned rpm" in lowered:
return "package-trust"
if "permission denied" in lowered or "operation not permitted" in lowered:
return "permission"
if "docker image" in lowered or "manifest unknown" in lowered or "pull access denied" in lowered:
return "image"
if isinstance(error, subprocess.TimeoutExpired):
return "timeout"
return "build"
def parse_missing_build_requires(log_text: str) -> list[str]:
missing: list[str] = []
capture = False
for line in log_text.splitlines():
if line.strip() == "error: Failed build dependencies:":
capture = True
continue
if not capture:
continue
if line.startswith("\t") or line.startswith(" "):
requirement = line.strip()
if " is needed by " in requirement:
requirement = requirement.split(" is needed by ", 1)[0].strip()
if requirement:
missing.append(requirement)
continue
if missing and line.strip():
break
return sorted(dict.fromkeys(missing))
def extract_zypper_names(output: str) -> list[str]:
names: list[str] = []
for line in output.splitlines():
if "|" not in line or line.lstrip().startswith("--+"):
continue
parts = [part.strip() for part in line.split("|")]
if len(parts) < 3:
continue
name = parts[1]
if name and name not in {"Name", "S"}:
names.append(name)
return sorted(dict.fromkeys(names))
def diagnose_missing_dependencies(project_dir: Path, release: str, arch: str) -> None:
log_file = build_log_path(project_dir)
if not log_file.is_file():
return
missing = parse_missing_build_requires(log_file.read_text(encoding="utf-8"))
if not missing:
return
image = f"{CONTAINER_IMAGE}:{release}"
target = f"SailfishOS-{release}-{arch}"
log("Dependency diagnostics from the target SDK:")
for requirement in missing:
if requirement.startswith("pkgconfig("):
query = (
f"sb2 -t {shlex.quote(target)} -m sdk-install -R "
f"zypper search --provides --match-exact {shlex.quote(requirement)}"
)
else:
query = (
f"sb2 -t {shlex.quote(target)} -m sdk-install -R "
f"zypper se -s {shlex.quote(requirement)}"
)
try:
result = run(
["docker", "run", "--rm", image, "bash", "-lc", query],
capture_output=True,
)
except subprocess.CalledProcessError:
log(f"- {requirement}: diagnostic lookup failed")
continue
names = extract_zypper_names(result.stdout)
if names:
log(f"- {requirement}: available as {', '.join(names)}")
else:
log(f"- {requirement}: not available in {target}")
def verify_expected_rpms(rpms: list[Path], debug_build: bool) -> None:
if not rpms:
raise SystemExit("Build completed but no RPMs were captured")
if debug_build:
names = {rpm.name for rpm in rpms}
if not any("-debuginfo-" in name for name in names):
raise SystemExit("Debug build completed but no -debuginfo RPM was produced")
if not any("-debugsource-" in name for name in names):
raise SystemExit("Debug build completed but no -debugsource RPM was produced")
def variant_destination_dir(base_dir: Path, release: str, arch: str, debug_build: bool) -> Path:
return base_dir / release / arch / ("debug" if debug_build else "release")
def host_user() -> str:
return os.environ.get("USER") or os.environ.get("LOGNAME") or Path.home().name
def local_sdk_build_engine_image(user: str) -> str:
return os.environ.get(LOCAL_SDK_BUILD_ENGINE_IMAGE_ENV, f"sailfish-sdk-build-engine:{user}")
def local_sdk_project_mount_root(project_dir: Path) -> Path:
home = Path.home().resolve()
resolved = project_dir.resolve()
try:
resolved.relative_to(home)
except ValueError as exc:
raise SystemExit(
"Local SDK builds currently require the project to live under the current user's home "
"directory so the installed SDK chroot can see the same path."
) from exc
return home
def local_sdk_mount_root(local_sdk: Path) -> Path:
resolved = local_sdk.resolve(strict=False)
srv_mer = Path("/srv/mer")
try:
resolved.relative_to(srv_mer)
except ValueError:
return resolved.parent
return srv_mer
def local_sdk_targets_dir(local_sdk: Path) -> Path:
return local_sdk_mount_root(local_sdk) / "targets"
def canonical_local_target_name(name: str) -> str:
while name.endswith(".default"):
name = name[: -len(".default")]
return name
def split_local_target_arch(target: str) -> tuple[str, str] | None:
for arch in LOCAL_TARGET_ARCHES:
if target == arch:
return arch, ""
if target.startswith(f"{arch}-"):
return arch, target[len(arch) + 1 :]
return None
def read_key_value_file(path: Path) -> dict[str, str]:
if not path.is_file():
return {}
metadata: dict[str, str] = {}
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("[") or line.startswith("#"):
continue
if "=" not in line:
continue
key, value = line.split("=", 1)
metadata[key.strip()] = value.strip().strip('"')
return metadata
def target_metadata(target_dir: Path) -> dict[str, str]:
sailfish = read_key_value_file(target_dir / "etc" / "sailfish-release")
ssu = read_key_value_file(target_dir / "etc" / "ssu" / "ssu.ini")
return {
"release": ssu.get("release", ""),
"version_id": sailfish.get("VERSION_ID", ""),
"flavour": ssu.get("flavour") or sailfish.get("SAILFISH_FLAVOUR", ""),
}
def list_local_sdk_targets(local_sdk: Path) -> list[LocalSdkTarget]:
targets_dir = local_sdk_targets_dir(local_sdk)
if not targets_dir.is_dir():
return []
targets: dict[str, LocalSdkTarget] = {}
for child in sorted(targets_dir.iterdir()):
if not child.is_dir() or ".pool." in child.name:
continue
target = canonical_local_target_name(child.name)
arch_and_suffix = split_local_target_arch(target)
if arch_and_suffix is None:
continue
arch, suffix = arch_and_suffix
if target in targets and child.name != target:
continue
metadata = target_metadata(child)
release = metadata.get("release", "")
version_id = metadata.get("version_id", "")
flavour = metadata.get("flavour", "")
if not release and suffix:
release = suffix
targets[target] = LocalSdkTarget(
arch=arch,
target=target,
release=release,
version_id=version_id,
flavour=flavour,
)
return sorted(targets.values(), key=lambda item: (item.arch, item.target))
def release_component_count(release: str) -> int:
return len(release.split(".")) if re.fullmatch(r"\d+(?:\.\d+){2,3}", release) else 0
def local_target_matches_release(target: LocalSdkTarget, release: str) -> bool:
release = normalize_local_release(release)
if not release or release == LIVE_RELEASE:
return target.release == LIVE_RELEASE
if release == "latest":
return False
if target.release == release or target.version_id == release:
return True
component_count = release_component_count(release)
if component_count == 3:
return target.version_id.startswith(f"{release}.") or target.target.endswith(f"-{release}")
return target.target.endswith(f"-{release}")
def normalize_local_release(release: str | None) -> str:
if not release:
return ""
release = release.strip()
if release.lower() == LIVE_RELEASE:
return LIVE_RELEASE
return release
def requested_release(project_dirs: Iterable[Path], explicit_release: str | None) -> str | None:
requested = explicit_requested_release(explicit_release)
if requested:
return requested
seen: set[Path] = set()
for project_dir in project_dirs:
if project_dir in seen:
continue
seen.add(project_dir)
inferred = infer_release_from_workflows(project_dir)
if inferred:
return inferred
return None
def explicit_requested_release(explicit_release: str | None) -> str | None:
if explicit_release:
return explicit_release
env_release = os.environ.get("SAILFISHOS_RELEASE")
if env_release:
return env_release
return None
def local_sdk_requested_release(explicit_release: str | None) -> str:
return normalize_local_release(explicit_requested_release(explicit_release)) or LIVE_RELEASE
def select_local_sdk_builds(
local_sdk: Path,
release: str,
requested_arches: list[str],
build_all: bool,
project_dir: Path,
requested_targets: list[str] | None = None,
) -> list[LocalSdkBuild] | None:
requested_targets = requested_targets or []
installed = list_local_sdk_targets(local_sdk)
matching = [
target
for target in installed
if local_target_matches_release(target, release)
]
if requested_targets:
by_name = {target.target: target for target in installed}
builds: list[LocalSdkBuild] = []
for requested in requested_targets:
target = by_name.get(canonical_local_target_name(requested))
if target is None:
return None
if release != LIVE_RELEASE and not local_target_matches_release(target, release):
return None
builds.append(LocalSdkBuild(target.arch, target.target))
return builds
if not matching:
return None
by_arch = {target.arch: target for target in matching}
by_target = {target.target: target for target in matching}
if build_all:
return [LocalSdkBuild(target.arch, target.target) for target in matching]
requested = requested_arches[:]
if not requested:
last_arch = parse_last_arch(project_dir)
if last_arch:
requested = [last_arch]
if not requested:
return None
builds: list[LocalSdkBuild] = []
for arch in requested:
target = by_target.get(arch) or by_arch.get(arch)
if target is None:
return None
builds.append(LocalSdkBuild(target.arch, target.target))
return builds
def build_local_sdk_arch(
project_dir: Path,
local_sdk: Path,
release: str,
arch: str,
target: str,
debug_build: bool = False,
local_rpm_dirs: list[Path] | None = None,
no_vcs_apply: bool = True,
allow_untrusted_rpms: bool = False,
) -> None:
user = host_user()
uid = os.getuid()
gid = os.getgid()
home = str(Path.home().resolve())
image = local_sdk_build_engine_image(user)
project_mount_root = local_sdk_project_mount_root(project_dir)
sdk_mount_root = local_sdk_mount_root(local_sdk)
binary_names = ":".join(sorted(spec_names(project_dir) | pro_targets(project_dir)))
local_rpm_dirs = local_rpm_dirs or []
inner_command = r'''
set -euo pipefail
cd "$PROJECT_DIR"
mkdir -p .mb2
mkdir -p .mb2/build-sailfishos-skill
logfile="$BUILD_LOG"
: > "$logfile"
{
echo "# build-sailfishos-skill"
echo "release=${RELEASE:-}"
echo "arch=${ARCH:-}"
echo "debug=${DEBUG_BUILD:-0}"
echo "target=${TARGET:-}"
echo
} >> "$logfile"
if [ -n "${LOCAL_RPM_DIRS:-}" ]; then
rpm_files=()
OLDIFS="$IFS"
IFS=':'
for dir in ${LOCAL_RPM_DIRS}; do
[ -d "$dir" ] || continue
for rpm in "$dir"/*.rpm; do
[ -e "$rpm" ] || continue
case "$(basename "$rpm")" in
*-debuginfo-*|*-debugsource-*|*-tests-*|*-examples-*|*-doc-*|*-ts-devel-*)
continue
;;
esac
rpm_files+=("$rpm")
done
done
IFS="$OLDIFS"
if [ "${#rpm_files[@]}" -gt 0 ]; then
zypper_args=( --non-interactive install --oldpackage --force-resolution )
if [ "${ALLOW_UNTRUSTED_RPMS:-0}" = "1" ]; then
zypper_args+=( --allow-unsigned-rpm )
fi
sb2 -t "$TARGET" -m sdk-install -R zypper "${zypper_args[@]}" \
"${rpm_files[@]}" 2>&1 | tee -a "$logfile"
fi
fi
mb2_args=( -t "$TARGET" )
if [ "${NO_VCS_APPLY:-0}" = "1" ]; then
mb2_args+=( --no-vcs-apply )
fi
mb2_args+=( build --prepare )
if [ "${DEBUG_BUILD:-0}" = "1" ]; then
mb2_args+=( -d )
fi
mb2 "${mb2_args[@]}" 2>&1 | tee -a "$logfile"
rm -rf .mb2/build-sailfishos-skill/rpms
if [ -d RPMS ]; then
mkdir -p .mb2/build-sailfishos-skill/rpms
find RPMS -maxdepth 1 -type f -name '*.rpm' -exec cp -f {} .mb2/build-sailfishos-skill/rpms/ \;
chmod -R u+rwX .mb2/build-sailfishos-skill/rpms >/dev/null 2>&1 || true
fi
OLDIFS="$IFS"
IFS=':'
for name in ${SYNC_BINARIES:-}; do
[ -n "$name" ] || continue
[ -e "$name" ] || continue
cp -f "$name" .mb2/build-sailfishos-skill/ >/dev/null 2>&1 || true
done
IFS="$OLDIFS"
'''
wrapper_command = rf'''
set -euo pipefail
if [ ! -x "$LOCAL_SDK" ]; then
echo "Installed Sailfish SDK chroot not found or not executable at $LOCAL_SDK" >&2
exit 1
fi
if getent passwd mersdk >/dev/null 2>&1; then
sed -i 's#^mersdk:[^:]*:[0-9]*:[0-9]*:[^:]*:[^:]*:#{user}:x:{uid}:{gid}::{home}:#' /etc/passwd
elif ! getent passwd {shlex.quote(user)} >/dev/null 2>&1; then
printf '%s:x:%s:%s::%s:/bin/bash\n' {shlex.quote(user)} {uid} {gid} {shlex.quote(home)} >> /etc/passwd
fi
"$LOCAL_SDK" -u {shlex.quote(user)} env \
PROJECT_DIR="$PROJECT_DIR" \
RELEASE="$RELEASE" \
TARGET="$TARGET" \
ARCH="$ARCH" \
DEBUG_BUILD="$DEBUG_BUILD" \
BUILD_LOG="$BUILD_LOG" \
LOCAL_RPM_DIRS="$LOCAL_RPM_DIRS" \
NO_VCS_APPLY="$NO_VCS_APPLY" \
ALLOW_UNTRUSTED_RPMS="$ALLOW_UNTRUSTED_RPMS" \
SYNC_BINARIES="$SYNC_BINARIES" \
bash -lc {shlex.quote(inner_command)}
'''
log(f"Building local SDK target {target} for {release} via installed /srv/mer SDK")
run(
[
"docker",
"run",
"--rm",
"--privileged",
"-v",
f"{sdk_mount_root}:{sdk_mount_root}",
"-v",
f"{project_mount_root}:{project_mount_root}",
"-w",
str(project_dir),
"-e",
f"PROJECT_DIR={project_dir}",
"-e",
f"LOCAL_SDK={local_sdk}",
"-e",
f"RELEASE={release}",
"-e",
f"TARGET={target}",
"-e",
f"ARCH={arch}",
"-e",
f"DEBUG_BUILD={'1' if debug_build else '0'}",
"-e",
f"BUILD_LOG={build_log_path(project_dir)}",
"-e",
f"LOCAL_RPM_DIRS={':'.join(str(path) for path in local_rpm_dirs)}",
"-e",
f"NO_VCS_APPLY={'1' if no_vcs_apply else '0'}",
"-e",
f"ALLOW_UNTRUSTED_RPMS={'1' if allow_untrusted_rpms else '0'}",
"-e",
f"SYNC_BINARIES={binary_names}",
image,
"bash",
"-lc",
wrapper_command,
]
)
def build_arch(
project_dir: Path,
release: str,
arch: str,
debug_build: bool = False,
local_rpm_dirs: list[Path] | None = None,
no_vcs_apply: bool = False,
allow_untrusted_rpms: bool = False,
) -> None:
image = f"{CONTAINER_IMAGE}:{release}"
target = f"SailfishOS-{release}-{arch}"
binary_names = ":".join(sorted(spec_names(project_dir) | pro_targets(project_dir)))
is_gecko_build = (project_dir / "gecko-dev").is_dir() and (project_dir / "rpm" / "xulrunner-qt5.spec").is_file()
local_rpm_dirs = local_rpm_dirs or []
local_rpm_mounts = [f"/local-rpms/{index}" for index, _ in enumerate(local_rpm_dirs)]
build_command = r'''
set -euo pipefail
workroot="${HOME:-/tmp}"
if [ ! -d "$workroot" ] || [ ! -w "$workroot" ]; then
workroot=/tmp
fi
workdir="$workroot/build-sailfishos-skill"
mkdir -p /share/.mb2
mkdir -p /share/.mb2/build-sailfishos-skill
logfile=/share/.mb2/build-sailfishos-skill-last.log
: > "$logfile"
{
echo "# build-sailfishos-skill"
echo "release=${RELEASE:-}"
echo "arch=${ARCH:-}"
echo "debug=${DEBUG_BUILD:-0}"
echo "target=${TARGET:-}"
echo
} >> "$logfile"
rm -rf "$workdir"
mkdir -p "$workdir"
cp -a /share/. "$workdir/"
rm -rf "$workdir/RPMS"
cd "$workdir"
if [ "${IS_GECKO_BUILD:-0}" = "1" ]; then
# The local Sailfish gecko checkout already has the rpm/ patch stack applied,
# so keep %prep for its bootstrap side effects but disable patch re-apply in
# the copied spec.
sed -i \
-e 's/^%autosetup -p1 -n /%autosetup -N -n /' \
rpm/xulrunner-qt5.spec
fi
if [ -n "${LOCAL_RPM_DIRS:-}" ]; then
rpm_files=()
OLDIFS="$IFS"
IFS=':'
for dir in ${LOCAL_RPM_DIRS}; do
[ -d "$dir" ] || continue
for rpm in "$dir"/*.rpm; do
[ -e "$rpm" ] || continue
case "$(basename "$rpm")" in
*-debuginfo-*|*-debugsource-*|*-tests-*|*-examples-*|*-doc-*|*-ts-devel-*)
continue
;;
esac
rpm_files+=("$rpm")
done
done
IFS="$OLDIFS"
if [ "${#rpm_files[@]}" -gt 0 ]; then
zypper_args=( --non-interactive install --oldpackage --force-resolution )
if [ "${ALLOW_UNTRUSTED_RPMS:-0}" = "1" ]; then
zypper_args+=( --allow-unsigned-rpm )
fi
zypper "${zypper_args[@]}" "${rpm_files[@]}" 2>&1 | tee -a "$logfile"
fi
fi
mb2_args=( -t "$TARGET" )
if [ "${IS_GECKO_BUILD:-0}" = "1" ] || [ "${NO_VCS_APPLY:-0}" = "1" ]; then
mb2_args+=( --no-vcs-apply )
fi
mb2_args+=( build )
if [ "${IS_GECKO_BUILD:-0}" = "1" ]; then
mb2_args+=( --prepare )
fi
if [ "${DEBUG_BUILD:-0}" = "1" ]; then
mb2_args+=( -d )
fi
mb2 "${mb2_args[@]}" 2>&1 | tee -a "$logfile"
for state_file in .mb2/target .mb2/spec .mb2/snapshot.lock; do
if [ -e "$state_file" ]; then
cp -f "$state_file" /share/.mb2/
fi
done
chmod -R a+rwX /share/.mb2 >/dev/null 2>&1 || true
rm -rf /share/.mb2/build-sailfishos-skill/rpms
if [ -d RPMS ]; then
mkdir -p /share/.mb2/build-sailfishos-skill/rpms
find RPMS -maxdepth 1 -type f -name '*.rpm' -exec cp -f {} /share/.mb2/build-sailfishos-skill/rpms/ \;
chmod -R a+rwX /share/.mb2/build-sailfishos-skill/rpms >/dev/null 2>&1 || true
fi
for pattern in \
Makefile .qmake.stash '*.o' '*.a' '*.so' '*.prl' '*.list' \
'moc_*.cpp' 'moc_*.o' 'qrc_*.cpp' 'qrc_*.o' 'ui_*.h' \
CMakeCache.txt cmake_install.cmake compile_commands.json build.ninja rules.ninja install_manifest.txt
do
for f in $pattern; do
[ -e "$f" ] || continue
cp -f "$f" /share/
done
done
if [ -d translations ]; then
mkdir -p /share/translations
for f in translations/*.qm; do
[ -e "$f" ] || continue
cp -f "$f" /share/translations/
done
fi
OLDIFS="$IFS"
IFS=':'
for name in ${SYNC_BINARIES:-}; do
[ -n "$name" ] || continue
[ -e "$name" ] || continue
cp -f "$name" /share/
done
IFS="$OLDIFS"
'''
gecko_wrapper_command = rf'''
set -euo pipefail
if [ ! -e /usr/lib/libclang.so.15 ]; then
zypper --non-interactive install clang-libs
fi
if ! rpm -q gcc-c++ >/dev/null 2>&1; then
zypper --non-interactive install gcc-c++
fi
python3 - <<'PY'
import os
import pwd
pw = pwd.getpwnam("mersdk")
os.environ["HOME"] = pw.pw_dir
os.setgroups([])
os.setgid(pw.pw_gid)
os.setuid(pw.pw_uid)
os.execvp("bash", ["bash", "-lc", {build_command!r}])
PY
'''
log(f"Building {target} via container shadow build and syncing artifacts back in place")
try:
docker_cmd = [
"docker",
"run",
"--rm",
"--privileged",
"-v",
f"{project_dir}:/share",
]
if is_gecko_build:
docker_cmd.extend(["-u", "0"])
for mount_path, local_rpm_dir in zip(local_rpm_mounts, local_rpm_dirs):
docker_cmd.extend(["-v", f"{local_rpm_dir}:{mount_path}:ro"])
docker_cmd.extend(
[
"-e",
f"TARGET={target}",
"-e",
f"RELEASE={release}",
"-e",
f"ARCH={arch}",
"-e",
f"DEBUG_BUILD={'1' if debug_build else '0'}",
"-e",
f"BUILD_LOG={build_log_path(project_dir)}",
"-e",
f"SYNC_BINARIES={binary_names}",
"-e",
f"LOCAL_RPM_DIRS={':'.join(local_rpm_mounts)}",
"-e",
f"NO_VCS_APPLY={'1' if no_vcs_apply else '0'}",
"-e",
f"ALLOW_UNTRUSTED_RPMS={'1' if allow_untrusted_rpms else '0'}",
"-e",
f"IS_GECKO_BUILD={'1' if is_gecko_build else '0'}",
image,
"bash",
"-lc",
gecko_wrapper_command if is_gecko_build else build_command,
]
)
run(docker_cmd)
except subprocess.CalledProcessError:
diagnose_missing_dependencies(project_dir, release, arch)
raise
def copy_rpms(project_dir: Path, release: str, arch: str, debug_build: bool, artifacts_dir: Path) -> list[Path]:
rpm_dir = staging_rpms_dir(project_dir)
if not rpm_dir.is_dir():
raise SystemExit("Build completed but staged RPMs were not captured")
rpms = sorted(rpm_dir.glob("*.rpm"))
if not rpms:
raise SystemExit("Build completed but no staged RPMs were found")
destination_dir = variant_destination_dir(artifacts_dir, release, arch, debug_build)
if destination_dir.exists():
shutil.rmtree(destination_dir)
destination_dir.mkdir(parents=True, exist_ok=True)
copied: list[Path] = []
for rpm in rpms:
destination = destination_dir / rpm.name
shutil.copy2(rpm, destination)
copied.append(destination)
shutil.rmtree(rpm_dir)
return copied
def resolve_project_dir(project_dir: Path) -> Path:
if not project_dir.is_dir():
raise SystemExit(f"Project directory not found: {project_dir}")
if has_spec_files(project_dir):
return project_dir
matches = [child for child in sorted(project_dir.iterdir()) if child.is_dir() and has_spec_files(child)]
if len(matches) == 1:
log(f"Using SailfishOS build root {matches[0]} discovered under {project_dir}")
return matches[0]
if len(matches) > 1:
options = ", ".join(str(path) for path in matches)
raise SystemExit(
f"{project_dir} contains multiple one-level-deep SailfishOS build roots: {options}. "
"Pass --project-dir pointing at the intended one."
)
raise SystemExit(
f"Could not find rpm/*.spec in {project_dir} or one level below it. "
"Pass --project-dir pointing at the SailfishOS build root."
)
def build_preflight_payload(
*,
project_dir: Path,
context: BuildContext,
builds: list[LocalSdkBuild | str],
artifacts_dir: Path,
local_rpms: dict[Path, list[Path]],
debug_build: bool,
clean: bool,
no_vcs_apply: bool,
allow_untrusted_rpms: bool,
pull_policy: str,
image_available: bool | None,
) -> dict[str, object]:
planned_builds = [
{
"arch": build.arch if isinstance(build, LocalSdkBuild) else build,
"target": build.target if isinstance(build, LocalSdkBuild) else f"SailfishOS-{context.release}-{build}",
}
for build in builds
]
permission_strategy = "local-sdk-user"
if context.backend == "docker":
permission_strategy = "scoped-acl" if shutil.which("setfacl") else "configured-fallback"
would_pull = bool(
context.backend == "docker"
and (pull_policy == "always" or (pull_policy == "missing" and image_available is False))
)
return {
"schema_version": 1,
"helper_version": HELPER_VERSION,
"project_dir": str(project_dir),
"backend": context.backend,
"release": context.release,
"image": context.image,
"image_available": image_available,
"local_sdk": context.local_sdk,
"builds": planned_builds,
"debug": debug_build,
"clean": clean,
"no_vcs_apply": no_vcs_apply,
"artifacts_dir": str(artifacts_dir),
"local_rpms": {
str(directory): [str(rpm) for rpm in rpms]
for directory, rpms in local_rpms.items()
},
"allow_untrusted_rpms": allow_untrusted_rpms,
"pull_policy": pull_policy,
"would_pull": would_pull,
"permission_strategy": permission_strategy,
"mutates_project": False,
}
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Build a SailfishOS project with Docker or an installed SDK")
parser.add_argument("--version", action="version", version=f"%(prog)s {HELPER_VERSION}")
parser.add_argument("--project-dir", default=".", help="Project root containing rpm/*.spec")
parser.add_argument("--release", help="SailfishOS release, for example 3.4.0.24")
parser.add_argument("--arch", action="append", default=[], help="Architecture to build, may be repeated")
parser.add_argument(
"--target",
action="append",
default=[],
help="Exact installed local SDK target to build; may be repeated",
)
parser.add_argument("--all", action="store_true", help="Build every architecture supported by the chosen SDK image")
parser.add_argument("--list-arches", action="store_true", help="Print supported architectures and exit")
parser.add_argument(
"--backend",
choices=("auto", "docker", "local"),
default="auto",
help="Build backend. Auto uses --local-sdk/--target when supplied, otherwise Docker",
)
parser.add_argument(
"--permission-fallback",
choices=("error", "chmod"),
default=DEFAULT_PERMISSION_FALLBACK,
help="Fallback when setfacl is unavailable",
)
parser.add_argument(
"--artifacts-dir",
help="Directory where built RPMs are copied. Defaults to RPMS/",
)
parser.add_argument("--clean", action="store_true", help="Remove generated in-place build artifacts before building")
parser.add_argument(
"--debug",
action="store_true",
help="Pass -d to mb2 build so main binaries are stripped and debug packages are generated",
)
parser.add_argument(
"--local-rpms-dir",
action="append",
default=[],
help="Directory of locally built RPMs to install into the SDK target before building; may be repeated",
)
parser.add_argument(
"--pull-policy",
choices=("always", "missing", "never"),
default="always",
help="When to pull the release Docker image",
)
parser.add_argument("--no-pull", action="store_true", help=argparse.SUPPRESS)
parser.add_argument(
"--local-sdk",
nargs="?",
const=str(DEFAULT_LOCAL_SDK),
help=(
"Use the installed SDK chroot through a privileged Docker wrapper "
f"instead of a release Docker image. Defaults to {DEFAULT_LOCAL_SDK} "
"when no path is supplied."
),
)
vcs_group = parser.add_mutually_exclusive_group()
vcs_group.add_argument(
"--no-vcs-apply",
dest="no_vcs_apply",
action="store_true",
default=None,
help="Tell mb2 not to apply VCS changes before building",
)
vcs_group.add_argument(
"--vcs-apply",
dest="no_vcs_apply",
action="store_false",
help="Allow mb2 to apply VCS changes (local SDK builds default to no VCS apply)",
)
parser.add_argument(
"--allow-untrusted-rpms",
action="store_true",
help="Allow unsigned RPMs supplied with --local-rpms-dir",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Validate inputs and print the build plan without pulling, cleaning, changing ACLs, or building",
)
parser.add_argument("--json", action="store_true", help="Print --dry-run output as JSON")
args = parser.parse_args(argv)
if args.json and not args.dry_run:
parser.error("--json requires --dry-run")
if args.target and args.backend == "docker":
parser.error("--target requires --backend local or auto")
if args.local_sdk and args.backend == "docker":
parser.error("--local-sdk cannot be combined with --backend docker")
return args
def concise_error(error: BaseException) -> str:
if isinstance(error, subprocess.CalledProcessError):
command = error.cmd if isinstance(error.cmd, list) else [str(error.cmd)]
return f"Command exited with status {error.returncode}: {shlex.join(command)[:500]}"
return str(error) or error.__class__.__name__
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
require_tool("docker")
requested_project_dir = Path(args.project_dir).resolve()
project_dir = resolve_project_dir(requested_project_dir)
if args.no_pull:
args.pull_policy = "never"
local_requested = args.backend == "local" or args.local_sdk is not None or bool(args.target)
local_sdk_value = args.local_sdk or (str(DEFAULT_LOCAL_SDK) if local_requested else None)
local_sdk_path = Path(local_sdk_value).expanduser().resolve(strict=False) if local_sdk_value else None
local_builds: list[LocalSdkBuild] | None = None
if local_requested and args.backend != "docker":
assert local_sdk_path is not None
local_release = local_sdk_requested_release(args.release)
local_builds = select_local_sdk_builds(
local_sdk_path,
local_release,
args.arch,
args.all or args.list_arches,
project_dir,
args.target,
)
if local_builds:
if local_release == LIVE_RELEASE:
installed_by_name = {target.target: target for target in list_local_sdk_targets(local_sdk_path)}
selected = installed_by_name.get(local_builds[0].target)
release = (selected.release or selected.version_id) if selected else LIVE_RELEASE
release = release or LIVE_RELEASE
else:
release = local_release
elif args.backend == "local" or args.target or local_release == LIVE_RELEASE:
available = ", ".join(target.target for target in list_local_sdk_targets(local_sdk_path)) or "none"
raise SystemExit(
f"No matching installed local SDK target for release {local_release}. Available targets: {available}"
)
else:
log(
f"No matching local SDK target for release {local_release}; "
f"falling back to {CONTAINER_IMAGE}"
)
release = resolve_release((requested_project_dir, project_dir), args.release)
else:
release = resolve_release((requested_project_dir, project_dir), args.release)
if release == LIVE_RELEASE:
raise SystemExit("Release 'live' requires --local-sdk with a matching installed SDK target.")
use_local_sdk = local_sdk_path is not None and local_builds is not None
image: str | None = None
image_available: bool | None = None
if use_local_sdk:
image = local_sdk_build_engine_image(host_user())
image_available = docker_image_exists(image)
if not image_available and not args.dry_run:
raise SystemExit(f"Local SDK wrapper image is not available: {image}")
else:
image = f"{CONTAINER_IMAGE}:{release}"
image_available = docker_image_exists(image)
supported_arches: list[str] = []
if not use_local_sdk and not args.dry_run:
image, _ = ensure_image(release, args.pull_policy)
image_available = True
supported_arches = list_supported_arches(release)
elif not use_local_sdk and image_available:
supported_arches = list_supported_arches(release)
if args.list_arches:
if use_local_sdk:
print("\n".join(build.arch for build in local_builds))
return 0
if args.dry_run and not supported_arches:
raise SystemExit(f"Cannot list architectures because Docker image {image} is not available locally.")
print("\n".join(supported_arches))
return 0
if use_local_sdk:
builds: list[LocalSdkBuild | str] = local_builds
elif args.dry_run and not supported_arches:
if args.all:
builds = ["<all-supported-architectures>"]
else:
requested = args.arch or ([parse_last_arch(project_dir)] if parse_last_arch(project_dir) else [])
if not requested:
raise SystemExit("Pass --arch or make the Docker image available so targets can be discovered.")
builds = [arch for arch in requested if arch]
else:
builds = resolve_arches(args.arch, args.all, supported_arches, project_dir)
artifacts_dir = Path(args.artifacts_dir).resolve() if args.artifacts_dir else default_artifacts_dir(project_dir)
local_rpm_dirs = [Path(path).resolve() for path in args.local_rpms_dir]
selected_local_rpms = validate_local_rpm_dirs(local_rpm_dirs)
no_vcs_apply = args.no_vcs_apply if args.no_vcs_apply is not None else use_local_sdk
context = BuildContext(
backend="local" if use_local_sdk else "docker",
release=release,
image=image,
image_id=docker_image_id(image) if image_available and image else None,
local_sdk=str(local_sdk_path) if use_local_sdk else None,
)
if args.dry_run:
payload = build_preflight_payload(
project_dir=project_dir,
context=context,
builds=builds,
artifacts_dir=artifacts_dir,
local_rpms=selected_local_rpms,
debug_build=args.debug,
clean=args.clean,
no_vcs_apply=no_vcs_apply,
allow_untrusted_rpms=args.allow_untrusted_rpms,
pull_policy=args.pull_policy,
image_available=image_available,
)
if args.json:
print(json.dumps(payload, indent=2, sort_keys=True))
else:
print(f"Backend: {payload['backend']}")
print(f"Release: {payload['release']}")
print(f"Builds: {', '.join(item['target'] for item in payload['builds'])}")
print(f"Artifacts: {payload['artifacts_dir']}")
print(f"Would pull image: {'yes' if payload['would_pull'] else 'no'}")
return 0
started_at = datetime.now(timezone.utc)
all_copied_rpms: list[Path] = []
build_records: list[dict[str, object]] = []
rpm_context = stage_local_sdk_rpms(project_dir, selected_local_rpms) if use_local_sdk else nullcontext(local_rpm_dirs)
with project_build_lock(project_dir), rpm_context as effective_local_rpm_dirs:
if not use_local_sdk:
ensure_container_write_access(project_dir, args.permission_fallback)
for build in builds:
arch = build.arch if isinstance(build, LocalSdkBuild) else build
target = build.target if isinstance(build, LocalSdkBuild) else f"SailfishOS-{release}-{arch}"
record: dict[str, object] = {
"arch": arch,
"target": target,
"status": "running",
"rpms": [],
}
build_records.append(record)
write_build_metadata(
project_dir,
context=context,
builds=build_records,
debug_build=args.debug,
artifacts_dir=artifacts_dir,
status="running",
started_at=started_at,
)
build_started = time.monotonic()
try:
previous_arch = parse_last_arch(project_dir)
if previous_arch and previous_arch != arch:
cleanup_in_place_artifacts(project_dir, previous_arch, arch)
elif args.clean:
cleanup_generated_artifacts(project_dir, "Explicit cleanup requested")
if isinstance(build, LocalSdkBuild):
assert local_sdk_path is not None
build_local_sdk_arch(
project_dir,
local_sdk_path,
release,
arch,
build.target,
debug_build=args.debug,
local_rpm_dirs=effective_local_rpm_dirs,
no_vcs_apply=no_vcs_apply,
allow_untrusted_rpms=args.allow_untrusted_rpms,
)
else:
build_arch(
project_dir,
release,
arch,
debug_build=args.debug,
local_rpm_dirs=effective_local_rpm_dirs,
no_vcs_apply=no_vcs_apply,
allow_untrusted_rpms=args.allow_untrusted_rpms,
)
write_target_marker(project_dir, arch)
write_manifest(project_dir, generated_candidate_paths(project_dir))
copied = copy_rpms(project_dir, release, arch, args.debug, artifacts_dir)
verify_expected_rpms(copied, args.debug)
record.update(
status="success",
duration_seconds=round(time.monotonic() - build_started, 3),
rpms=copied,
)
all_copied_rpms.extend(copied)
log(
f"Copied {len(copied)} RPM(s) for {arch} to "
f"{variant_destination_dir(artifacts_dir, release, arch, args.debug)}"
)
except BaseException as error:
failure_class = classify_failure(error, build_log_path(project_dir))
message = concise_error(error)
record.update(
status="failed",
duration_seconds=round(time.monotonic() - build_started, 3),
failure_class=failure_class,
failure_message=message,
)
write_build_metadata(
project_dir,
context=context,
builds=build_records,
debug_build=args.debug,
artifacts_dir=artifacts_dir,
status="failed",
started_at=started_at,
failure_class=failure_class,
failure_message=message,
)
raise
write_build_metadata(
project_dir,
context=context,
builds=build_records,
debug_build=args.debug,
artifacts_dir=artifacts_dir,
status="success",
started_at=started_at,
)
print("Built RPMs:")
for rpm in all_copied_rpms:
print(rpm)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except subprocess.CalledProcessError as error:
log(f"Build failed: {concise_error(error)}")
sys.exit(error.returncode or 1)
except OSError as error:
log(f"Build failed: {concise_error(error)}")
sys.exit(1)
|