-
Notifications
You must be signed in to change notification settings - Fork 512
Expand file tree
/
Copy pathproject.py
More file actions
1618 lines (1384 loc) · 60.6 KB
/
project.py
File metadata and controls
1618 lines (1384 loc) · 60.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2022-2024 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Project file definition and helpers."""
from __future__ import annotations
import copy
import re
import textwrap
from typing import Any, Literal, Mapping, Tuple, cast
import pydantic
from craft_application import models
from craft_application.errors import CraftValidationError
from craft_application.models import BuildInfo, SummaryStr, VersionStr
from craft_application.models.constraints import (
SingleEntryDict,
SingleEntryList,
UniqueList,
)
from craft_cli import emit
from craft_grammar.models import Grammar # type: ignore[import-untyped]
from craft_platforms import DebianArchitecture, Platforms, snap
from craft_providers import bases
from pydantic import ConfigDict, PrivateAttr, StringConstraints
from typing_extensions import Annotated, Self, override
from snapcraft import utils
from snapcraft.const import SUPPORTED_ARCHS, SnapArch
from snapcraft.elf.elf_utils import get_arch_triplet
from snapcraft.errors import ProjectValidationError
from snapcraft.providers import SNAPCRAFT_BASE_TO_PROVIDER_BASE
from snapcraft.utils import get_effective_base
TIME_DURATION_REGEX = re.compile(r"^([0-9]+(ns|us|ms|s|m)){1,5}$")
ProjectName = Annotated[str, StringConstraints(max_length=40)]
def _validate_command_chain(command_chains: list[str] | None) -> list[str] | None:
"""Validate command_chain."""
if command_chains is not None:
for command_chain in command_chains:
if not re.match(r"^[A-Za-z0-9/._#:$-]*$", command_chain):
raise ValueError(
f"{command_chain!r} is not a valid command chain. Command chain entries must "
"be strings, and can only use ASCII alphanumeric characters and the following "
"special characters: / . _ # : $ -"
)
return command_chains
def validate_architectures(architectures):
"""Expand and validate architecture data.
Validation includes:
- The list cannot be a combination of strings and Architecture objects.
- The same architecture cannot be defined in multiple `build-for` fields,
even if the implicit values are used to define `build-for`.
- Only one architecture can be defined in the `build-for` list.
- The `all` keyword is properly used. (see `_validate_architectures_all_keyword()`)
:raise ValueError: If architecture data is invalid.
"""
if not architectures:
return architectures
# validate strings and Architecture objects are not mixed
if not (
all(isinstance(architecture, str) for architecture in architectures)
or all(isinstance(architecture, Architecture) for architecture in architectures)
):
raise ValueError(
f"every item must either be a string or an object for {architectures!r}"
)
_expand_architectures(architectures)
# validate `build_for` after expanding data
if any(len(architecture.build_for) > 1 for architecture in architectures):
raise ValueError("only one architecture can be defined for 'build-for'")
_validate_architectures_all_keyword(architectures)
if len(architectures) > 1:
# validate multiple uses of the same architecture
unique_build_fors = set()
for element in architectures:
for architecture in element.build_for:
if architecture in unique_build_fors:
raise ValueError(
f"multiple items will build snaps that claim to run on {architecture}"
)
unique_build_fors.add(architecture)
# validate architectures are supported
if len(architectures):
for element in architectures:
for arch in element.build_for + element.build_on:
if arch != "all" and arch not in utils.get_supported_architectures():
supported_archs = utils.humanize_list(
utils.get_supported_architectures(), "and"
)
raise ValueError(
f"Architecture {arch!r} is not supported. Supported "
f"architectures are {supported_archs}."
)
return architectures
def _expand_architectures(architectures):
"""Expand architecture data.
Expansion to fully-defined Architecture objects includes the following:
- strings (shortform notation) are converted to Architecture objects
- `build-on` and `build-for` strings are converted to single item lists
- Empty `build-for` fields are implicitly set to the same architecture used in `build-on`
"""
for index, architecture in enumerate(architectures):
# convert strings into Architecture objects
if isinstance(architecture, str):
architectures[index] = Architecture(
build_on=cast(UniqueList[str], [architecture]),
build_for=cast(UniqueList[str], [architecture]),
)
elif isinstance(architecture, Architecture):
# convert strings to lists
if isinstance(architecture.build_on, str):
architectures[index].build_on = [architecture.build_on]
if isinstance(architecture.build_for, str):
architectures[index].build_for = [architecture.build_for]
# implicitly set build_for from build_on
elif architecture.build_for is None:
architectures[index].build_for = architectures[index].build_on
def _validate_architectures_all_keyword(architectures):
"""Validate `all` keyword is properly used.
Validation rules:
- `all` cannot be used to `build-on`
- If `all` is used for `build-for`, no other architectures can be defined
for `build-for`.
:raise ValueError: if `all` keyword isn't properly used.
"""
# validate use of `all` inside each build-on list
for architecture in architectures:
if "all" in architecture.build_on:
raise ValueError("'all' cannot be used for 'build-on'")
# validate use of `all` across all items in architecture list
if len(architectures) > 1:
if any("all" in architecture.build_for for architecture in architectures):
raise ValueError(
"one of the items has 'all' in 'build-for', but there are"
f" {len(architectures)} items: upon release they will conflict."
"'all' should only be used if there is a single item"
)
def apply_root_packages(yaml_data: dict[str, Any]) -> dict[str, Any]:
"""Create a new part with root level attributes.
Root level attributes such as build-packages and build-snaps
are known to Snapcraft but not Craft Parts. Create a new part
"snapcraft/core" with these attributes and apply it to the
current yaml_data.
"""
if "build-packages" not in yaml_data and "build-snaps" not in yaml_data:
return yaml_data
yaml_data = copy.deepcopy(yaml_data)
yaml_data.setdefault("parts", {})
yaml_data["parts"]["snapcraft/core"] = {"plugin": "nil"}
if "build-packages" in yaml_data:
yaml_data["parts"]["snapcraft/core"]["build-packages"] = yaml_data.pop(
"build-packages"
)
if "build-snaps" in yaml_data:
yaml_data["parts"]["snapcraft/core"]["build-snaps"] = yaml_data.pop(
"build-snaps"
)
return yaml_data
def _validate_version_name(version: str, model_name: str) -> None:
"""Validate a version complies to the naming convention.
:param version: version string to validate
:param model_name: name of the model that contains the version
:raises ValueError: if the version contains invalid characters
"""
if version and not re.match(
r"^[a-zA-Z0-9](?:[a-zA-Z0-9:.+~-]*[a-zA-Z0-9+~])?$", version
):
raise ValueError(
f"Invalid version '{version}': {model_name.title()} versions consist of "
"upper- and lower-case alphanumeric characters, as well as periods, colons, "
"plus signs, tildes, and hyphens. They cannot begin with a period, colon, "
"plus sign, tilde, or hyphen. They cannot end with a period, colon, or "
"hyphen"
)
def validate_name(*, name: str, field_name: str) -> str:
"""Validate a name.
:param name: The name to validate.
:param field_name: The name of the field being validated.
:returns: The validated name.
"""
if not re.match(r"^[a-z0-9-]*[a-z][a-z0-9-]*$", name):
raise ValueError(
f"{field_name} names can only use lowercase alphanumeric "
"and hyphens and must have at least one letter"
)
if name.startswith("-"):
raise ValueError(f"{field_name} names cannot start with a hyphen")
if name.endswith("-"):
raise ValueError(f"{field_name} names cannot end with a hyphen")
if "--" in name:
raise ValueError(f"{field_name} names cannot have two hyphens in a row")
return name
def _validate_component(name: str) -> str:
"""Validate a component name.
:param name: The component name to validate.
:returns: The validated component name.
"""
if name.startswith("snap-"):
raise ValueError(
"component names cannot start with the reserved prefix 'snap-'"
)
return validate_name(name=name, field_name="component")
def _get_partitions_from_components(
components_data: dict[str, Any] | None,
) -> list[str] | None:
"""Get a list of partitions based on the project's components.
:returns: A list of partitions formatted as ['default', 'component/<name>', ...]
or None if no components are defined.
"""
if components_data:
return ["default", *[f"component/{name}" for name in components_data.keys()]]
return None
def _validate_mandatory_base(base: str | None, snap_type: str | None) -> None:
"""Validate that the base is specified, if required by the snap_type."""
if (base is not None) ^ (snap_type not in ["base", "kernel", "snapd"]):
raise ValueError(
"Snap base must be declared when type is not base, kernel or snapd"
)
def _validate_duration_string(duration: str):
if not TIME_DURATION_REGEX.match(duration):
raise ValueError(f"{duration!r} is not a valid time value")
return duration
DurationString = Annotated[
str,
pydantic.Field(
examples=["1", "2s", "3m", "4ms", "5us", "6m7s8ms"],
pattern=TIME_DURATION_REGEX,
description="A duration string to be parsed by snapd.",
),
pydantic.BeforeValidator(_validate_duration_string),
]
class Socket(models.CraftBaseModel):
"""Snapcraft app socket definition."""
listen_stream: int | str = pydantic.Field(
description="The socket's abstract name or socket path.",
examples=["listen-stream: $SNAP_COMMON/lxd/unix.socket", "listen-stream: 80"],
)
socket_mode: int | None = pydantic.Field(
default=None,
description="The socket's mode and permissions.",
examples=["socket-mode: 0660"],
)
@pydantic.field_validator("listen_stream")
@classmethod
def _validate_list_stream(cls, listen_stream):
if isinstance(listen_stream, int):
if listen_stream < 1 or listen_stream > 65535:
raise ValueError(
f"{listen_stream!r} is not an integer between 1 and 65535 (inclusive)."
)
elif isinstance(listen_stream, str):
if not listen_stream.startswith("@snap.") and not re.match(
r"^[A-Za-z0-9/._#:$-]*$", listen_stream
):
raise ValueError(
f"{listen_stream!r} is not a valid socket path (e.g. /tmp/mysocket.sock)."
)
return listen_stream
class Lint(models.CraftBaseModel):
"""Linter configuration.
:ivar ignore: A list describing which files should have issues ignored for given linters.
The items in the list can be either:
- a string, which must be the name of one of the known linters (see below). All issues
from this linter will be ignored.
- a dict containing exactly one key, which must be the name of one of the known linters.
The value is then a list of strings corresponding to the filenames/patterns that
should be ignored for that linter.
The "known" linter names are the keys in :ref:`LINTERS`
"""
ignore: list[str | dict[str, list[str]]] = pydantic.Field(
description="Linters or files to skip when linting.",
examples=["lint: {ignore: [classic, library: [usr/lib/**/libfoo.so*]]}"],
)
# A private field to simplify lookup.
_lint_ignores: dict[str, list[str]] = PrivateAttr(default_factory=dict)
def __eq__(self, other):
"""Compare two Lint objects and ignore private attributes."""
return self.ignore == other.ignore
def __init__(self, **kwargs):
super().__init__(**kwargs)
for item in self.ignore:
if isinstance(item, str):
self._lint_ignores[item] = []
else:
assert len(item) == 1, "Expected exactly one key in lint ignore entry."
name, files = list(item.items())[0]
self._lint_ignores[name] = files
def all_ignored(self, linter_name: str) -> bool:
"""Whether all issues for linter `lint_name` should be ignored."""
return (
linter_name in self._lint_ignores
and len(self._lint_ignores[linter_name]) == 0
)
def ignored_files(self, linter_name: str) -> list[str]:
"""Get a list of filenames/patterns to ignore for `lint_name`.
Since the main usecase for this method is a for-loop with `fnmatch()`, it will
return `['*']` when *all* files should be ignored for `linter_name`, and `[]`
when *no* files should be ignored.
"""
if linter_name not in self._lint_ignores:
return []
if self.all_ignored(linter_name):
return ["*"]
return self._lint_ignores[linter_name]
class App(models.CraftBaseModel):
"""Snapcraft project app definition."""
command: str = pydantic.Field(
description="The command to run inside the snap when the app is invoked.",
examples=["command: bin/foo-app"],
)
autostart: str | None = pydantic.Field(
default=None,
description="The desktop file used to start an application when the desktop environment starts.",
examples=["autostart: foo-app.desktop"],
)
common_id: str | None = pydantic.Field(
default=None,
description="The app's unique `AppStream identifier <https://www.freedesktop.org/software/appstream/docs/chap-CatalogData.html#tag-ct-component-id>`_.",
examples=["common-id: org.canonical.foo"],
)
bus_name: str | None = pydantic.Field(
default=None,
description="The bus name that the app or service exposes through D-Bus.",
examples=["bus-name: org.bluez"],
)
desktop: str | None = pydantic.Field(
default=None,
description="The desktop file used to start the app.",
examples=["desktop: my-app.desktop"],
)
completer: str | None = pydantic.Field(
default=None,
description="The name of the bash completion script for the app.",
examples=["completer: bash-complete.sh"],
)
stop_command: str | None = pydantic.Field(
default=None,
description="The command that stops the service.",
examples=["stop-command: bin/foo-app --halt"],
)
post_stop_command: str | None = pydantic.Field(
default=None,
description="The command to run after the service is stopped.",
examples=["post-stop-command: bin/logrotate --force"],
)
start_timeout: DurationString | None = pydantic.Field(
default=None,
description="The maximum amount of time to wait for the service to start.",
examples=["start-timeout: 10s", "start-timeout: 2m"],
)
stop_timeout: DurationString | None = pydantic.Field(
default=None,
description="The maximum amount of time to wait for the service to stop.",
examples=["stop-timeout: 10s", "stop-timeout: 2m"],
)
watchdog_timeout: DurationString | None = pydantic.Field(
default=None,
description="The maximum amount of time the service can run without sending a heartbeat to the watchdog.",
examples=["watchdog-timeout: 10s", "watchdog-timeout: 2m"],
)
reload_command: str | None = pydantic.Field(
default=None,
description="The command to run to restart the service.",
examples=["reload-command: bin/foo-app --restart"],
)
restart_delay: DurationString | None = pydantic.Field(
default=None,
description="The time to wait between service restarts.",
examples=["restart-delay: 10s", "restart-delay: 2m"],
)
timer: str | None = pydantic.Field(
default=None,
description="The time or schedule to run a service.",
examples=[
"timer: 23:00",
"timer: 00:00-24:00/24",
"timer: mon,10:00,,fri,15:00",
],
)
daemon: Literal["simple", "forking", "oneshot", "notify", "dbus"] | None = (
pydantic.Field(
default=None,
description="Configures the app as a service, and sets its runtime and notification behavior.",
examples=["daemon: simple", "daemon: oneshot"],
)
)
after: UniqueList[str] = pydantic.Field(
default_factory=list,
description="The sequence of apps that the service runs after it launches.",
examples=["after: [foo-app, bar-app]"],
)
before: UniqueList[str] = pydantic.Field(
default_factory=list,
description="The sequence of apps that the service runs before it launches.",
examples=["before: [baz-app, quz-app]"],
)
refresh_mode: Literal["endure", "restart", "ignore-running"] | None = (
pydantic.Field(
default=None,
description="Determines how the service should restart when the snap refreshed.",
examples=["refresh-mode: restart"],
)
)
stop_mode: (
Literal[
"sigterm",
"sigterm-all",
"sighup",
"sighup-all",
"sigusr1",
"sigusr1-all",
"sigusr2",
"sigusr2-all",
"sigint",
"sigint-all",
]
| None
) = pydantic.Field(
default=None,
description="The signal to send when stopping the service.",
examples=["stop-mode: sigterm"],
)
restart_condition: (
Literal[
"on-success",
"on-failure",
"on-abnormal",
"on-abort",
"on-watchdog",
"always",
"never",
]
| None
) = pydantic.Field(
default=None,
description="The condition under which the service restarts.",
examples=["restart-condition: on-failure"],
)
install_mode: Literal["enable", "disable"] | None = pydantic.Field(
default=None,
description="Whether snapd can automatically start the service when the snap is installed.",
examples=["install-mode: enable"],
)
slots: UniqueList[str] | None = pydantic.Field(
default=None, description="The app's slots.", examples=["slots: [dbus-daemon]"]
)
plugs: UniqueList[str] | None = pydantic.Field(
default=None,
description="The interfaces that the app can connect to.",
examples=["plugs: [home, removable-media]"],
)
aliases: UniqueList[str] | None = pydantic.Field(
default=None,
description="The app's alternative internal identifiers.",
examples=["aliases: [my-app]"],
)
environment: dict[str, str] | None = pydantic.Field(
default=None,
description="The runtime environment variables available to the snap's apps.",
examples=[
"environment: {PYTHONPATH: $SNAP/usr/lib/python3/dist-packages, DISABLE_WAYLAND: 1"
],
)
command_chain: list[str] = pydantic.Field(
default_factory=list,
description="The sequence of commands to run before the app's command runs. These commands also run when the user invokes ``snap run --shell``.",
examples=["command-chain: [bin/alsa-launch, bin/desktop-launch]"],
)
sockets: dict[str, Socket] | None = pydantic.Field(
default=None,
description="The app's sockets.",
examples=["listen-stream: $SNAP_COMMON/lxd/unix.socket, socket-mode: 0660"],
)
daemon_scope: Literal["system", "user"] | None = pydantic.Field(
default=None,
description="Determines whether the service is run on a system or user instance of systemd.",
examples=["daemon-scope: user"],
)
activates_on: UniqueList[str] | None = pydantic.Field(
default=None,
description="The slots exposed by the snap to activate the service with D-Bus.",
examples=["activates-on: gnome-shell-dbus"],
)
passthrough: dict[str, Any] | None = pydantic.Field(
default=None,
description=(
"Values to push to the built snap's metadata file, snap.yaml. "
"Snapcraft doesn't validate the values provided here, so this key is "
"a convenient means of configuring snap features that are "
"experimental or in early access."
),
examples=["passthrough: {daemon: complex}"],
)
@pydantic.field_validator("autostart")
@classmethod
def _validate_autostart_name(cls, name):
if not re.match(r"^[A-Za-z0-9. _#:$-]+\.desktop$", name):
raise ValueError(
f"{name!r} is not a valid desktop file name (e.g. myapp.desktop)"
)
return name
@pydantic.field_validator(
"command", "stop_command", "post_stop_command", "reload_command", "bus_name"
)
@classmethod
def _validate_apps_section_content(cls, command: str) -> str:
# Find any invalid characters in the field.
# The regex below is derived from snapd's validator code.
# https://github.com/canonical/snapd/blob/0706e2d0b20ae2bf030863f142b8491b66e80bcb/snap/validate.go#L756
if not re.match(r"^[A-Za-z0-9/. _#:$-]*$", command):
message = "App commands must consist of only alphanumeric characters, spaces, and the following characters: / . _ # : $ -"
raise ValueError(message)
return command
@pydantic.field_validator("command_chain")
@classmethod
def _validate_command_chain(cls, command_chains):
return _validate_command_chain(command_chains)
@pydantic.field_validator("aliases")
@classmethod
def _validate_aliases(cls, aliases):
for alias in aliases:
if not re.match(r"^[a-zA-Z0-9][-_.a-zA-Z0-9]*$", alias):
raise ValueError(
f"{alias!r} is not a valid alias. Aliases must be strings, begin with an ASCII "
"alphanumeric character, and can only use ASCII alphanumeric characters and "
"the following special characters: . _ -"
)
return aliases
class Hook(models.CraftBaseModel):
"""Snapcraft project hook definition."""
command_chain: list[str] = pydantic.Field(
default_factory=list,
description="The sequence of commands to run before the app's command runs. Also applied when running ``snap run --shell``",
examples=["command-chain: [bin/alsa-launch, bin/desktop-launch]"],
)
environment: dict[str, str | None] | None = pydantic.Field(
default=None,
description="The hook's run-time environment variables.",
examples=[
"environment: {PYTHONPATH: /custom/path/:$PYTHON_PATH, DISABLE_WAYLAND: 1}"
],
)
plugs: UniqueList[str] | None = pydantic.Field(
default=None,
description="The interfaces that the hook can connect to.",
examples=["plugs: [home, removable-media]"],
)
passthrough: dict[str, Any] | None = pydantic.Field(
default=None,
description="Attributes to not validate for correctness. Useful for testing experimental snapd features.",
examples=["passthrough: {daemon: complex}"],
)
@pydantic.field_validator("command_chain")
@classmethod
def _validate_command_chain(cls, command_chains):
return _validate_command_chain(command_chains)
@pydantic.field_validator("plugs")
@classmethod
def _validate_plugs(cls, plugs):
if not plugs:
raise ValueError("'plugs' field cannot be empty.")
return plugs
class Architecture(models.CraftBaseModel, extra="forbid"):
"""Snapcraft project architecture definition."""
build_on: str | UniqueList[str] = pydantic.Field(
description="The architectures on which the snap can be built.",
examples=["build-on: amd64, riscv64"],
)
build_for: str | UniqueList[str] | None = pydantic.Field(
default=None,
description="The single element list of the architecture where the snap can be run",
examples=["build-for: amd64, riscv64"],
)
class ContentPlug(models.CraftBaseModel):
"""Snapcraft project content plug definition."""
content: str | None = pydantic.Field(
default=None,
description="The name for the content type.",
examples=["content: themes"],
)
interface: str = pydantic.Field(description="The name of the interface.")
target: str = pydantic.Field(
description="The path to the producer's files in the snap.",
examples=["target: $SNAP/data-dir/themes"],
)
default_provider: str | None = pydantic.Field(
default=None,
description="The default snap install to satisfy the interface.",
examples=["default-provider: gtk-common-themes"],
)
@pydantic.field_validator("default_provider")
@classmethod
def _validate_default_provider(cls, default_provider):
if default_provider and "/" in default_provider:
raise ValueError(
"Specifying a snap channel in 'default_provider' is not supported: "
f"{default_provider}"
)
return default_provider
class Platform(models.Platform):
"""Snapcraft project platform definition."""
build_on: UniqueList[str] | None = pydantic.Field(
description="The architectures on which the snap can be built.",
examples=["build-on: amd64, riscv64"],
min_length=1,
)
build_for: SingleEntryList | None = pydantic.Field(
default=None,
description="The single element list of the architecture the snap is built for.",
examples=["build-on: amd64, riscv64"],
)
@pydantic.field_validator("build_on", "build_for", mode="before")
@classmethod
def _vectorise_build_on_build_for(cls, val: str | list[str]) -> list[str]:
"""Vectorise architectures if needed."""
if isinstance(val, str):
val = [val]
return val
@pydantic.model_validator(mode="before")
@classmethod
def _validate_platform_set(cls, values: Mapping[str, Any]) -> Mapping[str, Any]:
"""If build_for is provided, then build_on must also be.
This aligns with the precedent set by the `architectures` keyword.
"""
if not values.get("build_on") and values.get("build_for"):
raise CraftValidationError(
"'build_for' expects 'build_on' to also be provided."
)
return values
@classmethod
def from_architectures(
cls,
architectures: list[str | Architecture],
) -> dict[str, Self]:
"""Convert a core22 architectures configuration to core24 platforms."""
platforms: dict[str, Self] = {}
for architecture in architectures:
if isinstance(architecture, str):
build_on = build_for = cast(UniqueList[str], [architecture])
else:
if isinstance(architecture.build_on, str):
build_on = build_for = cast(
UniqueList[str], [architecture.build_on]
)
else:
build_on = build_for = cast(UniqueList[str], architecture.build_on)
if architecture.build_for:
if isinstance(architecture.build_for, str):
build_for = cast(UniqueList[str], [architecture.build_for])
else:
build_for = cast(UniqueList[str], architecture.build_for)
platforms[build_for[0]] = cls(build_for=build_for, build_on=build_on)
return platforms
class Component(models.CraftBaseModel):
"""Snapcraft component definition."""
summary: SummaryStr = pydantic.Field(
description="The summary of the component.",
examples=["summary: Language translations for the app"],
)
description: str = pydantic.Field(
description="The full description of the component.",
examples=[
"description: Contains optional translation packs to allow the user to change the language."
],
)
type: Literal["test", "kernel-modules", "standard"] = pydantic.Field(
description="The component's type.", examples=["type: standard"]
)
version: VersionStr | None = pydantic.Field(
default=None,
description="The version of the component.",
examples=["version: 1.2.3"],
)
hooks: dict[str, Hook] | None = pydantic.Field(
default=None,
description="Configures the component's hooks.",
examples=["hooks: {configure: {plugs: [home]}}"],
)
MANDATORY_ADOPTABLE_FIELDS = ("version", "summary", "description")
class Project(models.Project):
"""Snapcraft project definition.
See https://snapcraft.io/docs/snapcraft-yaml-reference
XXX: Not implemented in this version
- system-usernames
"""
# snapcraft's `name` is more general than craft-application
name: ProjectName # type: ignore[assignment]
build_base: str | None = pydantic.Field(
validate_default=True,
default=None,
description="The build environment to use when building the snap",
examples=["base: core20", "base: core22", "base: core24", "base: devel"],
)
compression: Literal["lzo", "xz"] = pydantic.Field(
default="xz",
description="Specifies the algorithm that compresses the snap.",
examples=["compression: xz", "compression: lzo"],
)
version: VersionStr | None = pydantic.Field(
default=None,
description="The version of the snap.",
examples=["version: 1.2.3"],
)
donation: UniqueList[str] | None = pydantic.Field(
default=None,
description="The snap's donation links.",
examples=["donation: donate@example.com, https://example.com/donate"],
)
# snapcraft's `source_code` is more general than craft-application
source_code: UniqueList[str] | None = pydantic.Field( # type: ignore[assignment]
default=None,
description="The links to the source code of the snap or the original project.",
examples=["source-code: https://example.com/source-code"],
)
contact: UniqueList[str] | None = pydantic.Field( # type: ignore[reportIncompatibleVariableOverride]
default=None,
description="The snap author's contact links and email addresses.",
examples=["contact: [contact@example.com, https://example.com/contact"],
)
issues: UniqueList[str] | None = pydantic.Field( # type: ignore[reportIncompatibleVariableOverride]
default=None,
description="The links and email addresses for submitting issues, bugs, and feature requests.",
examples=["issues: issues@email.com, https://example.com/issues"],
)
website: UniqueList[str] | None = pydantic.Field(
default=None,
description="The links to the original software's web pages.",
examples=["website: https://example.com"],
)
type: Literal["app", "base", "gadget", "kernel", "snapd"] | None = pydantic.Field(
default=None, description="The snap's type.", examples=["type: kernel"]
)
icon: str | None = pydantic.Field(
default=None,
description="The path to the snap's icon.",
examples=["icon: snap/gui/icon.svg"],
)
confinement: Literal["classic", "devmode", "strict"] = pydantic.Field(
description="The amount of isolation the snap has from the host system.",
examples=[
"confinement: strict",
"confinement: classic",
"confinement: devmode",
],
)
layout: (
dict[str, SingleEntryDict[Literal["symlink", "bind", "bind-file", "type"], str]]
| None
) = pydantic.Field(
default=None,
description="The file layouts in the execution environment.",
examples=["layout: { /var/lib/foo: {bind: $SNAP_DATA/var/lib/foo}}"],
)
grade: Literal["stable", "devel"] | None = pydantic.Field(
default=None,
description="Publication guardrail for the snap",
examples=["grade: stable", "grade: devel"],
)
architectures: list[str | Architecture] | None = pydantic.Field(
default=None,
description="Determines which instruction set architectures the snap builds on and runs on.",
examples=[
"architectures: [amd64, riscv64]",
"architectures: [{build-on: [amd64], build-for: [amd64]}]",
"architectures: [{build-on: [amd64, riscv64], build-for: [riscv64]}]",
],
)
_architectures_in_yaml: bool | None = None
platforms: dict[str, Platform] | None = pydantic.Field( # type: ignore[assignment,reportIncompatibleVariableOverride]
default=None,
description="Determines which instruction set architectures the snap builds on and runs on.",
examples=[
"platforms: {amd64: {build-on: [amd64], build-for: [amd64]}, arm64: {build-on: [amd64, arm64], build-for: [arm64]}}"
],
)
assumes: UniqueList[str] = pydantic.Field(
default_factory=list,
description="The snapd features or minimum version of snapd required by the snap.",
examples=["assumes: [snapd2.66]", "assumes: [common-data-dir]"],
)
hooks: dict[str, Hook] | None = pydantic.Field(
default=None,
description="Configures the snap's hooks.",
examples=["hooks: {configure: {plugs: [home]}}"],
)
passthrough: dict[str, Any] | None = pydantic.Field(
default=None,
description="Attributes to not validate for correctness. Useful for testing experimental snapd features.",
examples=["passthrough: {daemon: complex}"],
)
apps: dict[str, App] | None = pydantic.Field(
default=None,
description="Declares the individual programs and services that the snap runs.",
examples=["apps: {foo-app: {command: bin/foo-app}}"],
)
plugs: dict[str, ContentPlug | Any] | None = pydantic.Field(
default=None,
description="Declares the snap's plugs.",
examples=[
"plugs: {dot-gitconfig: {interface: personal-files, read: [$HOME/.gitconfig]}}"
],
)
slots: dict[str, Any] | None = pydantic.Field(
default=None,
description="Declares the snap's slots.",
examples=[
"slots: {slot-1: {interface: content, content: my-binaries, source: {read: [$SNAP/bin]}}}"
],
)
lint: Lint | None = pydantic.Field(
default=None,
description="The linter configuration.",
examples=["lint: {ignore: [classic, library: [usr/lib/**/libfoo.so*]]}"],
)
epoch: str | None = pydantic.Field(
default=None,
description="The epoch associated with this version of the snap.",
examples=["epoch: 1", "epoch: 2*"],
)
adopt_info: str | None = pydantic.Field(
default=None,
description=textwrap.dedent(
"""\
Selects a part to inherit metadata from and reuse for the snap's metadata.
Required if one of ``version``, ``summary``, or ``description`` isn't set."""
),
examples=["adopt-info: foo-part"],
)
system_usernames: dict[str, Any] | None = pydantic.Field(
default=None,
description="The system usernames that the snap can use to run services.",
examples=["system-usernames: {snap-daemon: shared}"],
)
environment: dict[str, str | None] | None = pydantic.Field(
default=None,
description="The snap's run-time environment variables.",
examples=[
"environment: {PYTHONPATH: $SNAP/usr/lib/python3/dist-packages:$PYTHON_PATH, DISABLE_WAYLAND: 1}"
],
)
build_packages: Grammar[list[str]] | None = pydantic.Field(
default=None,
description="The system packages required on the host so that it can build parts for the snap.",
examples=["build-packages: libssl-dev, libyaml-dev"],
)
build_snaps: Grammar[list[str]] | None = pydantic.Field(
default=None,
description="The snaps required on the host so that it can build parts for the snap.",
examples=["build-snaps: go/1.22/stable, yq"],
)
ua_services: set[str] | None = pydantic.Field(
default=None,
description="The Ubuntu Pro services to enable when building the snap.",
examples=["ua-services: [esm-apps]"],
)
provenance: str | None = pydantic.Field(
default=None,
description="The primary-key header for snaps signed by third parties.",
examples=["provenance: test-provenance"],
)
components: dict[ProjectName, Component] | None = pydantic.Field(
default=None,
description="Declares the components to pack in conjunction with the snap.",
examples=["components: {foo-component: {type: standard}}"],
)
@override
@classmethod
def _providers_base(cls, base: str) -> bases.BaseAlias | None: