Skip to content

Available Modules

Orchestration

tutorial_sdk.project.TutorialProject

High-level API for tutorial projects.

Source code in src/tutorial_sdk/project.py
 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
class TutorialProject:
    """High-level API for tutorial projects."""

    def __init__(
        self,
        spec: TutorialSpec,
        root: str | Path = ".",
        config_path: str | Path = DEFAULT_CONFIG,
    ) -> None:
        """Create a tutorial project object.

        Args:
            spec: Parsed tutorial specification.
            root: Project root directory.
            config_path: Path to the tutorial
                YAML configuration file.
        """

        self.spec = spec
        self.root = Path(root)
        self.config_path = Path(config_path)

    @classmethod
    def load(cls, path: str | Path) -> "TutorialProject":
        """Load a tutorial project from a YAML specification.

        Args:
            path: Path to a tutorial YAML file.

        Returns:
            A ``TutorialProject`` rooted in the config
            file's parent directory.
        """

        config_path = Path(path)
        spec = TutorialSpec.load(config_path)
        return cls(
            spec,
            config_path.parent,
            config_path,
        )

    @classmethod
    def init(cls, path: str | Path = ".") -> "TutorialProject":
        """Create a minimal tutorial project skeleton.

        Args:
            path: Target directory for the new project.

        Returns:
            A ``TutorialProject`` with a ``minimal``
            template applied.
        """

        from .scaffold import ProjectScaffolder

        return ProjectScaffolder().scaffold(
            "minimal",
            Path(path),
        )

    @classmethod
    def init_from(
        cls,
        source: str | Path,
        target: str | Path | None = None,
    ) -> "TutorialProject":
        """Import an existing directory as a tutorial project.

        Args:
            source: Path to an existing directory containing
                notebooks and associated files.
            target: Optional target directory for the new
                tutorial project.

        Returns:
            A fully initialised ``TutorialProject``.
        """

        from .scaffold import ProjectImporter

        return ProjectImporter().scan(
            source,
            target,
        )

    @classmethod
    def init_from_url(
        cls,
        url: str,
        target: str | Path | None = None,
        remove_clone: bool = False,
    ) -> "TutorialProject":
        """Import a remote repository as a tutorial project.

        Args:
            url: Git-compatible clone URL.
            target: Optional target directory.
            remove_clone: If ``True``, delete the cloned
                repository after importing.

        Returns:
            A ``TutorialProject``.
        """

        from .scaffold import ProjectImporter

        return ProjectImporter().scan_url(
            url,
            target,
            remove_clone=remove_clone,
        )

    @classmethod
    def init_from_github(
        cls,
        org_repo: str,
        target: str | Path | None = None,
        remove_clone: bool = False,
    ) -> "TutorialProject":
        """Import a GitHub repository as a tutorial project.

        Args:
            org_repo: ``ORG/REPO`` shorthand.
            target: Optional target directory.
            remove_clone: If ``True``, delete the cloned
                repository after importing.

        Returns:
            A ``TutorialProject``.
        """

        from .scaffold import ProjectImporter

        return ProjectImporter().scan_github(
            org_repo,
            target,
            remove_clone=remove_clone,
        )

    def resolve(self) -> ResolvedTutorialProject:
        """Resolve the project content graph.

        Returns:
            A ``ResolvedTutorialProject`` with content
            and missing paths populated.
        """

        return TutorialResolver(
            self.spec,
            self.root,
        ).resolve(self.config_path)

    def validate(
        self,
        strict: bool = False,
        container: bool = False,
        image: str | None = None,
    ) -> ValidationReport:
        """Run configured validation checks.

        Args:
            strict: If ``True``, promote warnings to
                failures.
            container: If ``True``, include container
                runtime validation.
            image: Override image tag for container
                validation.

        Returns:
            Combined ``ValidationReport``.
        """

        reports = [
            AssetValidator(self.spec, self.root).validate(),
            NotebookValidator(self.spec, self.root).validate(),
            DependencyValidator(self.spec).validate(),
        ]
        if container:
            reports.append(
                ContainerValidator(
                    self.spec,
                    self.root,
                ).validate(image=image)
            )
        report = ValidationReport.combine(reports)
        if strict and report.warnings:
            report = report.model_copy(update={"passed": False})
        return report

    def inspect(self) -> str:
        """Return resolved tutorial metadata as JSON.

        Returns:
            Pretty-printed JSON string.
        """

        resolved = self.resolve()
        payload = self.spec.to_manifest_dict(image=resolved.image)
        payload["missing_paths"] = [
            str(path.relative_to(self.root)) for path in resolved.missing_paths
        ]
        return json.dumps(payload, indent=2) + "\n"

    def build(
        self,
        image: str | None = None,
        no_cache: bool | None = None,
        platform: str | None = None,
    ) -> BuildResult:
        """Generate a Dockerfile and build the container image.

        Args:
            image: Optional image tag override.
            no_cache: If ``True``, disable Docker
                layer caching.
            platform: Target platform (e.g.
                ``linux/amd64``).

        Returns:
            A ``BuildResult`` with the image tag and
            Dockerfile path.
        """

        return LocalBuilder(
            self.spec,
            self.root,
        ).build(
            image=image,
            no_cache=no_cache,
            platform=platform,
        )

    def run(
        self, image: str | None = None, port: int = 8888, shell: bool = False
    ) -> RunResult:
        """Run the tutorial container locally.

        Args:
            image: Optional image tag override.
            port: Host port to bind.
            shell: If ``True``, override entrypoint
                with an interactive shell.

        Returns:
            A ``RunResult`` with the container exit
            code.
        """

        return RuntimeLauncher(
            self.spec,
            self.root,
        ).run(
            image=image,
            port=port,
            shell=shell,
        )

__init__

__init__(spec: TutorialSpec, root: str | Path = '.', config_path: str | Path = DEFAULT_CONFIG) -> None

Create a tutorial project object.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
root str | Path

Project root directory.

'.'
config_path str | Path

Path to the tutorial YAML configuration file.

DEFAULT_CONFIG
Source code in src/tutorial_sdk/project.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def __init__(
    self,
    spec: TutorialSpec,
    root: str | Path = ".",
    config_path: str | Path = DEFAULT_CONFIG,
) -> None:
    """Create a tutorial project object.

    Args:
        spec: Parsed tutorial specification.
        root: Project root directory.
        config_path: Path to the tutorial
            YAML configuration file.
    """

    self.spec = spec
    self.root = Path(root)
    self.config_path = Path(config_path)

load classmethod

load(path: str | Path) -> TutorialProject

Load a tutorial project from a YAML specification.

Parameters:

Name Type Description Default
path str | Path

Path to a tutorial YAML file.

required

Returns:

Type Description
TutorialProject

A TutorialProject rooted in the config file's parent directory.

Source code in src/tutorial_sdk/project.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@classmethod
def load(cls, path: str | Path) -> "TutorialProject":
    """Load a tutorial project from a YAML specification.

    Args:
        path: Path to a tutorial YAML file.

    Returns:
        A ``TutorialProject`` rooted in the config
        file's parent directory.
    """

    config_path = Path(path)
    spec = TutorialSpec.load(config_path)
    return cls(
        spec,
        config_path.parent,
        config_path,
    )

init classmethod

init(path: str | Path = '.') -> TutorialProject

Create a minimal tutorial project skeleton.

Parameters:

Name Type Description Default
path str | Path

Target directory for the new project.

'.'

Returns:

Type Description
TutorialProject

A TutorialProject with a minimal template applied.

Source code in src/tutorial_sdk/project.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@classmethod
def init(cls, path: str | Path = ".") -> "TutorialProject":
    """Create a minimal tutorial project skeleton.

    Args:
        path: Target directory for the new project.

    Returns:
        A ``TutorialProject`` with a ``minimal``
        template applied.
    """

    from .scaffold import ProjectScaffolder

    return ProjectScaffolder().scaffold(
        "minimal",
        Path(path),
    )

init_from classmethod

init_from(source: str | Path, target: str | Path | None = None) -> TutorialProject

Import an existing directory as a tutorial project.

Parameters:

Name Type Description Default
source str | Path

Path to an existing directory containing notebooks and associated files.

required
target str | Path | None

Optional target directory for the new tutorial project.

None

Returns:

Type Description
TutorialProject

A fully initialised TutorialProject.

Source code in src/tutorial_sdk/project.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@classmethod
def init_from(
    cls,
    source: str | Path,
    target: str | Path | None = None,
) -> "TutorialProject":
    """Import an existing directory as a tutorial project.

    Args:
        source: Path to an existing directory containing
            notebooks and associated files.
        target: Optional target directory for the new
            tutorial project.

    Returns:
        A fully initialised ``TutorialProject``.
    """

    from .scaffold import ProjectImporter

    return ProjectImporter().scan(
        source,
        target,
    )

init_from_url classmethod

init_from_url(url: str, target: str | Path | None = None, remove_clone: bool = False) -> TutorialProject

Import a remote repository as a tutorial project.

Parameters:

Name Type Description Default
url str

Git-compatible clone URL.

required
target str | Path | None

Optional target directory.

None
remove_clone bool

If True, delete the cloned repository after importing.

False

Returns:

Type Description
TutorialProject

A TutorialProject.

Source code in src/tutorial_sdk/project.py
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
@classmethod
def init_from_url(
    cls,
    url: str,
    target: str | Path | None = None,
    remove_clone: bool = False,
) -> "TutorialProject":
    """Import a remote repository as a tutorial project.

    Args:
        url: Git-compatible clone URL.
        target: Optional target directory.
        remove_clone: If ``True``, delete the cloned
            repository after importing.

    Returns:
        A ``TutorialProject``.
    """

    from .scaffold import ProjectImporter

    return ProjectImporter().scan_url(
        url,
        target,
        remove_clone=remove_clone,
    )

init_from_github classmethod

init_from_github(org_repo: str, target: str | Path | None = None, remove_clone: bool = False) -> TutorialProject

Import a GitHub repository as a tutorial project.

Parameters:

Name Type Description Default
org_repo str

ORG/REPO shorthand.

required
target str | Path | None

Optional target directory.

None
remove_clone bool

If True, delete the cloned repository after importing.

False

Returns:

Type Description
TutorialProject

A TutorialProject.

Source code in src/tutorial_sdk/project.py
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
@classmethod
def init_from_github(
    cls,
    org_repo: str,
    target: str | Path | None = None,
    remove_clone: bool = False,
) -> "TutorialProject":
    """Import a GitHub repository as a tutorial project.

    Args:
        org_repo: ``ORG/REPO`` shorthand.
        target: Optional target directory.
        remove_clone: If ``True``, delete the cloned
            repository after importing.

    Returns:
        A ``TutorialProject``.
    """

    from .scaffold import ProjectImporter

    return ProjectImporter().scan_github(
        org_repo,
        target,
        remove_clone=remove_clone,
    )

resolve

resolve() -> ResolvedTutorialProject

Resolve the project content graph.

Returns:

Type Description
ResolvedTutorialProject

A ResolvedTutorialProject with content and missing paths populated.

Source code in src/tutorial_sdk/project.py
160
161
162
163
164
165
166
167
168
169
170
171
def resolve(self) -> ResolvedTutorialProject:
    """Resolve the project content graph.

    Returns:
        A ``ResolvedTutorialProject`` with content
        and missing paths populated.
    """

    return TutorialResolver(
        self.spec,
        self.root,
    ).resolve(self.config_path)

validate

validate(strict: bool = False, container: bool = False, image: str | None = None) -> ValidationReport

Run configured validation checks.

Parameters:

Name Type Description Default
strict bool

If True, promote warnings to failures.

False
container bool

If True, include container runtime validation.

False
image str | None

Override image tag for container validation.

None

Returns:

Type Description
ValidationReport

Combined ValidationReport.

Source code in src/tutorial_sdk/project.py
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
def validate(
    self,
    strict: bool = False,
    container: bool = False,
    image: str | None = None,
) -> ValidationReport:
    """Run configured validation checks.

    Args:
        strict: If ``True``, promote warnings to
            failures.
        container: If ``True``, include container
            runtime validation.
        image: Override image tag for container
            validation.

    Returns:
        Combined ``ValidationReport``.
    """

    reports = [
        AssetValidator(self.spec, self.root).validate(),
        NotebookValidator(self.spec, self.root).validate(),
        DependencyValidator(self.spec).validate(),
    ]
    if container:
        reports.append(
            ContainerValidator(
                self.spec,
                self.root,
            ).validate(image=image)
        )
    report = ValidationReport.combine(reports)
    if strict and report.warnings:
        report = report.model_copy(update={"passed": False})
    return report

inspect

inspect() -> str

Return resolved tutorial metadata as JSON.

Returns:

Type Description
str

Pretty-printed JSON string.

Source code in src/tutorial_sdk/project.py
210
211
212
213
214
215
216
217
218
219
220
221
222
def inspect(self) -> str:
    """Return resolved tutorial metadata as JSON.

    Returns:
        Pretty-printed JSON string.
    """

    resolved = self.resolve()
    payload = self.spec.to_manifest_dict(image=resolved.image)
    payload["missing_paths"] = [
        str(path.relative_to(self.root)) for path in resolved.missing_paths
    ]
    return json.dumps(payload, indent=2) + "\n"

build

build(image: str | None = None, no_cache: bool | None = None, platform: str | None = None) -> BuildResult

Generate a Dockerfile and build the container image.

Parameters:

Name Type Description Default
image str | None

Optional image tag override.

None
no_cache bool | None

If True, disable Docker layer caching.

None
platform str | None

Target platform (e.g. linux/amd64).

None

Returns:

Type Description
BuildResult

A BuildResult with the image tag and Dockerfile path.

Source code in src/tutorial_sdk/project.py
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
def build(
    self,
    image: str | None = None,
    no_cache: bool | None = None,
    platform: str | None = None,
) -> BuildResult:
    """Generate a Dockerfile and build the container image.

    Args:
        image: Optional image tag override.
        no_cache: If ``True``, disable Docker
            layer caching.
        platform: Target platform (e.g.
            ``linux/amd64``).

    Returns:
        A ``BuildResult`` with the image tag and
        Dockerfile path.
    """

    return LocalBuilder(
        self.spec,
        self.root,
    ).build(
        image=image,
        no_cache=no_cache,
        platform=platform,
    )

run

run(image: str | None = None, port: int = 8888, shell: bool = False) -> RunResult

Run the tutorial container locally.

Parameters:

Name Type Description Default
image str | None

Optional image tag override.

None
port int

Host port to bind.

8888
shell bool

If True, override entrypoint with an interactive shell.

False

Returns:

Type Description
RunResult

A RunResult with the container exit code.

Source code in src/tutorial_sdk/project.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def run(
    self, image: str | None = None, port: int = 8888, shell: bool = False
) -> RunResult:
    """Run the tutorial container locally.

    Args:
        image: Optional image tag override.
        port: Host port to bind.
        shell: If ``True``, override entrypoint
            with an interactive shell.

    Returns:
        A ``RunResult`` with the container exit
        code.
    """

    return RuntimeLauncher(
        self.spec,
        self.root,
    ).run(
        image=image,
        port=port,
        shell=shell,
    )

tutorial_sdk.resolver.ResolvedTutorialProject dataclass

A specification with project-relative paths resolved.

Source code in src/tutorial_sdk/resolver.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@dataclass(frozen=True)
class ResolvedTutorialProject:
    """A specification with project-relative paths resolved."""

    spec: TutorialSpec
    root: Path
    config_path: Path
    content_paths: tuple[Path, ...]
    missing_paths: tuple[Path, ...]

    @property
    def image(self) -> str:
        """Return the configured or default image tag."""

        return self.spec.build.image or f"{self.spec.name}:latest"

image property

image: str

Return the configured or default image tag.

tutorial_sdk.resolver.TutorialResolver

Resolve content and generated artifact paths.

Source code in src/tutorial_sdk/resolver.py
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
class TutorialResolver:
    """Resolve content and generated artifact paths."""

    def __init__(self, spec: TutorialSpec, root: str | Path) -> None:
        """Create a resolver.

        Args:
            spec: Parsed tutorial specification.
            root: Tutorial project root directory.
        """

        self.spec = spec
        self.root = Path(root)

    def resolve(
        self,
        config_path: str | Path = DEFAULT_CONFIG,
    ) -> ResolvedTutorialProject:
        """Resolve declared content files.

        Args:
            config_path: Path to the configuration file
                associated with this project.

        Returns:
            A ``ResolvedTutorialProject`` containing
            absolute content paths and missing path details.
        """

        content_paths = tuple(
            self.root / path for path in self.spec.content.all_paths()
        )
        missing_paths = tuple(
            path for path in content_paths if not path.exists()
        )
        return ResolvedTutorialProject(
            spec=self.spec,
            root=self.root,
            config_path=Path(config_path),
            content_paths=content_paths,
            missing_paths=missing_paths,
        )

__init__

__init__(spec: TutorialSpec, root: str | Path) -> None

Create a resolver.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
root str | Path

Tutorial project root directory.

required
Source code in src/tutorial_sdk/resolver.py
30
31
32
33
34
35
36
37
38
39
def __init__(self, spec: TutorialSpec, root: str | Path) -> None:
    """Create a resolver.

    Args:
        spec: Parsed tutorial specification.
        root: Tutorial project root directory.
    """

    self.spec = spec
    self.root = Path(root)

resolve

resolve(config_path: str | Path = DEFAULT_CONFIG) -> ResolvedTutorialProject

Resolve declared content files.

Parameters:

Name Type Description Default
config_path str | Path

Path to the configuration file associated with this project.

DEFAULT_CONFIG

Returns:

Type Description
ResolvedTutorialProject

A ResolvedTutorialProject containing absolute content paths and missing path details.

Source code in src/tutorial_sdk/resolver.py
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
def resolve(
    self,
    config_path: str | Path = DEFAULT_CONFIG,
) -> ResolvedTutorialProject:
    """Resolve declared content files.

    Args:
        config_path: Path to the configuration file
            associated with this project.

    Returns:
        A ``ResolvedTutorialProject`` containing
        absolute content paths and missing path details.
    """

    content_paths = tuple(
        self.root / path for path in self.spec.content.all_paths()
    )
    missing_paths = tuple(
        path for path in content_paths if not path.exists()
    )
    return ResolvedTutorialProject(
        spec=self.spec,
        root=self.root,
        config_path=Path(config_path),
        content_paths=content_paths,
        missing_paths=missing_paths,
    )

Specification Models

tutorial_sdk.spec.TutorialSpec

Bases: BaseModel

Source-of-truth tutorial specification.

Source code in src/tutorial_sdk/spec.py
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
class TutorialSpec(BaseModel):
    """Source-of-truth tutorial specification."""

    model_config = ConfigDict(extra="forbid")

    name: str
    version: str = "0.1.0"
    title: str | None = None
    description: str = ""
    authors: list[AuthorSpec] = Field(default_factory=list)
    license: str | None = None
    runtime: RuntimeSpec = Field(default_factory=RuntimeSpec)
    dependencies: DependencySpec = Field(default_factory=DependencySpec)
    content: ContentSpec = Field(default_factory=ContentSpec)
    build: BuildSpec = Field(default_factory=BuildSpec)
    validation: ValidationSpec = Field(default_factory=ValidationSpec)
    entrypoint: EntrypointSpec = Field(default_factory=EntrypointSpec)

    @field_validator("name")
    @classmethod
    def validate_name(
        cls,
        value: str,
    ) -> str:
        """Validate the spec name used for files and image tags."""

        cleaned = value.strip()
        if not cleaned:
            raise ValueError("name must not be empty")
        return cleaned

    @property
    def display_title(self) -> str:
        """Return the title exposed in generated metadata."""

        return self.title or self.name

    @classmethod
    def load(cls, path: str | Path) -> "TutorialSpec":
        """Load a tutorial specification from YAML.

        Args:
            path: Path to a tutorial YAML file.

        Returns:
            Parsed tutorial specification.

        Raises:
            ConfigError: If the file cannot be read or validated.
        """

        spec_path = Path(path)
        try:
            raw = yaml.safe_load(spec_path.read_text()) or {}
        except OSError as exc:
            raise ConfigError(f"Unable to read {spec_path}: {exc}") from exc
        except yaml.YAMLError as exc:
            raise ConfigError(f"Unable to parse {spec_path}: {exc}") from exc

        try:
            return cls.model_validate(raw)
        except ValueError as exc:
            raise ConfigError(str(exc)) from exc

    def write(self, path: str | Path) -> None:
        """Write this specification as YAML.

        Args:
            path: Destination file path.
        """

        spec_path = Path(path)
        data = self.model_dump(mode="json", exclude_none=True)
        spec_path.write_text(yaml.safe_dump(data, sort_keys=False))

    def to_manifest_dict(
        self,
        image: str | None = None,
    ) -> dict[str, Any]:
        """Return the reproducibility manifest payload.

        Args:
            image: Override image tag.  Falls back to
                the build spec's configured image.

        Returns:
            Dictionary suitable for JSON serialisation.
        """

        return {
            "name": self.name,
            "version": self.version,
            "title": self.display_title,
            "description": self.description,
            "base_image": self.build.base_image,
            "image": image or self.build.image,
            "runtime": self.runtime.model_dump(mode="json"),
            "content": self.content.model_dump(mode="json"),
            "dependencies": self.dependencies.model_dump(mode="json"),
            "entrypoint": self.entrypoint.model_dump(mode="json"),
        }

display_title property

display_title: str

Return the title exposed in generated metadata.

validate_name classmethod

validate_name(value: str) -> str

Validate the spec name used for files and image tags.

Source code in src/tutorial_sdk/spec.py
138
139
140
141
142
143
144
145
146
147
148
149
@field_validator("name")
@classmethod
def validate_name(
    cls,
    value: str,
) -> str:
    """Validate the spec name used for files and image tags."""

    cleaned = value.strip()
    if not cleaned:
        raise ValueError("name must not be empty")
    return cleaned

load classmethod

load(path: str | Path) -> TutorialSpec

Load a tutorial specification from YAML.

Parameters:

Name Type Description Default
path str | Path

Path to a tutorial YAML file.

required

Returns:

Type Description
TutorialSpec

Parsed tutorial specification.

Raises:

Type Description
ConfigError

If the file cannot be read or validated.

Source code in src/tutorial_sdk/spec.py
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
@classmethod
def load(cls, path: str | Path) -> "TutorialSpec":
    """Load a tutorial specification from YAML.

    Args:
        path: Path to a tutorial YAML file.

    Returns:
        Parsed tutorial specification.

    Raises:
        ConfigError: If the file cannot be read or validated.
    """

    spec_path = Path(path)
    try:
        raw = yaml.safe_load(spec_path.read_text()) or {}
    except OSError as exc:
        raise ConfigError(f"Unable to read {spec_path}: {exc}") from exc
    except yaml.YAMLError as exc:
        raise ConfigError(f"Unable to parse {spec_path}: {exc}") from exc

    try:
        return cls.model_validate(raw)
    except ValueError as exc:
        raise ConfigError(str(exc)) from exc

write

write(path: str | Path) -> None

Write this specification as YAML.

Parameters:

Name Type Description Default
path str | Path

Destination file path.

required
Source code in src/tutorial_sdk/spec.py
184
185
186
187
188
189
190
191
192
193
def write(self, path: str | Path) -> None:
    """Write this specification as YAML.

    Args:
        path: Destination file path.
    """

    spec_path = Path(path)
    data = self.model_dump(mode="json", exclude_none=True)
    spec_path.write_text(yaml.safe_dump(data, sort_keys=False))

to_manifest_dict

to_manifest_dict(image: str | None = None) -> dict[str, Any]

Return the reproducibility manifest payload.

Parameters:

Name Type Description Default
image str | None

Override image tag. Falls back to the build spec's configured image.

None

Returns:

Type Description
dict[str, Any]

Dictionary suitable for JSON serialisation.

Source code in src/tutorial_sdk/spec.py
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
def to_manifest_dict(
    self,
    image: str | None = None,
) -> dict[str, Any]:
    """Return the reproducibility manifest payload.

    Args:
        image: Override image tag.  Falls back to
            the build spec's configured image.

    Returns:
        Dictionary suitable for JSON serialisation.
    """

    return {
        "name": self.name,
        "version": self.version,
        "title": self.display_title,
        "description": self.description,
        "base_image": self.build.base_image,
        "image": image or self.build.image,
        "runtime": self.runtime.model_dump(mode="json"),
        "content": self.content.model_dump(mode="json"),
        "dependencies": self.dependencies.model_dump(mode="json"),
        "entrypoint": self.entrypoint.model_dump(mode="json"),
    }

tutorial_sdk.spec.AuthorSpec

Bases: BaseModel

Tutorial author metadata.

Source code in src/tutorial_sdk/spec.py
14
15
16
17
18
19
20
class AuthorSpec(BaseModel):
    """Tutorial author metadata."""

    model_config = ConfigDict(extra="forbid")

    name: str
    email: str | None = None

tutorial_sdk.spec.RuntimeSpec

Bases: BaseModel

Runtime configuration for a tutorial environment.

Source code in src/tutorial_sdk/spec.py
23
24
25
26
27
28
29
30
31
32
class RuntimeSpec(BaseModel):
    """Runtime configuration for a tutorial environment."""

    model_config = ConfigDict(extra="forbid")

    language: str = "python"
    python: str = _PYTHON_VERSION_STR
    kernel: str = "python3"
    jupyterlab: bool = True
    expose_port: int = 8888

tutorial_sdk.spec.DependencySpec

Bases: BaseModel

Package dependencies declared by package manager.

Source code in src/tutorial_sdk/spec.py
35
36
37
38
39
40
41
42
43
class DependencySpec(BaseModel):
    """Package dependencies declared by package manager."""

    model_config = ConfigDict(extra="forbid")

    apt: list[str] = Field(default_factory=list)
    pip: list[str] = Field(default_factory=list)
    conda: list[str] = Field(default_factory=list)
    local: list[str] = Field(default_factory=list)

tutorial_sdk.spec.ContentSpec

Bases: BaseModel

Tutorial content assets copied into the image.

Source code in src/tutorial_sdk/spec.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class ContentSpec(BaseModel):
    """Tutorial content assets copied into the image."""

    model_config = ConfigDict(extra="forbid")

    notebooks: list[str] = Field(default_factory=list)
    scripts: list[str] = Field(default_factory=list)
    data: list[str] = Field(default_factory=list)
    docs: list[str] = Field(default_factory=list)
    exercises: list[str] = Field(default_factory=list)
    solutions: list[str] = Field(default_factory=list)

    def all_paths(self) -> list[str]:
        """Return every declared content path in stable order."""

        return [
            *self.notebooks,
            *self.scripts,
            *self.data,
            *self.docs,
            *self.exercises,
            *self.solutions,
        ]

all_paths

all_paths() -> list[str]

Return every declared content path in stable order.

Source code in src/tutorial_sdk/spec.py
58
59
60
61
62
63
64
65
66
67
68
def all_paths(self) -> list[str]:
    """Return every declared content path in stable order."""

    return [
        *self.notebooks,
        *self.scripts,
        *self.data,
        *self.docs,
        *self.exercises,
        *self.solutions,
    ]

tutorial_sdk.spec.DockerfileSections

Bases: BaseModel

Optional user-managed Dockerfile snippets.

Source code in src/tutorial_sdk/spec.py
71
72
73
74
75
76
77
78
class DockerfileSections(BaseModel):
    """Optional user-managed Dockerfile snippets."""

    model_config = ConfigDict(extra="forbid")

    before_dependencies: str | None = None
    after_dependencies: str | None = None
    before_entrypoint: str | None = None

tutorial_sdk.spec.BuildSpec

Bases: BaseModel

Build artifact and container image configuration.

Source code in src/tutorial_sdk/spec.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
class BuildSpec(BaseModel):
    """Build artifact and container image configuration."""

    model_config = ConfigDict(extra="forbid")

    dockerfile: str = "Dockerfile"
    image: str | None = None
    base_image: str = f"python:{_PYTHON_VERSION_STR}-slim"
    copy_repo: bool = True
    preexecute_notebooks: bool = False
    export_devcontainer: bool = False
    export_manifest: bool = True
    cache: bool = True
    custom_sections: DockerfileSections = Field(
        default_factory=DockerfileSections
    )

tutorial_sdk.spec.ValidationSpec

Bases: BaseModel

Validation checks enabled for a tutorial.

Source code in src/tutorial_sdk/spec.py
 99
100
101
102
103
104
105
106
107
class ValidationSpec(BaseModel):
    """Validation checks enabled for a tutorial."""

    model_config = ConfigDict(extra="forbid")

    execute_notebooks: bool = False
    check_imports: bool = True
    check_links: bool = True
    require_clean_execution: bool = True

tutorial_sdk.spec.EntrypointSpec

Bases: BaseModel

Default runtime entrypoint.

Source code in src/tutorial_sdk/spec.py
110
111
112
113
114
115
116
117
class EntrypointSpec(BaseModel):
    """Default runtime entrypoint."""

    model_config = ConfigDict(extra="forbid")

    kind: Literal["jupyterlab", "shell", "command"] = "jupyterlab"
    default_notebook: str | None = None
    command: list[str] | None = None

Configuration Loading

tutorial_sdk.config.load_config

load_config(path: str | Path = DEFAULT_CONFIG) -> TutorialSpec

Load a tutorial specification from disk.

Parameters:

Name Type Description Default
path str | Path

Path to the YAML configuration.

DEFAULT_CONFIG

Returns:

Type Description
TutorialSpec

Parsed tutorial specification.

Source code in src/tutorial_sdk/config.py
11
12
13
14
15
16
17
18
19
20
21
def load_config(path: str | Path = DEFAULT_CONFIG) -> TutorialSpec:
    """Load a tutorial specification from disk.

    Args:
        path: Path to the YAML configuration.

    Returns:
        Parsed tutorial specification.
    """

    return TutorialSpec.load(path)

Scaffold & Import

tutorial_sdk.scaffold.templates.ProjectScaffolder

Create starter tutorial projects.

The scaffolder writes a named template directory, creates a default tutorial YAML configuration file, and returns a loaded TutorialProject.

Source code in src/tutorial_sdk/scaffold/templates.py
 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
class ProjectScaffolder:
    """Create starter tutorial projects.

    The scaffolder writes a named template directory,
    creates a default tutorial YAML configuration file,
    and returns a loaded ``TutorialProject``.
    """

    SUPPORTED = set(_TEMPLATE_CONFIGS)

    def scaffold(
        self,
        template: str,
        path: str | Path,
        name: str | None = None,
    ) -> TutorialProject:
        """Create a tutorial project from a template.

        Args:
            template: Template name (one of
                :attr:`SUPPORTED`).
            path: Target directory for the project.
            name: Optional project name override.
                Defaults to the directory basename.

        Returns:
            A fully initialised ``TutorialProject``.

        Raises:
            ScaffoldError: If *template* is not
                recognised.
        """

        from ..project import TutorialProject

        if template not in self.SUPPORTED:
            raise ScaffoldError(f"Unknown template: {template}")

        cfg = _TEMPLATE_CONFIGS[template]
        root = Path(path)
        root.mkdir(parents=True, exist_ok=True)
        project_name = name or root.name or "my-tutorial"

        # Create directories.
        for dirname in cfg.get("dirs", []):
            (root / dirname).mkdir(
                parents=True,
                exist_ok=True,
            )
        (root / "docs").mkdir(exist_ok=True)

        # Create README.
        readme = root / "README.md"
        if not readme.exists():
            readme.write_text(f"# {project_name}\n")

        # Create notebook stubs.
        all_notebooks = (
            list(cfg.get("notebooks", []))
            + list(cfg.get("exercises", []))
            + list(cfg.get("solutions", []))
        )
        for nb_path in all_notebooks:
            nb_file = root / nb_path
            nb_file.parent.mkdir(
                parents=True,
                exist_ok=True,
            )
            if not nb_file.exists():
                nb_file.write_text(
                    _EMPTY_NOTEBOOK,
                )

        # Determine default notebook for entrypoint.
        first_notebook = cfg["notebooks"][0] if cfg.get("notebooks") else None

        build_overrides = cfg.get("build", {})
        validation_overrides = cfg.get(
            "validation",
            {},
        )

        spec = TutorialSpec(
            name=project_name,
            title=project_name.replace("-", " ").title(),
            description=str(cfg["description"]),
            runtime=RuntimeSpec(),
            dependencies=DependencySpec(
                pip=list(cfg.get("pip", [])),
            ),
            content=ContentSpec(
                notebooks=list(
                    cfg.get("notebooks", []),
                ),
                exercises=list(
                    cfg.get("exercises", []),
                ),
                solutions=list(
                    cfg.get("solutions", []),
                ),
                docs=["README.md"],
            ),
            build=BuildSpec(**build_overrides),
            validation=ValidationSpec(
                **validation_overrides,
            ),
            entrypoint=EntrypointSpec(
                kind="jupyterlab",
                default_notebook=first_notebook,
            ),
        )
        config_path = root / DEFAULT_CONFIG
        if not config_path.exists():
            spec.write(config_path)
        return TutorialProject(spec, root, config_path)

scaffold

scaffold(template: str, path: str | Path, name: str | None = None) -> TutorialProject

Create a tutorial project from a template.

Parameters:

Name Type Description Default
template str

Template name (one of :attr:SUPPORTED).

required
path str | Path

Target directory for the project.

required
name str | None

Optional project name override. Defaults to the directory basename.

None

Returns:

Type Description
TutorialProject

A fully initialised TutorialProject.

Raises:

Type Description
ScaffoldError

If template is not recognised.

Source code in src/tutorial_sdk/scaffold/templates.py
 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
def scaffold(
    self,
    template: str,
    path: str | Path,
    name: str | None = None,
) -> TutorialProject:
    """Create a tutorial project from a template.

    Args:
        template: Template name (one of
            :attr:`SUPPORTED`).
        path: Target directory for the project.
        name: Optional project name override.
            Defaults to the directory basename.

    Returns:
        A fully initialised ``TutorialProject``.

    Raises:
        ScaffoldError: If *template* is not
            recognised.
    """

    from ..project import TutorialProject

    if template not in self.SUPPORTED:
        raise ScaffoldError(f"Unknown template: {template}")

    cfg = _TEMPLATE_CONFIGS[template]
    root = Path(path)
    root.mkdir(parents=True, exist_ok=True)
    project_name = name or root.name or "my-tutorial"

    # Create directories.
    for dirname in cfg.get("dirs", []):
        (root / dirname).mkdir(
            parents=True,
            exist_ok=True,
        )
    (root / "docs").mkdir(exist_ok=True)

    # Create README.
    readme = root / "README.md"
    if not readme.exists():
        readme.write_text(f"# {project_name}\n")

    # Create notebook stubs.
    all_notebooks = (
        list(cfg.get("notebooks", []))
        + list(cfg.get("exercises", []))
        + list(cfg.get("solutions", []))
    )
    for nb_path in all_notebooks:
        nb_file = root / nb_path
        nb_file.parent.mkdir(
            parents=True,
            exist_ok=True,
        )
        if not nb_file.exists():
            nb_file.write_text(
                _EMPTY_NOTEBOOK,
            )

    # Determine default notebook for entrypoint.
    first_notebook = cfg["notebooks"][0] if cfg.get("notebooks") else None

    build_overrides = cfg.get("build", {})
    validation_overrides = cfg.get(
        "validation",
        {},
    )

    spec = TutorialSpec(
        name=project_name,
        title=project_name.replace("-", " ").title(),
        description=str(cfg["description"]),
        runtime=RuntimeSpec(),
        dependencies=DependencySpec(
            pip=list(cfg.get("pip", [])),
        ),
        content=ContentSpec(
            notebooks=list(
                cfg.get("notebooks", []),
            ),
            exercises=list(
                cfg.get("exercises", []),
            ),
            solutions=list(
                cfg.get("solutions", []),
            ),
            docs=["README.md"],
        ),
        build=BuildSpec(**build_overrides),
        validation=ValidationSpec(
            **validation_overrides,
        ),
        entrypoint=EntrypointSpec(
            kind="jupyterlab",
            default_notebook=first_notebook,
        ),
    )
    config_path = root / DEFAULT_CONFIG
    if not config_path.exists():
        spec.write(config_path)
    return TutorialProject(spec, root, config_path)

tutorial_sdk.scaffold.importer.ProjectImporter

Discover and import an existing project as a tutorial.

Importing copies discovered notebooks and related assets into a target directory, detects Python dependencies, and writes a populated tutorial YAML configuration file.

Source code in src/tutorial_sdk/scaffold/importer.py
 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
class ProjectImporter:
    """Discover and import an existing project as a tutorial.

    Importing copies discovered notebooks and related assets into a target
    directory, detects Python dependencies, and writes a populated
    tutorial YAML configuration file.
    """

    def scan(
        self,
        source: str | Path,
        target: str | Path | None = None,
    ) -> TutorialProject:
        """Scan *source* and create a tutorial project at *target*.

        Args:
            source: Path to an existing directory containing
                notebooks and associated files.
            target: Optional target directory for the new
                tutorial project.  Defaults to
                ``{source.name}_tutorial`` next to *source*.

        Returns:
            A fully initialised ``TutorialProject``.

        Raises:
            ScaffoldError: If *source* does not exist or
                contains no notebooks.
        """

        from ..project import TutorialProject

        source = Path(source).resolve()
        if not source.is_dir():
            raise ScaffoldError(f"Source directory does not exist: {source}")

        # Determine target directory.
        if target is None:
            target = source.parent / f"{source.name}_tutorial"
        target = Path(target).resolve()

        # If default config file already exists in target,
        # validate it and report rather than overwriting.
        config_path = target / DEFAULT_CONFIG
        if config_path.exists():
            return self._validate_existing(
                config_path,
                target,
            )

        # Discover content from source.
        discovery = self._discover(source)

        if not discovery["notebooks"]:
            raise ScaffoldError(f"No Jupyter notebooks found in {source}")

        # Derive project name from source directory name.
        project_name = source.name.replace(" ", "-").lower()

        # Detect Python version.
        python_version = _detect_python_version(source)

        # Build the spec.
        spec = self._build_spec(
            project_name,
            discovery,
            python_version,
        )

        # Create target directory and copy files.
        target.mkdir(parents=True, exist_ok=True)
        copied_paths = self._copy_files(
            source,
            target,
            discovery,
        )

        # Write default config file (tutorial YAML file).
        spec = self._rewrite_paths(spec, copied_paths)
        spec.write(config_path)

        # Create README if missing.
        readme = target / "README.md"
        if not readme.exists():
            readme.write_text(f"# {spec.display_title}\n\n{spec.description}\n")

        # Print summary.
        self._print_summary(spec, discovery, target)

        return TutorialProject(spec, target, config_path)

    def scan_url(
        self,
        url: str,
        target: str | Path | None = None,
        remove_clone: bool = False,
    ) -> TutorialProject:
        """Clone a remote repository and scan it.

        Args:
            url: Git-compatible clone URL.
            target: Optional target directory for the project.
            remove_clone: If ``True``, delete the cloned
                repository after importing.  When ``False``
                (the default), the clone is kept for
                inspection.

        Returns:
            A ``TutorialProject`` imported from the clone.
        """

        # Derive repo name from URL.
        repo_name = url.rstrip("/").rsplit("/", 1)[-1].removesuffix(".git")

        if target is None:
            target = Path.cwd() / f"{repo_name}_tutorial"
        target = Path(target).resolve()

        # Clone into a sibling directory of the target.
        clone_dir = target.parent / repo_name
        if clone_dir.exists():
            print(f"Clone directory already exists: {clone_dir}")
        else:
            try:
                subprocess.run(
                    ["git", "clone", "--depth", "1", url, str(clone_dir)],
                    capture_output=True,
                    text=True,
                    check=True,
                )
            except FileNotFoundError:
                raise ScaffoldError(
                    "git is required for --url / --github "
                    "but was not found on PATH."
                )
            except subprocess.CalledProcessError as exc:
                raise ScaffoldError(
                    f"Failed to clone {url}: {exc.stderr.strip()}"
                )

        try:
            result = self.scan(clone_dir, target)
        finally:
            if remove_clone and clone_dir.exists():
                shutil.rmtree(clone_dir)
                print(f"Removed clone: {clone_dir}")

        if not remove_clone:
            print(
                f"Clone kept at: {clone_dir}\n"
                f"  Use --remove-clone to delete it "
                f"after import."
            )

        return result

    def scan_github(
        self,
        org_repo: str,
        target: str | Path | None = None,
        remove_clone: bool = False,
    ) -> TutorialProject:
        """Import a GitHub repository.

        Args:
            org_repo: ``ORG/REPO`` shorthand.
            target: Optional target directory.
            remove_clone: If ``True``, delete the cloned
                repository after importing.

        Returns:
            A ``TutorialProject``.
        """

        url = f"https://github.com/{org_repo}.git"
        return self.scan_url(
            url,
            target,
            remove_clone=remove_clone,
        )

    # ---- discovery helpers ----

    def _discover(
        self,
        source: Path,
    ) -> dict[str, list[str]]:
        """Walk *source* and classify files."""

        notebooks: list[str] = []
        notebook_dirs: set[Path] = set()

        # Step 1: find all notebooks.
        for nb in sorted(source.rglob("*.ipynb")):
            # Skip checkpoint directories.
            if ".ipynb_checkpoints" in nb.parts:
                continue
            rel = str(nb.relative_to(source))
            notebooks.append(rel)
            notebook_dirs.add(nb.parent)

        # Step 2: discover scripts, data, docs scoped to
        # notebook directories and their subdirectories.
        scripts: list[str] = []
        data: list[str] = []
        docs: list[str] = []

        # Expand notebook_dirs to include all subdirectories.
        search_dirs = set(notebook_dirs)
        for nd in list(notebook_dirs):
            for child in nd.rglob("*"):
                if child.is_dir():
                    search_dirs.add(child)

        # Also include subdirs named 'data', 'docs', 'src',
        # 'scripts' if they live under notebook dirs.
        for d in sorted(search_dirs):
            for item in sorted(d.iterdir()):
                if not item.is_file():
                    continue
                if ".ipynb_checkpoints" in item.parts:
                    continue
                rel = str(item.relative_to(source))
                suffix = item.suffix.lower()
                if suffix == ".py":
                    scripts.append(rel)
                elif suffix in _DATA_EXTENSIONS:
                    data.append(rel)
                elif suffix in _DOC_EXTENSIONS and item.name != DEFAULT_CONFIG:
                    docs.append(rel)

        # Also pick up top-level README.
        for name in ("README.md", "README.rst", "README.txt"):
            readme = source / name
            if readme.exists():
                rel = str(readme.relative_to(source))
                if rel not in docs:
                    docs.insert(0, rel)

        # Step 3: extract dependencies.
        pip_deps = _extract_dependencies(
            source,
            notebooks,
        )

        return {
            "notebooks": notebooks,
            "scripts": scripts,
            "data": data,
            "docs": docs,
            "pip": sorted(pip_deps),
        }

    # ---- conflict handling ----

    def _validate_existing(
        self,
        config_path: Path,
        root: Path,
    ) -> TutorialProject:
        """Validate an existing default config file."""

        from ..project import TutorialProject

        try:
            spec = TutorialSpec.load(config_path)
        except ConfigError as exc:
            raise ScaffoldError(
                f"Existing {DEFAULT_CONFIG} at {config_path} "
                f"is invalid: {exc}\n"
                f"Fix or remove it before re-importing."
            )
        print(
            f"Found existing {DEFAULT_CONFIG} at "
            f"{config_path}\n"
            f"  Project: {spec.name} "
            f"(v{spec.version})\n"
            f"  Notebooks: "
            f"{len(spec.content.notebooks)}\n"
            f"  Dependencies: "
            f"{len(spec.dependencies.pip)} pip\n"
            f"Validation passed — no changes made."
        )
        return TutorialProject(spec, root, config_path)

    # ---- file organisation ----

    def _copy_files(
        self,
        source: Path,
        target: Path,
        discovery: dict[str, list[str]],
    ) -> dict[str, str]:
        """Copy discovered files into the target.

        Returns a mapping from original relative path to the
        new relative path inside *target*.
        """

        mapping: dict[str, str] = {}

        # Copy notebooks, preserving their relative structure.
        for nb in discovery["notebooks"]:
            src = source / nb
            dst = target / nb
            dst.parent.mkdir(parents=True, exist_ok=True)
            if not dst.exists():
                shutil.copy2(src, dst)
            mapping[nb] = nb

        # Copy scripts.
        for sc in discovery["scripts"]:
            src = source / sc
            dst = target / sc
            dst.parent.mkdir(parents=True, exist_ok=True)
            if not dst.exists():
                shutil.copy2(src, dst)
            mapping[sc] = sc

        # Copy data files.
        for df in discovery["data"]:
            src = source / df
            dst = target / df
            dst.parent.mkdir(parents=True, exist_ok=True)
            if not dst.exists():
                shutil.copy2(src, dst)
            mapping[df] = df

        # Copy docs.
        for doc in discovery["docs"]:
            src = source / doc
            dst = target / doc
            dst.parent.mkdir(parents=True, exist_ok=True)
            if not dst.exists():
                shutil.copy2(src, dst)
            mapping[doc] = doc

        return mapping

    def _rewrite_paths(
        self,
        spec: TutorialSpec,
        mapping: dict[str, str],
    ) -> TutorialSpec:
        """Update spec paths to match the copied layout."""

        # Currently paths are preserved, so this is a no-op,
        # but it provides a hook for future reorganisation.
        return spec

    def _build_spec(
        self,
        name: str,
        discovery: dict[str, list[str]],
        python_version: str,
    ) -> TutorialSpec:
        """Build a TutorialSpec from discovered content."""

        first_nb = discovery["notebooks"][0] if discovery["notebooks"] else None

        return TutorialSpec(
            name=name,
            title=name.replace("-", " ").replace("_", " ").title(),
            description=(
                f"Tutorial project imported from existing "
                f"repository ({len(discovery['notebooks'])} "
                f"notebook(s) discovered)."
            ),
            runtime=RuntimeSpec(python=python_version),
            dependencies=DependencySpec(
                pip=discovery["pip"],
            ),
            content=ContentSpec(
                notebooks=discovery["notebooks"],
                scripts=discovery["scripts"],
                data=discovery["data"],
                docs=discovery["docs"],
            ),
            build=BuildSpec(),
            validation=ValidationSpec(),
            entrypoint=EntrypointSpec(
                kind="jupyterlab",
                default_notebook=first_nb,
            ),
        )

    def _print_summary(
        self,
        spec: TutorialSpec,
        discovery: dict[str, list[str]],
        target: Path,
    ) -> None:
        """Print a human-readable import summary."""

        print(f"Imported project: {spec.display_title}")
        print(f"  Target: {target}")
        print(f"  Notebooks: {len(discovery['notebooks'])}")
        if discovery["scripts"]:
            print(f"  Scripts:   {len(discovery['scripts'])}")
        if discovery["data"]:
            print(f"  Data:      {len(discovery['data'])}")
        if discovery["docs"]:
            print(f"  Docs:      {len(discovery['docs'])}")
        print(f"  Pip deps:  {len(discovery['pip'])}")
        if discovery["pip"]:
            print(
                f"    {', '.join(discovery['pip'][:10])}"
                + (
                    f" (+{len(discovery['pip']) - 10} more)"
                    if len(discovery["pip"]) > 10
                    else ""
                )
            )
        print(f"  Python:    {spec.runtime.python}")
        print(f"  Config:    {target / DEFAULT_CONFIG}")
        print(
            "\nWARNING: Some Python packages may require system-level "
            "compilation tools (e.g. gcc) to build from source.\n"
            f"If the installation fails, manually add required packages "
            f"(like 'build-essential' and/or 'python3-dev') to the "
            f"'apt' list in the '{DEFAULT_CONFIG}' file."
        )

scan

scan(source: str | Path, target: str | Path | None = None) -> TutorialProject

Scan source and create a tutorial project at target.

Parameters:

Name Type Description Default
source str | Path

Path to an existing directory containing notebooks and associated files.

required
target str | Path | None

Optional target directory for the new tutorial project. Defaults to {source.name}_tutorial next to source.

None

Returns:

Type Description
TutorialProject

A fully initialised TutorialProject.

Raises:

Type Description
ScaffoldError

If source does not exist or contains no notebooks.

Source code in src/tutorial_sdk/scaffold/importer.py
 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
def scan(
    self,
    source: str | Path,
    target: str | Path | None = None,
) -> TutorialProject:
    """Scan *source* and create a tutorial project at *target*.

    Args:
        source: Path to an existing directory containing
            notebooks and associated files.
        target: Optional target directory for the new
            tutorial project.  Defaults to
            ``{source.name}_tutorial`` next to *source*.

    Returns:
        A fully initialised ``TutorialProject``.

    Raises:
        ScaffoldError: If *source* does not exist or
            contains no notebooks.
    """

    from ..project import TutorialProject

    source = Path(source).resolve()
    if not source.is_dir():
        raise ScaffoldError(f"Source directory does not exist: {source}")

    # Determine target directory.
    if target is None:
        target = source.parent / f"{source.name}_tutorial"
    target = Path(target).resolve()

    # If default config file already exists in target,
    # validate it and report rather than overwriting.
    config_path = target / DEFAULT_CONFIG
    if config_path.exists():
        return self._validate_existing(
            config_path,
            target,
        )

    # Discover content from source.
    discovery = self._discover(source)

    if not discovery["notebooks"]:
        raise ScaffoldError(f"No Jupyter notebooks found in {source}")

    # Derive project name from source directory name.
    project_name = source.name.replace(" ", "-").lower()

    # Detect Python version.
    python_version = _detect_python_version(source)

    # Build the spec.
    spec = self._build_spec(
        project_name,
        discovery,
        python_version,
    )

    # Create target directory and copy files.
    target.mkdir(parents=True, exist_ok=True)
    copied_paths = self._copy_files(
        source,
        target,
        discovery,
    )

    # Write default config file (tutorial YAML file).
    spec = self._rewrite_paths(spec, copied_paths)
    spec.write(config_path)

    # Create README if missing.
    readme = target / "README.md"
    if not readme.exists():
        readme.write_text(f"# {spec.display_title}\n\n{spec.description}\n")

    # Print summary.
    self._print_summary(spec, discovery, target)

    return TutorialProject(spec, target, config_path)

scan_url

scan_url(url: str, target: str | Path | None = None, remove_clone: bool = False) -> TutorialProject

Clone a remote repository and scan it.

Parameters:

Name Type Description Default
url str

Git-compatible clone URL.

required
target str | Path | None

Optional target directory for the project.

None
remove_clone bool

If True, delete the cloned repository after importing. When False (the default), the clone is kept for inspection.

False

Returns:

Type Description
TutorialProject

A TutorialProject imported from the clone.

Source code in src/tutorial_sdk/scaffold/importer.py
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
def scan_url(
    self,
    url: str,
    target: str | Path | None = None,
    remove_clone: bool = False,
) -> TutorialProject:
    """Clone a remote repository and scan it.

    Args:
        url: Git-compatible clone URL.
        target: Optional target directory for the project.
        remove_clone: If ``True``, delete the cloned
            repository after importing.  When ``False``
            (the default), the clone is kept for
            inspection.

    Returns:
        A ``TutorialProject`` imported from the clone.
    """

    # Derive repo name from URL.
    repo_name = url.rstrip("/").rsplit("/", 1)[-1].removesuffix(".git")

    if target is None:
        target = Path.cwd() / f"{repo_name}_tutorial"
    target = Path(target).resolve()

    # Clone into a sibling directory of the target.
    clone_dir = target.parent / repo_name
    if clone_dir.exists():
        print(f"Clone directory already exists: {clone_dir}")
    else:
        try:
            subprocess.run(
                ["git", "clone", "--depth", "1", url, str(clone_dir)],
                capture_output=True,
                text=True,
                check=True,
            )
        except FileNotFoundError:
            raise ScaffoldError(
                "git is required for --url / --github "
                "but was not found on PATH."
            )
        except subprocess.CalledProcessError as exc:
            raise ScaffoldError(
                f"Failed to clone {url}: {exc.stderr.strip()}"
            )

    try:
        result = self.scan(clone_dir, target)
    finally:
        if remove_clone and clone_dir.exists():
            shutil.rmtree(clone_dir)
            print(f"Removed clone: {clone_dir}")

    if not remove_clone:
        print(
            f"Clone kept at: {clone_dir}\n"
            f"  Use --remove-clone to delete it "
            f"after import."
        )

    return result

scan_github

scan_github(org_repo: str, target: str | Path | None = None, remove_clone: bool = False) -> TutorialProject

Import a GitHub repository.

Parameters:

Name Type Description Default
org_repo str

ORG/REPO shorthand.

required
target str | Path | None

Optional target directory.

None
remove_clone bool

If True, delete the cloned repository after importing.

False

Returns:

Type Description
TutorialProject

A TutorialProject.

Source code in src/tutorial_sdk/scaffold/importer.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def scan_github(
    self,
    org_repo: str,
    target: str | Path | None = None,
    remove_clone: bool = False,
) -> TutorialProject:
    """Import a GitHub repository.

    Args:
        org_repo: ``ORG/REPO`` shorthand.
        target: Optional target directory.
        remove_clone: If ``True``, delete the cloned
            repository after importing.

    Returns:
        A ``TutorialProject``.
    """

    url = f"https://github.com/{org_repo}.git"
    return self.scan_url(
        url,
        target,
        remove_clone=remove_clone,
    )

Generation

tutorial_sdk.generator.dockerfile.DockerfileGenerator

Render Dockerfiles from tutorial specifications.

Source code in src/tutorial_sdk/generator/dockerfile.py
  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
class DockerfileGenerator:
    """Render Dockerfiles from tutorial specifications."""

    def __init__(
        self,
        spec: TutorialSpec,
        root: str | Path = ".",
    ) -> None:
        """Create a Dockerfile generator.

        Args:
            spec: Parsed tutorial specification.
            root: Tutorial project root for custom section files.
        """

        self.spec = spec
        self.root = Path(root)

    def render(self) -> str:
        """Render the Dockerfile text.

        Returns:
            Complete Dockerfile contents ending with a trailing newline.
        """

        lines = [
            f"FROM {self.spec.build.base_image}",
            "",
            self._label("title", self.spec.display_title),
            self._label("version", self.spec.version),
            self._label("description", self.spec.description),
            "",
            "ENV PYTHONDONTWRITEBYTECODE=1",
            "ENV PYTHONUNBUFFERED=1",
            "",
        ]

        if self.spec.dependencies.apt:
            lines.extend(self._render_apt())

        lines.extend(self._read_custom_section("before_dependencies"))

        if self.spec.dependencies.pip or self.spec.dependencies.local:
            lines.extend(
                [
                    "RUN python -m venv --system-site-packages /opt/venv",
                    'ENV PATH="/opt/venv/bin:$PATH"',
                    "",
                ]
            )

        if self.spec.dependencies.pip:
            lines.extend(self._render_pip())

        if self.spec.dependencies.conda:
            lines.extend(self._render_conda_note())

        lines.extend(self._read_custom_section("after_dependencies"))
        lines.extend(["WORKDIR /workspace", ""])

        if self.spec.build.copy_repo:
            lines.extend(["COPY . /workspace", ""])
        else:
            lines.extend(self._render_content_copies())

        if self.spec.dependencies.local:
            lines.extend(self._render_local_dependencies())

        if self.spec.runtime.jupyterlab:
            lines.extend([f"EXPOSE {self.spec.runtime.expose_port}", ""])

        lines.extend(self._read_custom_section("before_entrypoint"))
        lines.extend(self._render_entrypoint())
        return "\n".join(lines).rstrip() + "\n"

    def _render_apt(self) -> list[str]:
        """Render ``apt-get install`` instructions.

        Returns:
            Dockerfile lines, or empty list if no apt
            packages are declared.
        """

        packages = [
            pkg.strip() for pkg in self.spec.dependencies.apt if pkg.strip()
        ]
        if not packages:
            return []
        lines = ["RUN apt-get update && apt-get install -y \\"]
        for i, package in enumerate(packages):
            if i == len(packages) - 1:
                lines.append(f"    {package} && \\")
            else:
                lines.append(f"    {package} \\")
        lines.extend(["    rm -rf /var/lib/apt/lists/*", ""])
        return lines

    def _render_pip(self) -> list[str]:
        """Render ``pip install`` instructions.

        Returns:
            Dockerfile lines, or empty list if no pip
            packages are declared.
        """

        packages = [
            pkg.strip() for pkg in self.spec.dependencies.pip if pkg.strip()
        ]
        if not packages:
            return []
        packages_str = " ".join(packages)
        return [
            "RUN python -m pip install --upgrade pip setuptools && \\",
            f"    python -m pip install --no-cache-dir {packages_str}",
            "",
        ]

    def _render_conda_note(self) -> list[str]:
        """Render a commented conda placeholder.

        Conda packages are listed as comments since the
        base image may not include conda.

        Returns:
            Commented Dockerfile lines.
        """

        packages = [
            pkg.strip() for pkg in self.spec.dependencies.conda if pkg.strip()
        ]
        if not packages:
            return []
        packages_str = " ".join(packages)
        return [
            "# Conda dependencies are declared but no conda base image was",
            "# requested. Install them when a conda-capable image is used.",
            f"# conda install -y {packages_str}",
            "",
        ]

    def _render_local_dependencies(self) -> list[str]:
        """Render ``pip install`` for local packages.

        Returns:
            Dockerfile lines for local dependency
            installations.
        """

        lines: list[str] = []
        for dependency in self.spec.dependencies.local:
            dep = dependency.strip()
            if dep:
                lines.append(f"RUN python -m pip install --no-cache-dir {dep}")
        if lines:
            lines.append("")
        return lines

    def _render_content_copies(self) -> list[str]:
        """Render ``COPY`` instructions for each content path.

        Returns:
            Dockerfile ``COPY`` lines.
        """

        lines: list[str] = []
        for path in self.spec.content.all_paths():
            lines.append(f"COPY {path} /workspace/{path}")
        if lines:
            lines.append("")
        return lines

    def _render_entrypoint(self) -> list[str]:
        """Render the ``CMD`` instruction.

        Returns:
            A single-element list with the ``CMD``
            line.
        """

        entrypoint = self.spec.entrypoint
        if entrypoint.kind == "shell":
            return ['CMD ["/bin/sh"]']
        if entrypoint.kind == "command" and entrypoint.command:
            parts = ", ".join(f'"{part}"' for part in entrypoint.command)
            return [f"CMD [{parts}]"]

        notebook = entrypoint.default_notebook
        command = [
            "jupyter",
            "lab",
            "--ip=0.0.0.0",
            "--allow-root",
            "--no-browser",
        ]
        if notebook:
            command.append(notebook)
        parts = ", ".join(f'"{part}"' for part in command)
        return [f"CMD [{parts}]"]

    def _read_custom_section(self, name: str) -> list[str]:
        """Read a user-supplied Dockerfile snippet.

        Args:
            name: Attribute name on ``DockerfileSections``
                (e.g. ``"before_dependencies"``).

        Returns:
            Lines from the snippet file, or an empty
            list if not configured.
        """

        section = getattr(self.spec.build.custom_sections, name)
        if not section:
            return []

        section_path = self.root / section
        if not section_path.exists():
            return [f"# Missing custom Dockerfile section: {section}", ""]
        return [section_path.read_text().rstrip(), ""]

    @staticmethod
    def _escape_label(value: str) -> str:
        """Escape a string for use in a Dockerfile LABEL."""

        return value.replace("\\", "\\\\").replace('"', '\\"')

    @classmethod
    def _label(
        cls,
        name: str,
        value: str,
    ) -> str:
        """Build an OCI image label instruction."""

        escaped = cls._escape_label(value)
        return f'LABEL org.opencontainers.image.{name}="{escaped}"'

__init__

__init__(spec: TutorialSpec, root: str | Path = '.') -> None

Create a Dockerfile generator.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
root str | Path

Tutorial project root for custom section files.

'.'
Source code in src/tutorial_sdk/generator/dockerfile.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def __init__(
    self,
    spec: TutorialSpec,
    root: str | Path = ".",
) -> None:
    """Create a Dockerfile generator.

    Args:
        spec: Parsed tutorial specification.
        root: Tutorial project root for custom section files.
    """

    self.spec = spec
    self.root = Path(root)

render

render() -> str

Render the Dockerfile text.

Returns:

Type Description
str

Complete Dockerfile contents ending with a trailing newline.

Source code in src/tutorial_sdk/generator/dockerfile.py
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
def render(self) -> str:
    """Render the Dockerfile text.

    Returns:
        Complete Dockerfile contents ending with a trailing newline.
    """

    lines = [
        f"FROM {self.spec.build.base_image}",
        "",
        self._label("title", self.spec.display_title),
        self._label("version", self.spec.version),
        self._label("description", self.spec.description),
        "",
        "ENV PYTHONDONTWRITEBYTECODE=1",
        "ENV PYTHONUNBUFFERED=1",
        "",
    ]

    if self.spec.dependencies.apt:
        lines.extend(self._render_apt())

    lines.extend(self._read_custom_section("before_dependencies"))

    if self.spec.dependencies.pip or self.spec.dependencies.local:
        lines.extend(
            [
                "RUN python -m venv --system-site-packages /opt/venv",
                'ENV PATH="/opt/venv/bin:$PATH"',
                "",
            ]
        )

    if self.spec.dependencies.pip:
        lines.extend(self._render_pip())

    if self.spec.dependencies.conda:
        lines.extend(self._render_conda_note())

    lines.extend(self._read_custom_section("after_dependencies"))
    lines.extend(["WORKDIR /workspace", ""])

    if self.spec.build.copy_repo:
        lines.extend(["COPY . /workspace", ""])
    else:
        lines.extend(self._render_content_copies())

    if self.spec.dependencies.local:
        lines.extend(self._render_local_dependencies())

    if self.spec.runtime.jupyterlab:
        lines.extend([f"EXPOSE {self.spec.runtime.expose_port}", ""])

    lines.extend(self._read_custom_section("before_entrypoint"))
    lines.extend(self._render_entrypoint())
    return "\n".join(lines).rstrip() + "\n"

tutorial_sdk.generator.manifest.ManifestGenerator

Generate machine-readable tutorial manifests.

Source code in src/tutorial_sdk/generator/manifest.py
 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
class ManifestGenerator:
    """Generate machine-readable tutorial manifests."""

    def __init__(self, spec: TutorialSpec) -> None:
        """Create a manifest generator.

        Args:
            spec: Parsed tutorial specification.
        """

        self.spec = spec

    def render_dict(self, image: str | None = None) -> dict[str, object]:
        """Render the manifest as a dictionary.

        Args:
            image: Override image tag.

        Returns:
            Manifest payload dictionary.
        """

        return self.spec.to_manifest_dict(image=image)

    def render_json(self, image: str | None = None) -> str:
        """Render the manifest as stable JSON.

        Args:
            image: Override image tag.

        Returns:
            Pretty-printed JSON string.
        """

        return json.dumps(self.render_dict(image=image), indent=2) + "\n"

    def write(self, path: str | Path, image: str | None = None) -> None:
        """Write the manifest to disk.

        Args:
            path: Destination file path.
            image: Override image tag.
        """

        Path(path).write_text(self.render_json(image=image))

__init__

__init__(spec: TutorialSpec) -> None

Create a manifest generator.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
Source code in src/tutorial_sdk/generator/manifest.py
12
13
14
15
16
17
18
19
def __init__(self, spec: TutorialSpec) -> None:
    """Create a manifest generator.

    Args:
        spec: Parsed tutorial specification.
    """

    self.spec = spec

render_dict

render_dict(image: str | None = None) -> dict[str, object]

Render the manifest as a dictionary.

Parameters:

Name Type Description Default
image str | None

Override image tag.

None

Returns:

Type Description
dict[str, object]

Manifest payload dictionary.

Source code in src/tutorial_sdk/generator/manifest.py
21
22
23
24
25
26
27
28
29
30
31
def render_dict(self, image: str | None = None) -> dict[str, object]:
    """Render the manifest as a dictionary.

    Args:
        image: Override image tag.

    Returns:
        Manifest payload dictionary.
    """

    return self.spec.to_manifest_dict(image=image)

render_json

render_json(image: str | None = None) -> str

Render the manifest as stable JSON.

Parameters:

Name Type Description Default
image str | None

Override image tag.

None

Returns:

Type Description
str

Pretty-printed JSON string.

Source code in src/tutorial_sdk/generator/manifest.py
33
34
35
36
37
38
39
40
41
42
43
def render_json(self, image: str | None = None) -> str:
    """Render the manifest as stable JSON.

    Args:
        image: Override image tag.

    Returns:
        Pretty-printed JSON string.
    """

    return json.dumps(self.render_dict(image=image), indent=2) + "\n"

write

write(path: str | Path, image: str | None = None) -> None

Write the manifest to disk.

Parameters:

Name Type Description Default
path str | Path

Destination file path.

required
image str | None

Override image tag.

None
Source code in src/tutorial_sdk/generator/manifest.py
45
46
47
48
49
50
51
52
53
def write(self, path: str | Path, image: str | None = None) -> None:
    """Write the manifest to disk.

    Args:
        path: Destination file path.
        image: Override image tag.
    """

    Path(path).write_text(self.render_json(image=image))

tutorial_sdk.generator.devcontainer.DevcontainerGenerator

Generate a minimal devcontainer configuration.

Source code in src/tutorial_sdk/generator/devcontainer.py
 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
class DevcontainerGenerator:
    """Generate a minimal devcontainer configuration."""

    def __init__(self, spec: TutorialSpec) -> None:
        """Create a devcontainer generator.

        Args:
            spec: Parsed tutorial specification.
        """

        self.spec = spec

    def render_dict(self) -> dict[str, object]:
        """Render devcontainer settings.

        Returns:
            Configuration dictionary.
        """

        return {
            "name": self.spec.display_title,
            "build": {
                "dockerfile": self.spec.build.dockerfile,
                "context": "..",
            },
            "workspaceFolder": "/workspace",
            "forwardPorts": [self.spec.runtime.expose_port],
        }

    def render_json(self) -> str:
        """Render devcontainer settings as stable JSON.

        Returns:
            Pretty-printed JSON string.
        """

        return json.dumps(self.render_dict(), indent=2) + "\n"

__init__

__init__(spec: TutorialSpec) -> None

Create a devcontainer generator.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
Source code in src/tutorial_sdk/generator/devcontainer.py
11
12
13
14
15
16
17
18
def __init__(self, spec: TutorialSpec) -> None:
    """Create a devcontainer generator.

    Args:
        spec: Parsed tutorial specification.
    """

    self.spec = spec

render_dict

render_dict() -> dict[str, object]

Render devcontainer settings.

Returns:

Type Description
dict[str, object]

Configuration dictionary.

Source code in src/tutorial_sdk/generator/devcontainer.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def render_dict(self) -> dict[str, object]:
    """Render devcontainer settings.

    Returns:
        Configuration dictionary.
    """

    return {
        "name": self.spec.display_title,
        "build": {
            "dockerfile": self.spec.build.dockerfile,
            "context": "..",
        },
        "workspaceFolder": "/workspace",
        "forwardPorts": [self.spec.runtime.expose_port],
    }

render_json

render_json() -> str

Render devcontainer settings as stable JSON.

Returns:

Type Description
str

Pretty-printed JSON string.

Source code in src/tutorial_sdk/generator/devcontainer.py
37
38
39
40
41
42
43
44
def render_json(self) -> str:
    """Render devcontainer settings as stable JSON.

    Returns:
        Pretty-printed JSON string.
    """

    return json.dumps(self.render_dict(), indent=2) + "\n"

Build & Runtime

tutorial_sdk.builder.docker.BuildResult dataclass

Result of a container build attempt.

Source code in src/tutorial_sdk/builder/docker.py
11
12
13
14
15
16
17
18
19
@dataclass(frozen=True)
class BuildResult:
    """Result of a container build attempt."""

    image: str
    dockerfile: Path
    pushed: bool = False
    digest: str | None = None
    status: str = "success"

tutorial_sdk.builder.docker.DockerBuilder

Build tutorial images with Docker.

Source code in src/tutorial_sdk/builder/docker.py
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
class DockerBuilder:
    """Build tutorial images with Docker."""

    def __init__(
        self,
        spec: TutorialSpec,
        root: str | Path = ".",
    ) -> None:
        """Create a Docker builder.

        Args:
            spec: Parsed tutorial specification.
            root: Tutorial project root directory.
        """

        self.spec = spec
        self.root = Path(root)

    def build(
        self,
        image: str | None = None,
        no_cache: bool | None = None,
        platform: str | None = None,
    ) -> BuildResult:
        """Run ``docker build`` for the tutorial.

        Args:
            image: Override image tag.
            no_cache: If ``True``, disable Docker layer
                caching.
            platform: Target platform (e.g.
                ``linux/amd64``).

        Returns:
            A ``BuildResult`` on success.

        Raises:
            BuildError: If the build exits non-zero.
        """

        image = image or self.spec.build.image or f"{self.spec.name}:latest"
        dockerfile = self.root / self.spec.build.dockerfile
        command = [
            "docker",
            "build",
            "-f",
            str(dockerfile),
            "-t",
            image,
        ]

        if no_cache is None:
            cache_enabled = self.spec.build.cache
        else:
            cache_enabled = not no_cache
        if not cache_enabled:
            command.append("--no-cache")
        if platform:
            command.extend(["--platform", platform])
        command.append(str(self.root))

        completed = subprocess.run(
            command,
            check=False,
            capture_output=True,
            text=True,
        )
        if completed.returncode != 0:
            raise BuildError(completed.stderr.strip() or "Docker build failed")
        return BuildResult(
            image=image,
            dockerfile=dockerfile,
        )

__init__

__init__(spec: TutorialSpec, root: str | Path = '.') -> None

Create a Docker builder.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
root str | Path

Tutorial project root directory.

'.'
Source code in src/tutorial_sdk/builder/docker.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def __init__(
    self,
    spec: TutorialSpec,
    root: str | Path = ".",
) -> None:
    """Create a Docker builder.

    Args:
        spec: Parsed tutorial specification.
        root: Tutorial project root directory.
    """

    self.spec = spec
    self.root = Path(root)

build

build(image: str | None = None, no_cache: bool | None = None, platform: str | None = None) -> BuildResult

Run docker build for the tutorial.

Parameters:

Name Type Description Default
image str | None

Override image tag.

None
no_cache bool | None

If True, disable Docker layer caching.

None
platform str | None

Target platform (e.g. linux/amd64).

None

Returns:

Type Description
BuildResult

A BuildResult on success.

Raises:

Type Description
BuildError

If the build exits non-zero.

Source code in src/tutorial_sdk/builder/docker.py
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
def build(
    self,
    image: str | None = None,
    no_cache: bool | None = None,
    platform: str | None = None,
) -> BuildResult:
    """Run ``docker build`` for the tutorial.

    Args:
        image: Override image tag.
        no_cache: If ``True``, disable Docker layer
            caching.
        platform: Target platform (e.g.
            ``linux/amd64``).

    Returns:
        A ``BuildResult`` on success.

    Raises:
        BuildError: If the build exits non-zero.
    """

    image = image or self.spec.build.image or f"{self.spec.name}:latest"
    dockerfile = self.root / self.spec.build.dockerfile
    command = [
        "docker",
        "build",
        "-f",
        str(dockerfile),
        "-t",
        image,
    ]

    if no_cache is None:
        cache_enabled = self.spec.build.cache
    else:
        cache_enabled = not no_cache
    if not cache_enabled:
        command.append("--no-cache")
    if platform:
        command.extend(["--platform", platform])
    command.append(str(self.root))

    completed = subprocess.run(
        command,
        check=False,
        capture_output=True,
        text=True,
    )
    if completed.returncode != 0:
        raise BuildError(completed.stderr.strip() or "Docker build failed")
    return BuildResult(
        image=image,
        dockerfile=dockerfile,
    )

tutorial_sdk.builder.local.LocalBuilder

Generate local build artifacts before invoking Docker.

Source code in src/tutorial_sdk/builder/local.py
 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
class LocalBuilder:
    """Generate local build artifacts before invoking Docker."""

    def __init__(
        self,
        spec: TutorialSpec,
        root: str | Path = ".",
    ) -> None:
        """Create a local builder.

        Args:
            spec: Parsed tutorial specification.
            root: Tutorial project root directory.
        """

        self.spec = spec
        self.root = Path(root)

    def write_dockerfile(self, path: str | Path | None = None) -> None:
        """Write the generated Dockerfile.

        Args:
            path: Destination path.  Defaults to the
                path configured in the build spec.
        """

        dockerfile = Path(path or self.spec.build.dockerfile)
        if not dockerfile.is_absolute():
            dockerfile = self.root / dockerfile
        dockerfile.write_text(
            DockerfileGenerator(
                self.spec,
                self.root,
            ).render()
        )

    def write_manifest(
        self,
        path: str | Path = DEFAULT_MANIFEST_NAME,
    ) -> None:
        """Write the tutorial manifest.

        Args:
            path: Destination path for the JSON
                manifest file.
        """

        manifest = Path(path)
        if not manifest.is_absolute():
            manifest = self.root / manifest
        ManifestGenerator(self.spec).write(manifest)

    def write_devcontainer(
        self,
        path: str | Path = DEFAULT_DEVCONT_NAME,
    ) -> None:
        """Write devcontainer configuration.

        Args:
            path: Destination path for the
                devcontainer JSON configuration
                file.
        """

        target = Path(path)
        if not target.is_absolute():
            target = self.root / target
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_text(DevcontainerGenerator(self.spec).render_json())

    def prepare(self) -> None:
        """Write generated files configured by the tutorial spec."""

        self.write_dockerfile()
        if self.spec.build.export_manifest:
            self.write_manifest()
        if self.spec.build.export_devcontainer:
            self.write_devcontainer()

    def build(
        self,
        image: str | None = None,
        no_cache: bool | None = None,
        platform: str | None = None,
    ) -> BuildResult:
        """Prepare artifacts and run Docker build.

        Args:
            image: Override image tag.
            no_cache: If ``True``, disable Docker layer
                caching.
            platform: Target platform.

        Returns:
            A ``BuildResult`` from Docker.
        """

        self.prepare()
        return DockerBuilder(self.spec, self.root).build(
            image=image, no_cache=no_cache, platform=platform
        )

__init__

__init__(spec: TutorialSpec, root: str | Path = '.') -> None

Create a local builder.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
root str | Path

Tutorial project root directory.

'.'
Source code in src/tutorial_sdk/builder/local.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def __init__(
    self,
    spec: TutorialSpec,
    root: str | Path = ".",
) -> None:
    """Create a local builder.

    Args:
        spec: Parsed tutorial specification.
        root: Tutorial project root directory.
    """

    self.spec = spec
    self.root = Path(root)

write_dockerfile

write_dockerfile(path: str | Path | None = None) -> None

Write the generated Dockerfile.

Parameters:

Name Type Description Default
path str | Path | None

Destination path. Defaults to the path configured in the build spec.

None
Source code in src/tutorial_sdk/builder/local.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def write_dockerfile(self, path: str | Path | None = None) -> None:
    """Write the generated Dockerfile.

    Args:
        path: Destination path.  Defaults to the
            path configured in the build spec.
    """

    dockerfile = Path(path or self.spec.build.dockerfile)
    if not dockerfile.is_absolute():
        dockerfile = self.root / dockerfile
    dockerfile.write_text(
        DockerfileGenerator(
            self.spec,
            self.root,
        ).render()
    )

write_manifest

write_manifest(path: str | Path = DEFAULT_MANIFEST_NAME) -> None

Write the tutorial manifest.

Parameters:

Name Type Description Default
path str | Path

Destination path for the JSON manifest file.

DEFAULT_MANIFEST_NAME
Source code in src/tutorial_sdk/builder/local.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def write_manifest(
    self,
    path: str | Path = DEFAULT_MANIFEST_NAME,
) -> None:
    """Write the tutorial manifest.

    Args:
        path: Destination path for the JSON
            manifest file.
    """

    manifest = Path(path)
    if not manifest.is_absolute():
        manifest = self.root / manifest
    ManifestGenerator(self.spec).write(manifest)

write_devcontainer

write_devcontainer(path: str | Path = DEFAULT_DEVCONT_NAME) -> None

Write devcontainer configuration.

Parameters:

Name Type Description Default
path str | Path

Destination path for the devcontainer JSON configuration file.

DEFAULT_DEVCONT_NAME
Source code in src/tutorial_sdk/builder/local.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def write_devcontainer(
    self,
    path: str | Path = DEFAULT_DEVCONT_NAME,
) -> None:
    """Write devcontainer configuration.

    Args:
        path: Destination path for the
            devcontainer JSON configuration
            file.
    """

    target = Path(path)
    if not target.is_absolute():
        target = self.root / target
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(DevcontainerGenerator(self.spec).render_json())

prepare

prepare() -> None

Write generated files configured by the tutorial spec.

Source code in src/tutorial_sdk/builder/local.py
87
88
89
90
91
92
93
94
def prepare(self) -> None:
    """Write generated files configured by the tutorial spec."""

    self.write_dockerfile()
    if self.spec.build.export_manifest:
        self.write_manifest()
    if self.spec.build.export_devcontainer:
        self.write_devcontainer()

build

build(image: str | None = None, no_cache: bool | None = None, platform: str | None = None) -> BuildResult

Prepare artifacts and run Docker build.

Parameters:

Name Type Description Default
image str | None

Override image tag.

None
no_cache bool | None

If True, disable Docker layer caching.

None
platform str | None

Target platform.

None

Returns:

Type Description
BuildResult

A BuildResult from Docker.

Source code in src/tutorial_sdk/builder/local.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def build(
    self,
    image: str | None = None,
    no_cache: bool | None = None,
    platform: str | None = None,
) -> BuildResult:
    """Prepare artifacts and run Docker build.

    Args:
        image: Override image tag.
        no_cache: If ``True``, disable Docker layer
            caching.
        platform: Target platform.

    Returns:
        A ``BuildResult`` from Docker.
    """

    self.prepare()
    return DockerBuilder(self.spec, self.root).build(
        image=image, no_cache=no_cache, platform=platform
    )

tutorial_sdk.runtime.launcher.RunResult dataclass

Result of starting a tutorial runtime.

Source code in src/tutorial_sdk/runtime/launcher.py
10
11
12
13
14
15
16
@dataclass(frozen=True)
class RunResult:
    """Result of starting a tutorial runtime."""

    image: str
    command: tuple[str, ...]
    returncode: int

tutorial_sdk.runtime.launcher.RuntimeLauncher

Launch tutorial images locally with Docker.

Source code in src/tutorial_sdk/runtime/launcher.py
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
class RuntimeLauncher:
    """Launch tutorial images locally with Docker."""

    def __init__(
        self,
        spec: TutorialSpec,
        root: str | Path = ".",
    ) -> None:
        """Create a runtime launcher.

        Args:
            spec: Parsed tutorial specification.
            root: Tutorial project root directory.
        """

        self.spec = spec
        self.root = Path(root)

    def run(
        self,
        image: str | None = None,
        port: int = 8888,
        shell: bool = False,
    ) -> RunResult:
        """Run the configured tutorial image.

        Args:
            image: Optional image tag override.
            port: Host port to bind.
            shell: If ``True``, override the entrypoint
                with an interactive shell.

        Returns:
            A ``RunResult`` with the exit code.
        """

        image = image or self.spec.build.image or f"{self.spec.name}:latest"
        command = [
            "docker",
            "run",
            "--rm",
            "-p",
            f"{port}:{self.spec.runtime.expose_port}",
        ]
        if shell:
            command.extend(["-it", "--entrypoint", "/bin/sh"])
        command.append(image)

        completed = subprocess.run(command, check=False)
        return RunResult(
            image=image,
            command=tuple(command),
            returncode=completed.returncode,
        )

__init__

__init__(spec: TutorialSpec, root: str | Path = '.') -> None

Create a runtime launcher.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
root str | Path

Tutorial project root directory.

'.'
Source code in src/tutorial_sdk/runtime/launcher.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def __init__(
    self,
    spec: TutorialSpec,
    root: str | Path = ".",
) -> None:
    """Create a runtime launcher.

    Args:
        spec: Parsed tutorial specification.
        root: Tutorial project root directory.
    """

    self.spec = spec
    self.root = Path(root)

run

run(image: str | None = None, port: int = 8888, shell: bool = False) -> RunResult

Run the configured tutorial image.

Parameters:

Name Type Description Default
image str | None

Optional image tag override.

None
port int

Host port to bind.

8888
shell bool

If True, override the entrypoint with an interactive shell.

False

Returns:

Type Description
RunResult

A RunResult with the exit code.

Source code in src/tutorial_sdk/runtime/launcher.py
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
def run(
    self,
    image: str | None = None,
    port: int = 8888,
    shell: bool = False,
) -> RunResult:
    """Run the configured tutorial image.

    Args:
        image: Optional image tag override.
        port: Host port to bind.
        shell: If ``True``, override the entrypoint
            with an interactive shell.

    Returns:
        A ``RunResult`` with the exit code.
    """

    image = image or self.spec.build.image or f"{self.spec.name}:latest"
    command = [
        "docker",
        "run",
        "--rm",
        "-p",
        f"{port}:{self.spec.runtime.expose_port}",
    ]
    if shell:
        command.extend(["-it", "--entrypoint", "/bin/sh"])
    command.append(image)

    completed = subprocess.run(command, check=False)
    return RunResult(
        image=image,
        command=tuple(command),
        returncode=completed.returncode,
    )

Validation

tutorial_sdk.validator.report.ValidationCheck

Bases: BaseModel

A single validation check result.

Source code in src/tutorial_sdk/validator/report.py
 9
10
11
12
13
14
15
16
class ValidationCheck(BaseModel):
    """A single validation check result."""

    model_config = ConfigDict(extra="forbid")

    name: str
    passed: bool
    message: str

tutorial_sdk.validator.report.ValidationReport

Bases: BaseModel

Machine-readable tutorial validation report.

Source code in src/tutorial_sdk/validator/report.py
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
class ValidationReport(BaseModel):
    """Machine-readable tutorial validation report."""

    model_config = ConfigDict(extra="forbid")

    passed: bool
    checks: list[ValidationCheck] = Field(default_factory=list)
    errors: list[str] = Field(default_factory=list)
    warnings: list[str] = Field(default_factory=list)

    @classmethod
    def combine(
        cls,
        reports: list["ValidationReport"],
    ) -> "ValidationReport":
        """Combine several reports into one report.

        Args:
            reports: List of reports to merge.

        Returns:
            A single ``ValidationReport`` with all
            checks, errors, and warnings aggregated.
        """

        checks: list[ValidationCheck] = []
        errors: list[str] = []
        warnings: list[str] = []
        for report in reports:
            checks.extend(report.checks)
            errors.extend(report.errors)
            warnings.extend(report.warnings)
        return cls(
            passed=all(report.passed for report in reports),
            checks=checks,
            errors=errors,
            warnings=warnings,
        )

    def render_json(self) -> str:
        """Render report as stable JSON.

        Returns:
            Pretty-printed JSON string.
        """

        return json.dumps(self.model_dump(mode="json"), indent=2) + "\n"

    def write(
        self,
        path: str | Path,
    ) -> None:
        """Write report JSON to disk.

        Args:
            path: Destination file path.
        """

        Path(path).write_text(self.render_json())

combine classmethod

combine(reports: list[ValidationReport]) -> ValidationReport

Combine several reports into one report.

Parameters:

Name Type Description Default
reports list[ValidationReport]

List of reports to merge.

required

Returns:

Type Description
ValidationReport

A single ValidationReport with all checks, errors, and warnings aggregated.

Source code in src/tutorial_sdk/validator/report.py
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
@classmethod
def combine(
    cls,
    reports: list["ValidationReport"],
) -> "ValidationReport":
    """Combine several reports into one report.

    Args:
        reports: List of reports to merge.

    Returns:
        A single ``ValidationReport`` with all
        checks, errors, and warnings aggregated.
    """

    checks: list[ValidationCheck] = []
    errors: list[str] = []
    warnings: list[str] = []
    for report in reports:
        checks.extend(report.checks)
        errors.extend(report.errors)
        warnings.extend(report.warnings)
    return cls(
        passed=all(report.passed for report in reports),
        checks=checks,
        errors=errors,
        warnings=warnings,
    )

render_json

render_json() -> str

Render report as stable JSON.

Returns:

Type Description
str

Pretty-printed JSON string.

Source code in src/tutorial_sdk/validator/report.py
58
59
60
61
62
63
64
65
def render_json(self) -> str:
    """Render report as stable JSON.

    Returns:
        Pretty-printed JSON string.
    """

    return json.dumps(self.model_dump(mode="json"), indent=2) + "\n"

write

write(path: str | Path) -> None

Write report JSON to disk.

Parameters:

Name Type Description Default
path str | Path

Destination file path.

required
Source code in src/tutorial_sdk/validator/report.py
67
68
69
70
71
72
73
74
75
76
77
def write(
    self,
    path: str | Path,
) -> None:
    """Write report JSON to disk.

    Args:
        path: Destination file path.
    """

    Path(path).write_text(self.render_json())

tutorial_sdk.validator.assets.AssetValidator

Validate declared content assets.

Source code in src/tutorial_sdk/validator/assets.py
 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
class AssetValidator:
    """Validate declared content assets."""

    def __init__(
        self,
        spec: TutorialSpec,
        root: str | Path = ".",
    ) -> None:
        """Create an asset validator.

        Args:
            spec: Parsed tutorial specification.
            root: Tutorial project root directory.
        """

        self.spec = spec
        self.root = Path(root)

    def validate(self) -> ValidationReport:
        """Check that declared content paths exist.

        Returns:
            A ``ValidationReport`` with path-existence
            checks.
        """

        missing = [
            path
            for path in self.spec.content.all_paths()
            if not (self.root / path).exists()
        ]
        if missing:
            message = "Missing declared paths: " + ", ".join(missing)
            return ValidationReport(
                passed=False,
                checks=[
                    ValidationCheck(
                        name="spec.paths",
                        passed=False,
                        message=message,
                    )
                ],
                errors=[message],
            )

        return ValidationReport(
            passed=True,
            checks=[
                ValidationCheck(
                    name="spec.paths",
                    passed=True,
                    message="All declared paths exist.",
                )
            ],
        )

__init__

__init__(spec: TutorialSpec, root: str | Path = '.') -> None

Create an asset validator.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
root str | Path

Tutorial project root directory.

'.'
Source code in src/tutorial_sdk/validator/assets.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def __init__(
    self,
    spec: TutorialSpec,
    root: str | Path = ".",
) -> None:
    """Create an asset validator.

    Args:
        spec: Parsed tutorial specification.
        root: Tutorial project root directory.
    """

    self.spec = spec
    self.root = Path(root)

validate

validate() -> ValidationReport

Check that declared content paths exist.

Returns:

Type Description
ValidationReport

A ValidationReport with path-existence checks.

Source code in src/tutorial_sdk/validator/assets.py
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
def validate(self) -> ValidationReport:
    """Check that declared content paths exist.

    Returns:
        A ``ValidationReport`` with path-existence
        checks.
    """

    missing = [
        path
        for path in self.spec.content.all_paths()
        if not (self.root / path).exists()
    ]
    if missing:
        message = "Missing declared paths: " + ", ".join(missing)
        return ValidationReport(
            passed=False,
            checks=[
                ValidationCheck(
                    name="spec.paths",
                    passed=False,
                    message=message,
                )
            ],
            errors=[message],
        )

    return ValidationReport(
        passed=True,
        checks=[
            ValidationCheck(
                name="spec.paths",
                passed=True,
                message="All declared paths exist.",
            )
        ],
    )

tutorial_sdk.validator.notebooks.NotebookValidator

Validate notebooks declared by a tutorial.

Source code in src/tutorial_sdk/validator/notebooks.py
 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
class NotebookValidator:
    """Validate notebooks declared by a tutorial."""

    def __init__(
        self,
        spec: TutorialSpec,
        root: str | Path = ".",
    ) -> None:
        """Create a notebook validator.

        Args:
            spec: Parsed tutorial specification.
            root: Tutorial project root directory.
        """

        self.spec = spec
        self.root = Path(root)

    def validate(self) -> ValidationReport:
        """Validate notebook files and stored execution errors.

        The MVP does not execute notebooks directly. It detects missing
        notebook files and error outputs already present in notebooks.
        """

        missing = [
            path
            for path in self.spec.content.notebooks
            if not (self.root / path).exists()
        ]
        if missing:
            message = "Missing notebooks: " + ", ".join(missing)
            return ValidationReport(
                passed=False,
                checks=[
                    ValidationCheck(
                        name="notebooks.present",
                        passed=False,
                        message=message,
                    )
                ],
                errors=[message],
            )

        errors = self._stored_execution_errors()
        if errors and self.spec.validation.require_clean_execution:
            message = "Notebook execution errors found: " + "; ".join(errors)
            return ValidationReport(
                passed=False,
                checks=[
                    ValidationCheck(
                        name="notebooks.clean",
                        passed=False,
                        message=message,
                    )
                ],
                errors=[message],
            )

        return ValidationReport(
            passed=True,
            checks=[
                ValidationCheck(
                    name="notebooks.present",
                    passed=True,
                    message=(
                        f"{len(self.spec.content.notebooks)} notebooks "
                        "declared and readable."
                    ),
                )
            ],
        )

    def _stored_execution_errors(self) -> list[str]:
        """Scan notebooks for stored error outputs.

        Returns:
            List of human-readable error descriptions
            (e.g. ``"notebook.ipynb: cell 3"``).
        """

        errors: list[str] = []
        for notebook in self.spec.content.notebooks:
            path = self.root / notebook
            try:
                payload = json.loads(path.read_text())
            except (OSError, json.JSONDecodeError):
                errors.append(f"{notebook}: invalid notebook JSON")
                continue

            for index, cell in enumerate(payload.get("cells", [])):
                outputs = cell.get("outputs", [])
                for output in outputs:
                    if output.get("output_type") == "error":
                        errors.append(f"{notebook}: cell {index}")
        return errors

__init__

__init__(spec: TutorialSpec, root: str | Path = '.') -> None

Create a notebook validator.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
root str | Path

Tutorial project root directory.

'.'
Source code in src/tutorial_sdk/validator/notebooks.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def __init__(
    self,
    spec: TutorialSpec,
    root: str | Path = ".",
) -> None:
    """Create a notebook validator.

    Args:
        spec: Parsed tutorial specification.
        root: Tutorial project root directory.
    """

    self.spec = spec
    self.root = Path(root)

validate

validate() -> ValidationReport

Validate notebook files and stored execution errors.

The MVP does not execute notebooks directly. It detects missing notebook files and error outputs already present in notebooks.

Source code in src/tutorial_sdk/validator/notebooks.py
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
def validate(self) -> ValidationReport:
    """Validate notebook files and stored execution errors.

    The MVP does not execute notebooks directly. It detects missing
    notebook files and error outputs already present in notebooks.
    """

    missing = [
        path
        for path in self.spec.content.notebooks
        if not (self.root / path).exists()
    ]
    if missing:
        message = "Missing notebooks: " + ", ".join(missing)
        return ValidationReport(
            passed=False,
            checks=[
                ValidationCheck(
                    name="notebooks.present",
                    passed=False,
                    message=message,
                )
            ],
            errors=[message],
        )

    errors = self._stored_execution_errors()
    if errors and self.spec.validation.require_clean_execution:
        message = "Notebook execution errors found: " + "; ".join(errors)
        return ValidationReport(
            passed=False,
            checks=[
                ValidationCheck(
                    name="notebooks.clean",
                    passed=False,
                    message=message,
                )
            ],
            errors=[message],
        )

    return ValidationReport(
        passed=True,
        checks=[
            ValidationCheck(
                name="notebooks.present",
                passed=True,
                message=(
                    f"{len(self.spec.content.notebooks)} notebooks "
                    "declared and readable."
                ),
            )
        ],
    )

tutorial_sdk.validator.dependencies.DependencyValidator

Validate dependency declarations that can be checked locally.

Source code in src/tutorial_sdk/validator/dependencies.py
  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
class DependencyValidator:
    """Validate dependency declarations that can be checked locally."""

    def __init__(self, spec: TutorialSpec) -> None:
        """Create a dependency validator.

        Args:
            spec: Parsed tutorial specification.
        """

        self.spec = spec

    def validate(self) -> ValidationReport:
        """Validate dependency sections.

        Returns:
            A ``ValidationReport`` with import
            availability checks.
        """

        warnings: list[str] = []
        checks = [
            ValidationCheck(
                name="dependencies.declared",
                passed=True,
                message="Dependency sections are well formed.",
            )
        ]

        if self.spec.validation.check_imports:
            missing = self._missing_imports()
            if missing:
                message = "Local Python imports unavailable: " + ", ".join(
                    missing
                )
                warnings.append(message)
                checks.append(
                    ValidationCheck(
                        name="dependencies.imports",
                        passed=True,
                        message=message,
                    )
                )
            else:
                checks.append(
                    ValidationCheck(
                        name="dependencies.imports",
                        passed=True,
                        message=(
                            "Declared import-like pip packages are available."
                        ),
                    )
                )

        return ValidationReport(
            passed=all(check.passed for check in checks),
            checks=checks,
            warnings=warnings,
        )

    def _missing_imports(self) -> list[str]:
        """Return pip packages whose modules are not importable.

        Returns:
            List of module names that could not be
            found by ``importlib``.
        """

        missing: list[str] = []
        for package in self.spec.dependencies.pip:
            module = self._package_to_module(package)
            if module and importlib.util.find_spec(module) is None:
                missing.append(module)
        return missing

    @staticmethod
    def _package_to_module(package: str) -> str | None:
        """Convert a pip package spec to an importable name.

        Args:
            package: A pip dependency string (e.g.
                ``"numpy>=1.24"``).

        Returns:
            The bare module name, or ``None`` if the
            spec cannot be converted (e.g. URLs).
        """

        name = package.split("==", 1)[0]
        name = name.split(">=", 1)[0].split("<=", 1)[0]
        name = name.split("[", 1)[0].strip()
        if not name or any(char in name for char in "/.@"):
            return None
        return name.replace("-", "_")

__init__

__init__(spec: TutorialSpec) -> None

Create a dependency validator.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
Source code in src/tutorial_sdk/validator/dependencies.py
12
13
14
15
16
17
18
19
def __init__(self, spec: TutorialSpec) -> None:
    """Create a dependency validator.

    Args:
        spec: Parsed tutorial specification.
    """

    self.spec = spec

validate

validate() -> ValidationReport

Validate dependency sections.

Returns:

Type Description
ValidationReport

A ValidationReport with import availability checks.

Source code in src/tutorial_sdk/validator/dependencies.py
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
def validate(self) -> ValidationReport:
    """Validate dependency sections.

    Returns:
        A ``ValidationReport`` with import
        availability checks.
    """

    warnings: list[str] = []
    checks = [
        ValidationCheck(
            name="dependencies.declared",
            passed=True,
            message="Dependency sections are well formed.",
        )
    ]

    if self.spec.validation.check_imports:
        missing = self._missing_imports()
        if missing:
            message = "Local Python imports unavailable: " + ", ".join(
                missing
            )
            warnings.append(message)
            checks.append(
                ValidationCheck(
                    name="dependencies.imports",
                    passed=True,
                    message=message,
                )
            )
        else:
            checks.append(
                ValidationCheck(
                    name="dependencies.imports",
                    passed=True,
                    message=(
                        "Declared import-like pip packages are available."
                    ),
                )
            )

    return ValidationReport(
        passed=all(check.passed for check in checks),
        checks=checks,
        warnings=warnings,
    )

tutorial_sdk.validator.container.ContainerValidator

Validate built container environments.

Source code in src/tutorial_sdk/validator/container.py
 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
class ContainerValidator:
    """Validate built container environments."""

    def __init__(
        self,
        spec: TutorialSpec,
        root: str | Path = ".",
    ) -> None:
        """Create a container validator.

        Args:
            spec: Parsed tutorial specification.
            root: Tutorial project root directory.
        """

        self.spec = spec
        self.root = Path(root)

    def validate(self, image: str | None = None) -> ValidationReport:
        """Verify the built container image starts and has JupyterLab.

        Args:
            image: Override image tag.  Falls back to
                the build spec's configured image.

        Returns:
            A ``ValidationReport`` with container
            start and JupyterLab availability checks.
        """

        image_name = (
            image or self.spec.build.image or f"{self.spec.name}:latest"
        )
        container_name = f"tutorial-sdk-val-{self.spec.name}"

        # Ensure container doesn't already exist from a stale run
        subprocess.run(
            ["docker", "rm", "-f", container_name],
            capture_output=True,
            check=False,
        )

        checks = []
        errors = []

        # 1. Attempt to run the container in the background
        start_cmd = [
            "docker",
            "run",
            "-d",
            "--name",
            container_name,
            image_name,
        ]
        try:
            start_res = subprocess.run(
                start_cmd,
                capture_output=True,
                text=True,
            )
        except FileNotFoundError:
            raise ValidationError(
                "Docker is not installed or not on PATH."
            )

        if start_res.returncode != 0:
            msg = f"Failed to start container: {start_res.stderr.strip()}"
            return ValidationReport(
                passed=False,
                checks=[
                    ValidationCheck(
                        name="container.start",
                        passed=False,
                        message=msg,
                    )
                ],
                errors=[msg],
            )

        try:
            # Sleep a bit to allow initial startup processes
            time.sleep(2)

            # Check if container is still running
            inspect_cmd = [
                "docker",
                "inspect",
                "-f",
                "{{.State.Running}}",
                container_name,
            ]
            inspect_res = subprocess.run(
                inspect_cmd,
                capture_output=True,
                text=True,
            )
            is_running = inspect_res.stdout.strip() == "true"

            if not is_running:
                # Capture logs to report failure reason
                logs_res = subprocess.run(
                    ["docker", "logs", container_name],
                    capture_output=True,
                    text=True,
                )
                msg = (
                    "Container stopped immediately. Logs:\n"
                    f"{logs_res.stderr.strip() or logs_res.stdout.strip()}"
                )
                checks.append(
                    ValidationCheck(
                        name="container.start",
                        passed=False,
                        message=msg,
                    )
                )
                errors.append(msg)
                return ValidationReport(
                    passed=False,
                    checks=checks,
                    errors=errors,
                )

            checks.append(
                ValidationCheck(
                    name="container.start",
                    passed=True,
                    message="Container started successfully.",
                )
            )

            # 2. Check if JupyterLab executable is available
            # inside the container.
            exec_cmd = [
                "docker",
                "exec",
                container_name,
                "jupyter",
                "lab",
                "--version",
            ]
            exec_res = subprocess.run(
                exec_cmd,
                capture_output=True,
                text=True,
            )

            if exec_res.returncode == 0:
                checks.append(
                    ValidationCheck(
                        name="container.jupyterlab",
                        passed=True,
                        message=(
                            "JupyterLab is available (version "
                            f"{exec_res.stdout.strip()})."
                        ),
                    )
                )
            else:
                msg = (
                    "JupyterLab command not available in container: "
                    f"{exec_res.stderr.strip() or exec_res.stdout.strip()}"
                )
                checks.append(
                    ValidationCheck(
                        name="container.jupyterlab",
                        passed=False,
                        message=msg,
                    )
                )
                errors.append(msg)

        finally:
            # Make sure we clean up the container under all circumstances
            subprocess.run(
                ["docker", "rm", "-f", container_name],
                capture_output=True,
                check=False,
            )

        return ValidationReport(
            passed=all(c.passed for c in checks),
            checks=checks,
            errors=errors,
        )

__init__

__init__(spec: TutorialSpec, root: str | Path = '.') -> None

Create a container validator.

Parameters:

Name Type Description Default
spec TutorialSpec

Parsed tutorial specification.

required
root str | Path

Tutorial project root directory.

'.'
Source code in src/tutorial_sdk/validator/container.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def __init__(
    self,
    spec: TutorialSpec,
    root: str | Path = ".",
) -> None:
    """Create a container validator.

    Args:
        spec: Parsed tutorial specification.
        root: Tutorial project root directory.
    """

    self.spec = spec
    self.root = Path(root)

validate

validate(image: str | None = None) -> ValidationReport

Verify the built container image starts and has JupyterLab.

Parameters:

Name Type Description Default
image str | None

Override image tag. Falls back to the build spec's configured image.

None

Returns:

Type Description
ValidationReport

A ValidationReport with container start and JupyterLab availability checks.

Source code in src/tutorial_sdk/validator/container.py
 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
def validate(self, image: str | None = None) -> ValidationReport:
    """Verify the built container image starts and has JupyterLab.

    Args:
        image: Override image tag.  Falls back to
            the build spec's configured image.

    Returns:
        A ``ValidationReport`` with container
        start and JupyterLab availability checks.
    """

    image_name = (
        image or self.spec.build.image or f"{self.spec.name}:latest"
    )
    container_name = f"tutorial-sdk-val-{self.spec.name}"

    # Ensure container doesn't already exist from a stale run
    subprocess.run(
        ["docker", "rm", "-f", container_name],
        capture_output=True,
        check=False,
    )

    checks = []
    errors = []

    # 1. Attempt to run the container in the background
    start_cmd = [
        "docker",
        "run",
        "-d",
        "--name",
        container_name,
        image_name,
    ]
    try:
        start_res = subprocess.run(
            start_cmd,
            capture_output=True,
            text=True,
        )
    except FileNotFoundError:
        raise ValidationError(
            "Docker is not installed or not on PATH."
        )

    if start_res.returncode != 0:
        msg = f"Failed to start container: {start_res.stderr.strip()}"
        return ValidationReport(
            passed=False,
            checks=[
                ValidationCheck(
                    name="container.start",
                    passed=False,
                    message=msg,
                )
            ],
            errors=[msg],
        )

    try:
        # Sleep a bit to allow initial startup processes
        time.sleep(2)

        # Check if container is still running
        inspect_cmd = [
            "docker",
            "inspect",
            "-f",
            "{{.State.Running}}",
            container_name,
        ]
        inspect_res = subprocess.run(
            inspect_cmd,
            capture_output=True,
            text=True,
        )
        is_running = inspect_res.stdout.strip() == "true"

        if not is_running:
            # Capture logs to report failure reason
            logs_res = subprocess.run(
                ["docker", "logs", container_name],
                capture_output=True,
                text=True,
            )
            msg = (
                "Container stopped immediately. Logs:\n"
                f"{logs_res.stderr.strip() or logs_res.stdout.strip()}"
            )
            checks.append(
                ValidationCheck(
                    name="container.start",
                    passed=False,
                    message=msg,
                )
            )
            errors.append(msg)
            return ValidationReport(
                passed=False,
                checks=checks,
                errors=errors,
            )

        checks.append(
            ValidationCheck(
                name="container.start",
                passed=True,
                message="Container started successfully.",
            )
        )

        # 2. Check if JupyterLab executable is available
        # inside the container.
        exec_cmd = [
            "docker",
            "exec",
            container_name,
            "jupyter",
            "lab",
            "--version",
        ]
        exec_res = subprocess.run(
            exec_cmd,
            capture_output=True,
            text=True,
        )

        if exec_res.returncode == 0:
            checks.append(
                ValidationCheck(
                    name="container.jupyterlab",
                    passed=True,
                    message=(
                        "JupyterLab is available (version "
                        f"{exec_res.stdout.strip()})."
                    ),
                )
            )
        else:
            msg = (
                "JupyterLab command not available in container: "
                f"{exec_res.stderr.strip() or exec_res.stdout.strip()}"
            )
            checks.append(
                ValidationCheck(
                    name="container.jupyterlab",
                    passed=False,
                    message=msg,
                )
            )
            errors.append(msg)

    finally:
        # Make sure we clean up the container under all circumstances
        subprocess.run(
            ["docker", "rm", "-f", container_name],
            capture_output=True,
            check=False,
        )

    return ValidationReport(
        passed=all(c.passed for c in checks),
        checks=checks,
        errors=errors,
    )

Built-in Exceptions

tutorial_sdk.errors

Exception hierarchy for tutorial-sdk.

TutorialSdkError

Bases: Exception

Base class for SDK errors.

Source code in src/tutorial_sdk/errors.py
4
5
class TutorialSdkError(Exception):
    """Base class for SDK errors."""

ConfigError

Bases: TutorialSdkError

Raised when a tutorial specification is invalid.

Source code in src/tutorial_sdk/errors.py
8
9
class ConfigError(TutorialSdkError):
    """Raised when a tutorial specification is invalid."""

BuildError

Bases: TutorialSdkError

Raised when a container build fails.

Source code in src/tutorial_sdk/errors.py
12
13
class BuildError(TutorialSdkError):
    """Raised when a container build fails."""

ValidationError

Bases: TutorialSdkError

Raised when validation cannot complete.

Source code in src/tutorial_sdk/errors.py
16
17
class ValidationError(TutorialSdkError):
    """Raised when validation cannot complete."""

ScaffoldError

Bases: TutorialSdkError

Raised when scaffolding cannot be created.

Source code in src/tutorial_sdk/errors.py
20
21
class ScaffoldError(TutorialSdkError):
    """Raised when scaffolding cannot be created."""

Extension Protocols

Plugin interfaces for SDK extension points.

ValidatorPlugin

Bases: Protocol

Protocol for external validation plugins.

Source code in src/tutorial_sdk/plugins/__init__.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class ValidatorPlugin(Protocol):
    """Protocol for external validation plugins."""

    name: str

    def validate(self, project: object) -> object:
        """Validate a project and return a report.

        Args:
            project: Project-like object supplied by the SDK.

        Returns:
            Plugin-defined validation result.
        """

validate

validate(project: object) -> object

Validate a project and return a report.

Parameters:

Name Type Description Default
project object

Project-like object supplied by the SDK.

required

Returns:

Type Description
object

Plugin-defined validation result.

Source code in src/tutorial_sdk/plugins/__init__.py
11
12
13
14
15
16
17
18
19
def validate(self, project: object) -> object:
    """Validate a project and return a report.

    Args:
        project: Project-like object supplied by the SDK.

    Returns:
        Plugin-defined validation result.
    """

TutorialGenerator

Bases: Protocol

Protocol for future tutorial generation strategies.

Source code in src/tutorial_sdk/plugins/__init__.py
22
23
24
25
26
27
28
29
30
31
32
33
class TutorialGenerator(Protocol):
    """Protocol for future tutorial generation strategies."""

    def generate(self, request: object) -> object:
        """Generate tutorial content from a request.

        Args:
            request: Plugin-defined generation request.

        Returns:
            Plugin-defined generation result.
        """

generate

generate(request: object) -> object

Generate tutorial content from a request.

Parameters:

Name Type Description Default
request object

Plugin-defined generation request.

required

Returns:

Type Description
object

Plugin-defined generation result.

Source code in src/tutorial_sdk/plugins/__init__.py
25
26
27
28
29
30
31
32
33
def generate(self, request: object) -> object:
    """Generate tutorial content from a request.

    Args:
        request: Plugin-defined generation request.

    Returns:
        Plugin-defined generation result.
    """