Skip to content

API reference

Auto-generated from docstrings -- full signatures, parameter types, and defaults for the same Python API surface that page introduces narratively. Start there for how to use it; come here for the exact call signature.

Generator functions

pitloom.assemble.generate

generate(
    target: Path | str = ".",
    *,
    offline: bool | None = None,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    extract_file_header: bool | None = None,
    scan_model_usage: bool | None = None,
    trust_model_files: bool | None = None,
    content_type: bool | None = None,
    content_type_method: str | None = None,
    update_id_registry: bool | None = None,
    use_lockfile: bool | None = None,
    build_options: BuildOptions = BuildOptions(),
    max_source_metadata_bytes: int | None = None,
    max_model_extract_bytes: int | None = None,
    pitloom_config: PitloomConfig | None = None,
    project_dir: Path | str | None = None,
    check_url: Callable[[str], None] | None = None,
    max_download_bytes: int | None = None,
    credentials: CredentialPolicy | None = None,
) -> str

Smart unified entrypoint for generating SPDX 3 SBOMs across all target types.

build_options (see :class:~pitloom.core.build_options.BuildOptions) takes effect for a project directory target only. Env, wheel, model and Hugging Face targets log one WARNING: per given build flag here, before dispatching; a Git URL, a PyPI URL and an sdist archive are settled by :func:generate_git_project_sbom, :func:generate_pypi_sbom and :func:generate_project_sbom.

project_dir (the project directory an sdist or a wheel was built from, for its registry keys) reaches the sdist and wheel delegates; any other target warns that it has no effect. So does max_model_extract_bytes on any target but a wheel, and max_download_bytes on any target but a PyPI URL, a Git URL or a Hugging Face model; an invalid value of either raises ValueError whatever the target. offline, max_download_bytes and check_url resolve for every remote target as :func:~pitloom.core.config_cascade.resolve_fetch_policy resolves them.

A PyPI project or release URL is read as loom wheel reads it: the release's wheel that best matches the running environment is downloaded, verified and read (:func:generate_pypi_sbom), then one INFO: names :func:generate_pypi_sbom with kind="sdist" for the sdist. check_url is called with every URL of the release lookup and the download before it is requested (the PyPI lookup of a dependency's licence and originator, made unless offline is true, does not pass through it); max_download_bytes caps the file.

A target that is the http or https URL of a Git repository (or of one of its web pages) is fetched and read as a project, or as the model file it names or its folder's one model file (:func:generate_git_sbom); check_url is its address policy, called with every redirect target before it is requested. A local target does not use it. max_download_bytes caps the disk the checkout takes, as it caps a PyPI download.

A Hugging Face model URL or id is read by :func:generate_model_sbom: check_url is called with the URL of each metadata file it downloads and each redirect target, and max_download_bytes caps each file.

A local directory with no project config is read for its one model file; one with no model file either is refused (project-or-model-not-found).

credentials (:class:~pitloom.core.credential_policy.CredentialPolicy) adds to the URL credentials pitloom_config accepts, for every target.

Source code in pitloom/assemble/__init__.py
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
def generate(
    target: Path | str = ".",
    *,
    offline: bool | None = None,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    extract_file_header: bool | None = None,
    scan_model_usage: bool | None = None,
    trust_model_files: bool | None = None,
    content_type: bool | None = None,
    content_type_method: str | None = None,
    update_id_registry: bool | None = None,
    use_lockfile: bool | None = None,
    build_options: BuildOptions = BuildOptions(),
    max_source_metadata_bytes: int | None = None,
    max_model_extract_bytes: int | None = None,
    pitloom_config: PitloomConfig | None = None,
    project_dir: Path | str | None = None,
    check_url: Callable[[str], None] | None = None,
    max_download_bytes: int | None = None,
    credentials: CredentialPolicy | None = None,
) -> str:
    """Smart unified entrypoint for generating SPDX 3 SBOMs across all target types.

    ``build_options`` (see :class:`~pitloom.core.build_options.BuildOptions`)
    takes effect for a project directory target only. Env, wheel, model and
    Hugging Face targets log one ``WARNING:`` per given build flag here,
    before dispatching; a Git URL, a PyPI URL and an sdist archive are
    settled by :func:`generate_git_project_sbom`, :func:`generate_pypi_sbom`
    and :func:`generate_project_sbom`.

    *project_dir* (the project directory an sdist or a wheel was built
    from, for its registry keys) reaches the sdist and wheel delegates; any
    other target warns that it has no effect. So does
    *max_model_extract_bytes* on any target but a wheel, and
    *max_download_bytes* on any target but a PyPI URL, a Git URL or a
    Hugging Face model; an invalid value of either raises ``ValueError``
    whatever the target. *offline*, *max_download_bytes* and *check_url*
    resolve for every remote target as
    :func:`~pitloom.core.config_cascade.resolve_fetch_policy` resolves
    them.

    A PyPI project or release URL is read as ``loom wheel`` reads it: the
    release's wheel that best matches the running environment is
    downloaded, verified and read (:func:`generate_pypi_sbom`), then one
    ``INFO:`` names :func:`generate_pypi_sbom` with ``kind="sdist"`` for
    the sdist.
    *check_url* is called with every URL of the release lookup and the
    download before it is requested (the PyPI lookup of a dependency's
    licence and originator, made unless *offline* is true, does not pass
    through it); *max_download_bytes* caps the file.

    A target that is the ``http`` or ``https`` URL of a Git repository (or of
    one of its web pages) is fetched and read as a project, or as the model
    file it names or its folder's one model file
    (:func:`generate_git_sbom`); *check_url* is its address policy,
    called with every redirect target before it is requested. A local
    target does not use it. *max_download_bytes* caps the disk the checkout
    takes, as it caps a PyPI download.

    A Hugging Face model URL or id is read by :func:`generate_model_sbom`:
    *check_url* is called with the URL of each metadata file it downloads
    and each redirect target, and *max_download_bytes* caps each file.

    A local directory with no project config is read for its one model
    file; one with no model file either is refused
    (``project-or-model-not-found``).

    *credentials* (:class:`~pitloom.core.credential_policy.CredentialPolicy`)
    adds to the URL credentials *pitloom_config* accepts, for every target.
    """
    # Before the no-effect warnings below, which precede any delegate's own
    # configure_logging() call.
    configure_logging()
    if max_model_extract_bytes is not None:
        require_model_extract_override(max_model_extract_bytes)  # even if inert
    if max_download_bytes is not None:
        require_download_override(max_download_bytes)  # even if inert
    target_str = str(target).strip()
    classification = _classify_target(target_str)

    if classification not in ("project", "git", "pypi"):
        # Warns once and resets to defaults, as every
        # settle_not_applicable() call does.
        build_options = build_options.settle_not_applicable(
            target_str, NON_PROJECT_TARGET_REASON
        )

    options: dict[str, Any] = {
        "output_path": output_path,
        "creation_metadata": creation_metadata,
        "pretty": pretty,
        "describe_relationship": describe_relationship,
        "id_registry": id_registry,
        "provenance": provenance,
        "offline": offline,
        "enrich": enrich,
        "extract_file_header": extract_file_header,
        "scan_model_usage": scan_model_usage,
        "trust_model_files": trust_model_files,
        "content_type": content_type,
        "content_type_method": content_type_method,
        "update_id_registry": update_id_registry,
        "max_source_metadata_bytes": max_source_metadata_bytes,
        "max_model_extract_bytes": max_model_extract_bytes,
        "pitloom_config": pitloom_config,
        "use_lockfile": use_lockfile,
        "project_dir": project_dir,
        "max_download_bytes": max_download_bytes,
        "credentials": credentials,
    }
    # Each delegate gets what it accepts; an option it does not accept is
    # settled here, once, with the target kind's reason.
    if classification in ("pypi", "git"):
        return _generate_remote(
            classification, target_str, options, build_options, check_url
        )
    if classification == "env":
        return generate_env_sbom(
            **forward_options(ENV, target_str, generate_env_sbom, options)
        )
    if classification == "wheel":
        return generate_wheel_sbom(
            target_str,
            **forward_options(WHEEL, target_str, generate_wheel_sbom, options),
            check_url=check_url,
        )
    if classification == "hf":
        return generate_model_sbom(
            target_str,
            **forward_options(HF, target_str, generate_model_sbom, options),
            check_url=check_url,
        )
    if classification in ("model_file", "model_folder"):
        forwarded = forward_options(
            MODEL_FILE, target_str, generate_model_sbom, options
        )
        # A local file does not use check_url; passed as to every delegate.
        return generate_model_sbom(
            _model_file_of(target_str), **forwarded, check_url=check_url
        )
    project_target = Path(target_str)
    kind = project_target_kind(project_target)
    return generate_project_sbom(
        project_target,
        **forward_options(kind, project_target, generate_project_sbom, options),
        build_options=build_options,
        check_url=check_url,
    )

pitloom.assemble.generate_project_sbom

generate_project_sbom(
    project_target: Path | str,
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    project_metadata: ProjectMetadata | None = None,
    pitloom_config: PitloomConfig | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    extract_file_header: bool | None = None,
    scan_model_usage: bool | None = None,
    trust_model_files: bool | None = None,
    content_type: bool | None = None,
    content_type_method: str | None = None,
    offline: bool | None = None,
    update_id_registry: bool | None = None,
    use_lockfile: bool | None = None,
    build_options: BuildOptions = BuildOptions(),
    max_source_metadata_bytes: int | None = None,
    project_dir: Path | str | None = None,
    check_url: Callable[[str], None] | None = None,
    max_download_bytes: int | None = None,
    acquisition: Acquisition | None = None,
    credentials: CredentialPolicy | None = None,
) -> str

Generate a Source SPDX 3 SBOM for a Python project or sdist archive.

project_target may be a PyPI project or release URL (a str; a :class:~pathlib.Path is always local): the release's sdist is downloaded and read (:func:~pitloom.assemble.generate_pypi_sbom, which never reads the sdist's own [tool.pitloom]): check_url is called with every URL of the release lookup and the download before it is requested (a dependency's licence lookup does not pass through it), and max_download_bytes caps the file; project_metadata then has no effect, with one WARNING:. For a local target check_url is not used and max_download_bytes has no effect (one WARNING:; an invalid value raises all the same). acquisition records how an sdist was downloaded (set by :func:~pitloom.assemble.generate_pypi_sbom): one provenance record on the main package, nothing else.

build_options (see :class:~pitloom.core.build_options.BuildOptions), unlike every other flag-shaped parameter here, deliberately has no pitloom_config.* fallback to defer to when unset. A caller must pass BuildOptions(allow=True) explicitly every time it wants Pitloom to execute the target project's own PEP 517 build backend; there is no config-cascade layer for it, since the config file lives in the (untrusted) project being scanned and must never be able to silently opt itself into code execution. For an sdist archive target every given build flag is ignored with one WARNING: each.

Settings come from the arguments, then pitloom_config, then the target's own [tool.pitloom], then the built-in defaults. pitloom_config alone replaces the target's config (--config); the project metadata is still read from project_target, and its lock-file cascade follows use_lockfile, else pitloom_config's use-lockfile.

use_lockfile only affects metadata resolved by this call: if the caller pre-supplies BOTH project_metadata and pitloom_config together, this parameter has no effect -- the lock-file cascade decision was already made when that metadata was produced. project_metadata alone is not supported: it is re-read from project_target, with a WARNING: explaining why (see "no silent deviations" in AGENTS.md).

For an sdist archive, extract_file_header, content_type, enrich, scan_model_usage, use_lockfile and trust_model_files have no effect, and for a directory trust_model_files has none; each warns when given (see :data:pitloom.core.inert_options.INERT). max_model_extract_bytes is no parameter here: a caller forwarding it settles it with :func:~pitloom.core.inert_options.forward_options and :func:~pitloom.core.inert_options.project_target_kind.

project_dir names the project directory an sdist archive was built from: its members are then keyed below that directory's path from the registry's root (a registry above the project, a monorepo), as embed-wheel --project-dir keys a wheel's. Nothing is read from it; without a registry it has no effect, with one WARNING:, and for a directory target it has none (that directory is the project).

credentials (:class:~pitloom.core.credential_policy.CredentialPolicy) adds to the credentials pitloom_config accepts; it never replaces them.

Raises:

Type Description
FileNotFoundError

project_dir is given for an sdist and is not a directory.

ValueError

project_target is a Hugging Face model URL (target-wrong-format), or a malformed one (hf-url-invalid): :func:~pitloom.extract.remote.huggingface.refuse_hub_model_target.

RemoteSourceError

a PyPI URL's sdist could not be fetched or verified (pypi.*).

Source code in pitloom/assemble/_generators.py
 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
def generate_project_sbom(
    project_target: Path | str,
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    project_metadata: ProjectMetadata | None = None,
    pitloom_config: PitloomConfig | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    extract_file_header: bool | None = None,
    scan_model_usage: bool | None = None,
    trust_model_files: bool | None = None,
    content_type: bool | None = None,
    content_type_method: str | None = None,
    offline: bool | None = None,
    update_id_registry: bool | None = None,
    use_lockfile: bool | None = None,
    build_options: BuildOptions = BuildOptions(),
    max_source_metadata_bytes: int | None = None,
    project_dir: Path | str | None = None,
    check_url: Callable[[str], None] | None = None,
    max_download_bytes: int | None = None,
    acquisition: Acquisition | None = None,
    credentials: CredentialPolicy | None = None,
) -> str:
    """Generate a Source SPDX 3 SBOM for a Python project or sdist archive.

    *project_target* may be a PyPI project or release URL (a ``str``; a
    :class:`~pathlib.Path` is always local): the release's sdist is
    downloaded and read (:func:`~pitloom.assemble.generate_pypi_sbom`, which
    never reads the sdist's own ``[tool.pitloom]``): *check_url* is called
    with every URL of the release lookup and the download before it is
    requested (a dependency's licence lookup does not pass through it), and
    *max_download_bytes* caps the file; *project_metadata* then has no effect,
    with one ``WARNING:``. For a local target *check_url* is not used and
    *max_download_bytes* has no effect (one ``WARNING:``; an invalid value
    raises all the same). *acquisition* records how an sdist was downloaded
    (set by :func:`~pitloom.assemble.generate_pypi_sbom`): one provenance
    record on the main package, nothing else.

    ``build_options`` (see :class:`~pitloom.core.build_options.BuildOptions`),
    unlike every other flag-shaped parameter here, deliberately has no
    ``pitloom_config.*`` fallback to defer to when unset. A caller must
    pass ``BuildOptions(allow=True)`` explicitly every time it wants
    Pitloom to execute the target project's own PEP 517 build backend;
    there is no config-cascade layer for it, since the config file lives
    in the (untrusted) project being scanned and must never be able to
    silently opt itself into code execution. For an sdist archive target
    every given build flag is ignored with one ``WARNING:`` each.

    Settings come from the arguments, then *pitloom_config*, then the
    target's own ``[tool.pitloom]``, then the built-in defaults.
    *pitloom_config* alone replaces the target's config (``--config``); the
    project metadata is still read from *project_target*, and its lock-file
    cascade follows ``use_lockfile``, else *pitloom_config*'s
    ``use-lockfile``.

    ``use_lockfile`` only affects metadata resolved by this call: if the
    caller pre-supplies BOTH ``project_metadata`` and ``pitloom_config``
    together, this parameter has no effect -- the lock-file cascade
    decision was already made when that metadata was produced.
    *project_metadata* alone is not supported: it is re-read from
    *project_target*, with a ``WARNING:`` explaining why (see "no silent
    deviations" in AGENTS.md).

    For an sdist archive, ``extract_file_header``, ``content_type``,
    ``enrich``, ``scan_model_usage``, ``use_lockfile`` and
    ``trust_model_files`` have no effect, and for a directory
    ``trust_model_files`` has none; each warns when given (see
    :data:`pitloom.core.inert_options.INERT`). ``max_model_extract_bytes``
    is no parameter here: a caller forwarding it settles it with
    :func:`~pitloom.core.inert_options.forward_options` and
    :func:`~pitloom.core.inert_options.project_target_kind`.

    *project_dir* names the project directory an sdist archive was built
    from: its members are then keyed below that directory's path from the
    registry's root (a registry above the project, a monorepo), as
    ``embed-wheel --project-dir`` keys a wheel's. Nothing is read from it;
    without a registry it has no effect, with one ``WARNING:``, and for a
    directory target it has none (that directory is the project).

    *credentials* (:class:`~pitloom.core.credential_policy.CredentialPolicy`)
    adds to the credentials *pitloom_config* accepts; it never replaces them.

    Raises:
        FileNotFoundError: *project_dir* is given for an sdist and is not a
            directory.
        ValueError: *project_target* is a Hugging Face model URL
            (``target-wrong-format``), or a malformed one
            (``hf-url-invalid``):
            :func:`~pitloom.extract.remote.huggingface.refuse_hub_model_target`.
        pitloom.extract.remote.errors.RemoteSourceError: a PyPI URL's sdist
            could not be fetched or verified (``pypi.*``).
    """
    configure_logging()
    refuse_hub_model_target(project_target)
    if isinstance(project_target, str) and is_pypi_url(project_target):
        if project_metadata is not None:
            warn_no_effect(
                project_target,
                ("project_metadata",),
                "for a PyPI URL target (the metadata is read from the downloaded "
                "sdist)",
            )
        return generate_pypi_sbom(
            project_target,
            kind=SDIST_FILE,
            check_url=check_url,
            max_download_bytes=max_download_bytes,
            output_path=output_path,
            creation_metadata=creation_metadata,
            pretty=pretty,
            describe_relationship=describe_relationship,
            pitloom_config=pitloom_config,
            id_registry=id_registry,
            provenance=provenance,
            enrich=enrich,
            extract_file_header=extract_file_header,
            scan_model_usage=scan_model_usage,
            trust_model_files=trust_model_files,
            content_type=content_type,
            content_type_method=content_type_method,
            offline=offline,
            update_id_registry=update_id_registry,
            use_lockfile=use_lockfile,
            build_options=build_options,
            max_source_metadata_bytes=max_source_metadata_bytes,
            project_dir=project_dir,
            credentials=credentials,
        )
    if max_download_bytes is not None:
        require_download_override(max_download_bytes)  # even if inert
    # Named as given in a message (a URL's "//" kept).
    target_path = TypedPath(project_target)

    # A cheap stat, before any project-metadata/lock-file read, so the
    # build-flag WARNING: is the first thing this call logs.
    build_options = build_options.settle_target(target_path)

    if project_target_kind(target_path) == SDIST:
        # Every option is passed, so an INERT[SDIST] entry needs no change
        # here.
        settle_inert(
            SDIST,
            target_path,
            {
                "pretty": pretty,
                "describe_relationship": describe_relationship,
                "enrich": enrich,
                "extract_file_header": extract_file_header,
                "scan_model_usage": scan_model_usage,
                "trust_model_files": trust_model_files,
                "content_type": content_type,
                "content_type_method": content_type_method,
                "max_source_metadata_bytes": max_source_metadata_bytes,
                "offline": offline,
                "id_registry": id_registry,
                "update_id_registry": update_id_registry,
                "creation_metadata": creation_metadata,
                "use_lockfile": use_lockfile,
                "project_dir": project_dir,
                "max_download_bytes": max_download_bytes,
            },
        )
    else:
        settle_inert(
            PROJECT,
            target_path,
            {
                "trust_model_files": trust_model_files,
                "project_dir": project_dir,
                "max_download_bytes": max_download_bytes,
            },
        )

    if project_metadata is None or pitloom_config is None:
        _warn_if_metadata_without_config(project_metadata, pitloom_config, target_path)
        project_metadata, pitloom_config, _ = resolve_project_with_lockfile(
            target_path, use_lockfile, pitloom_config
        )

    cfg = apply_overrides(
        pitloom_config,
        ConfigOverrides(
            provenance=provenance,
            enrich=enrich,
            extract_file_header=extract_file_header,
            scan_model_usage=scan_model_usage,
            content_type=content_type,
            content_type_method=content_type_method,
            offline=offline,
            pretty=pretty,
            describe_relationship=describe_relationship,
            update_id_registry=update_id_registry,
            max_source_metadata_bytes=max_source_metadata_bytes,
            credentials=credentials,
        ),
    )

    resolved_registry = resolve_registry(
        id_registry,
        cfg.id_registry,
        registry_base_dir(target_path),
        refuse_credentials=cfg.credential_policy.refuse,
    )
    sdist_project_dir = (
        archive_project_dir(project_dir, resolved_registry, target_path)
        if target_path.is_file()
        else None
    )

    # Owns SIGTERM/SIGHUP handling for the whole lifetime of a
    # build-and-read result: once a build ran, a signal until the end of
    # this block removes its extraction directory before the process
    # ends (see pitloom.core.build_signals). Without a build, inert.
    with TerminationGuard():
        if target_path.is_file():
            # Warned above, before metadata resolution -- nothing left to
            # warn about here. An sdist's copy of an in-tree registry is
            # left out as discovery leaves out the file.
            merkle_root = None
            project_files = without_registry_copies(
                project_metadata.files,
                registry_copy(resolved_registry, sdist_project_dir),
                in_sdist=True,
            )
            cleanup_discovery: Callable[[], None] = _noop_cleanup
        else:
            merkle_root, project_files, cleanup_discovery = get_wheel_files(
                target_path,
                scan_file_headers=cfg.extract_file_header,
                detect_content_type=cfg.content_type.enabled,
                content_type_method=cfg.content_type.method,
                content_type_overrides=cfg.content_type.overrides,
                build_options=build_options,
                exclude_path=registry_file_path(resolved_registry),
            )

        # cleanup_discovery (a no-op unless --allow-build's build-and-read
        # sourced project_files) must stay alive -- and this whole block
        # must run inside its try -- through every step below that either
        # re-reads a ProjectFile's bytes from disk via physical_path (AI-
        # model scanning, enrichment) or could itself raise before reaching
        # them (the fresh-containers copy): any of these raising before
        # cleanup_discovery() runs would leak the build-and-read temp
        # directory. Nothing after this block reads file bytes again
        # (document assembly only uses distribution_path/physical_path as
        # string keys, never re-opens the file).
        try:
            # `project_files` becomes the metadata's authoritative file
            # list. Every other dict/list field gets its own fresh copy too,
            # so nothing downstream can mutate the caller's own
            # `project_metadata`.
            project_metadata = project_metadata.replace_with_fresh_containers(
                files=project_files
            )

            ai_models = (
                scan_project_for_ai_models(
                    target_path,
                    project_files,
                    scan_usage=cfg.scan_model_usage is True,
                    usage_hint=lambda: cfg.scan_model_usage is None,
                )
                if target_path.is_dir()
                else []
            )

            enrichment_results_by_model = run_enrichers_for_models(
                ai_models, cfg.enrich, target_path
            )
        finally:
            cleanup_discovery()

    doc = DocumentModel(
        project=project_metadata,
        creation_metadata=creation_metadata or cfg.creation_metadata,
        ai_models=ai_models,
        acquisition=acquisition,
        files_origin=(
            FilesOrigin(project_dir=sdist_project_dir, archive=True, sdist=True)
            if target_path.is_file()
            else FilesOrigin(project_dir=target_path)
        ),
    )
    exporter = build(
        doc,
        merkle_root=merkle_root,
        sbom_type=spdx3_bindings.software_SbomType.source,
        registry=resolved_registry,
        enrichment_results_by_model=enrichment_results_by_model,
        **cfg.assemble_options,
    )

    if target_path.is_dir():
        merge_fragments(target_path, cfg.fragments, exporter)

    # Before the registry is written: a refused SBOM leaves it unchanged.
    sbom_json = exporter.to_json(
        pretty=cfg.pretty,
        describe_relationship=bool(cfg.describe_relationship),
        credentials=cfg.credential_policy,
    )

    _sync_registry(exporter, resolved_registry, cfg.update_id_registry)

    write_sbom_output(sbom_json, output_path)

    return sbom_json

pitloom.assemble.generate_git_sbom

generate_git_sbom(
    url: str,
    *,
    sbom_kind: str = AUTO,
    check_url: Callable[[str], None] | None = None,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    extract_file_header: bool | None = None,
    scan_model_usage: bool | None = None,
    content_type: bool | None = None,
    content_type_method: str | None = None,
    offline: bool | None = None,
    max_download_bytes: int | None = None,
    trust_model_files: bool | None = None,
    update_id_registry: bool | None = None,
    use_lockfile: bool | None = None,
    build_options: BuildOptions = BuildOptions(),
    max_source_metadata_bytes: int | None = None,
    project_metadata: ProjectMetadata | None = None,
    credentials: CredentialPolicy | None = None,
) -> str

Generate an SPDX 3 SBOM for the project or the AI model file at a Git URL.

url is fetched as :func:generate_git_project_sbom describes, every option meaning what it means there. sbom_kind says what the SBOM describes (:func:~pitloom.extract.remote.git_target.resolve_git_target):

  • "auto": a model file the URL names (whatever the folder holds), else the folder's Python project, else the folder's one AI model file;
  • "project": the folder's project only;
  • "model": the named model file, else the folder's one model file.

A model file of a clone, and each model file in its project's build file list, is read as a local one, except that a format whose reader a hostile file could crash or hang (fastText, GGUF, HDF5, ONNX, PyTorch) is listed without metadata, said in one INFO: per SBOM, unless trust_model_files (see :func:generate_git_project_sbom). A model file's messages name it by its path in the repository; an option a model SBOM cannot use warns once. credentials (:class:~pitloom.core.credential_policy.CredentialPolicy) adds to the credentials pitloom_config accepts.

Raises:

Type Description
InternalError

sbom_kind is none of the three (a :class:ValueError).

ValueError

max_download_bytes (or the config's) is not an integer of at least 1.

RemoteSourceError

the repository could not be fetched, the named file is not in it (git.path-not-found), or git.no-project.

CodedValueError

no model file to read (model-wrong-format, project-or-model-not-found), several (model-ambiguous), or a Git LFS pointer (lfs-pointer).

Source code in pitloom/assemble/_generators_git.py
 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
def generate_git_sbom(
    url: str,
    *,
    sbom_kind: str = AUTO,
    check_url: Callable[[str], None] | None = None,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    extract_file_header: bool | None = None,
    scan_model_usage: bool | None = None,
    content_type: bool | None = None,
    content_type_method: str | None = None,
    offline: bool | None = None,
    max_download_bytes: int | None = None,
    trust_model_files: bool | None = None,
    update_id_registry: bool | None = None,
    use_lockfile: bool | None = None,
    build_options: BuildOptions = BuildOptions(),
    max_source_metadata_bytes: int | None = None,
    project_metadata: ProjectMetadata | None = None,
    credentials: CredentialPolicy | None = None,
) -> str:
    """Generate an SPDX 3 SBOM for the project or the AI model file at a Git
    URL.

    *url* is fetched as :func:`generate_git_project_sbom` describes, every
    option meaning what it means there. *sbom_kind* says what the SBOM
    describes (:func:`~pitloom.extract.remote.git_target.resolve_git_target`):

    - ``"auto"``: a model file the URL names (whatever the folder holds),
      else the folder's Python project, else the folder's one AI model file;
    - ``"project"``: the folder's project only;
    - ``"model"``: the named model file, else the folder's one model file.

    A model file of a clone, and each model file in its project's build
    file list, is read as a local one, except that a format whose reader a
    hostile file could crash or hang (fastText, GGUF, HDF5, ONNX, PyTorch)
    is listed without metadata, said in one ``INFO:`` per SBOM, unless
    *trust_model_files* (see :func:`generate_git_project_sbom`). A model
    file's messages name it by its path in the repository; an option a
    model SBOM cannot use warns once. *credentials*
    (:class:`~pitloom.core.credential_policy.CredentialPolicy`) adds to the
    credentials *pitloom_config* accepts.

    Raises:
        pitloom.core.internal_error.InternalError: *sbom_kind* is none of
            the three (a :class:`ValueError`).
        ValueError: *max_download_bytes* (or the config's) is not an
            integer of at least 1.
        pitloom.extract.remote.errors.RemoteSourceError: the repository could
            not be fetched, the named file is not in it
            (``git.path-not-found``), or ``git.no-project``.
        pitloom.messages.CodedValueError: no model file to read
            (``model-wrong-format``, ``project-or-model-not-found``), several
            (``model-ambiguous``), or a Git LFS pointer (``lfs-pointer``).
    """
    configure_logging()
    if sbom_kind not in _SBOM_KINDS:
        raise InternalError(
            f"sbom_kind must be one of {_SBOM_KINDS}, got {sbom_kind!r}"
        )
    policy = resolve_fetch_policy(
        pitloom_config,
        offline=offline,
        max_download_bytes=max_download_bytes,
        check_url=check_url,
    )
    build_options.settle_not_applicable(url, REMOTE_REPOSITORY_REASON)
    if isinstance(id_registry, (str, Path)):
        # A relative path means the caller's directory, not the checkout's;
        # a message still names it as given.
        id_registry = GivenPath(
            Path(id_registry).absolute(), given_spelling(id_registry)
        )
    with fetch_git_project(
        url, policy=policy, trust_model_files=trust_model_files is True
    ) as checkout:
        with checkout.reading():
            target = resolve_git_target(checkout, sbom_kind, url)
            if target.model is not None:
                # The fetch consumed offline: the model read uses no network.
                return _git_model_sbom(
                    url,
                    target.model.path,
                    target.model.shown,
                    {
                        "output_path": output_path,
                        "creation_metadata": creation_metadata,
                        "pretty": pretty,
                        "describe_relationship": describe_relationship,
                        "pitloom_config": pitloom_config,
                        "id_registry": id_registry,
                        "provenance": provenance,
                        "enrich": enrich,
                        "extract_file_header": extract_file_header,
                        "scan_model_usage": scan_model_usage,
                        "content_type": content_type,
                        "content_type_method": content_type_method,
                        "update_id_registry": update_id_registry,
                        "use_lockfile": use_lockfile,
                        "max_source_metadata_bytes": max_source_metadata_bytes,
                        "project_metadata": project_metadata,
                        "credentials": credentials,
                    },
                )
            if pitloom_config is None:
                emit(
                    log,
                    CONFIG_UNSAFE,
                    logging.INFO,
                    line=CONFIG_UNSAFE_REMOTE_LINE,
                    frame=GIT_FRAME,
                )
            return generate_project_sbom(
                checkout.folder,
                output_path=output_path,
                creation_metadata=creation_metadata,
                pretty=pretty,
                describe_relationship=describe_relationship,
                project_metadata=project_metadata,
                pitloom_config=PitloomConfig()
                if pitloom_config is None
                else pitloom_config,
                id_registry=id_registry,
                provenance=provenance,
                enrich=enrich,
                extract_file_header=extract_file_header,
                scan_model_usage=scan_model_usage,
                content_type=content_type,
                content_type_method=content_type_method,
                offline=offline,
                update_id_registry=update_id_registry,
                use_lockfile=use_lockfile,
                max_source_metadata_bytes=max_source_metadata_bytes,
                credentials=credentials,
            )

pitloom.assemble.generate_git_project_sbom

generate_git_project_sbom(
    url: str,
    *,
    check_url: Callable[[str], None] | None = None,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    extract_file_header: bool | None = None,
    scan_model_usage: bool | None = None,
    content_type: bool | None = None,
    content_type_method: str | None = None,
    offline: bool | None = None,
    max_download_bytes: int | None = None,
    trust_model_files: bool | None = None,
    update_id_registry: bool | None = None,
    use_lockfile: bool | None = None,
    build_options: BuildOptions = BuildOptions(),
    max_source_metadata_bytes: int | None = None,
    project_metadata: ProjectMetadata | None = None,
    credentials: CredentialPolicy | None = None,
) -> str

Generate a Source SPDX 3 SBOM for the project at a Git URL.

url is a clone URL or the address of a repository web page, naming a branch, tag or commit and a folder (see :func:~pitloom.extract.remote.git.fetch_git_project, which fetches it). The repository is shallow-cloned into a temporary directory that is removed on return.

check_url is called with every redirect target before it is requested (the caller's address policy; Pitloom does not check the URL itself).

The repository is untrusted: its own [tool.pitloom] is ignored (a repository must not name host paths such as fragments or an ID registry) unless the caller passes pitloom_config, and its build backend is never run (a build flag in build_options warns once and has no effect). With offline (else pitloom_config's offline) true nothing is fetched (git.offline, offline-unusable). The fetch is stopped once the checkout takes more disk than max_download_bytes (else pitloom_config's max-download-bytes, else 512 MiB; git.too-large, over-cap). The three resolve as every remote route resolves them (:func:~pitloom.core.config_cascade.resolve_fetch_policy).

A model file of the repository in a format whose reader a hostile file could crash or hang (fastText, GGUF, HDF5, ONNX, PyTorch) is listed without metadata, with one INFO: (reader-unsafe/remote). With trust_model_files the caller vouches for the repository's model files and those readers run. Never set it from a request a third party can make (a service that takes repository URLs): a hostile file can crash or hang the process, and Ctrl-C cannot interrupt it. No configuration file can set it. When the folder holds no Python project but folders below it do, the failure names them (git.no-project); when it holds files that may be AI models instead, the failure says to ask for a model SBOM (:func:generate_git_sbom).

Raises:

Type Description
RemoteSourceError

the repository could not be fetched, or git.no-project.

ValueError

url is a Hugging Face model URL (target-wrong-format), or a malformed one (hf-url-invalid): :func:~pitloom.extract.remote.huggingface.refuse_hub_model_target.

Source code in pitloom/assemble/_generators_git.py
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
def generate_git_project_sbom(
    url: str,
    *,
    check_url: Callable[[str], None] | None = None,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    extract_file_header: bool | None = None,
    scan_model_usage: bool | None = None,
    content_type: bool | None = None,
    content_type_method: str | None = None,
    offline: bool | None = None,
    max_download_bytes: int | None = None,
    trust_model_files: bool | None = None,
    update_id_registry: bool | None = None,
    use_lockfile: bool | None = None,
    build_options: BuildOptions = BuildOptions(),
    max_source_metadata_bytes: int | None = None,
    project_metadata: ProjectMetadata | None = None,
    credentials: CredentialPolicy | None = None,
) -> str:
    """Generate a Source SPDX 3 SBOM for the project at a Git URL.

    *url* is a clone URL or the address of a repository web page, naming a
    branch, tag or commit and a folder (see
    :func:`~pitloom.extract.remote.git.fetch_git_project`, which fetches it).
    The repository is shallow-cloned into a temporary directory that is
    removed on return.

    *check_url* is called with every redirect target before it is requested
    (the caller's address policy; Pitloom does not check the URL itself).

    The repository is untrusted: its own ``[tool.pitloom]`` is ignored (a
    repository must not name host paths such as fragments or an ID registry)
    unless the caller passes *pitloom_config*, and its build backend is never
    run (a build flag in *build_options* warns once and has no effect). With
    *offline* (else *pitloom_config*'s ``offline``) true nothing is fetched
    (``git.offline``, ``offline-unusable``). The fetch is stopped once the
    checkout takes more disk than *max_download_bytes* (else
    *pitloom_config*'s ``max-download-bytes``, else 512 MiB;
    ``git.too-large``, ``over-cap``). The three resolve as every remote
    route resolves them
    (:func:`~pitloom.core.config_cascade.resolve_fetch_policy`).

    A model file of the repository in a format whose reader a hostile file
    could crash or hang (fastText, GGUF, HDF5, ONNX, PyTorch) is listed
    without metadata, with one ``INFO:`` (``reader-unsafe/remote``). With
    *trust_model_files* the caller vouches for the repository's model files
    and those readers run. Never set it from a request a third party can
    make (a service that takes repository URLs): a hostile file can crash
    or hang the process, and Ctrl-C cannot interrupt it. No configuration
    file can set it. When the folder
    holds no Python project but folders below it do, the failure names them
    (``git.no-project``); when it holds files that may be AI models instead,
    the failure says to ask for a model SBOM (:func:`generate_git_sbom`).

    Raises:
        pitloom.extract.remote.errors.RemoteSourceError: the repository could
            not be fetched, or ``git.no-project``.
        ValueError: *url* is a Hugging Face model URL
            (``target-wrong-format``), or a malformed one
            (``hf-url-invalid``):
            :func:`~pitloom.extract.remote.huggingface.refuse_hub_model_target`.
    """
    configure_logging()
    refuse_hub_model_target(url)
    return generate_git_sbom(
        url,
        sbom_kind=PROJECT,
        check_url=check_url,
        output_path=output_path,
        creation_metadata=creation_metadata,
        pretty=pretty,
        describe_relationship=describe_relationship,
        pitloom_config=pitloom_config,
        id_registry=id_registry,
        provenance=provenance,
        enrich=enrich,
        extract_file_header=extract_file_header,
        scan_model_usage=scan_model_usage,
        content_type=content_type,
        content_type_method=content_type_method,
        offline=offline,
        max_download_bytes=max_download_bytes,
        trust_model_files=trust_model_files,
        update_id_registry=update_id_registry,
        use_lockfile=use_lockfile,
        build_options=build_options,
        max_source_metadata_bytes=max_source_metadata_bytes,
        project_metadata=project_metadata,
        credentials=credentials,
    )

pitloom.assemble.generate_wheel_sbom

generate_wheel_sbom(
    wheel_path: Path | str,
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    offline: bool | None = None,
    content_type_method: str | None = None,
    update_id_registry: bool | None = None,
    max_source_metadata_bytes: int | None = None,
    max_model_extract_bytes: int | None = None,
    scan_model_usage: bool | None = None,
    trust_model_files: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    project_dir: Path | str | None = None,
    check_url: Callable[[str], None] | None = None,
    max_download_bytes: int | None = None,
    credentials: CredentialPolicy | None = None,
) -> str

Generate an Analyzed SPDX 3 SBOM for a built Python wheel.

wheel_path may be a PyPI project or release URL (a str; a :class:~pathlib.Path is always a local file): the release's wheel that best matches the running environment is downloaded and read (:func:~pitloom.assemble.generate_pypi_sbom): check_url is called with every URL of the release lookup and the download before it is requested (a dependency's licence lookup does not pass through it), and max_download_bytes caps the file. For a local wheel check_url is not used and max_download_bytes has no effect (one WARNING:; an invalid value raises all the same).

A wheel has no [tool.pitloom] of its own, and none is borrowed: not from the current directory, not from beside the wheel -- either may belong to an unrelated project. Settings come from the arguments, then pitloom_config when the caller names one explicitly, then the built-in defaults. The same holds for the registry: id_registry, else the explicit config's id-registry; no loom-id-registry.json is searched for. The copy of that registry a build put in the wheel is left out, with one WARNING:, when its path below the project directory is the member's (see :func:~pitloom.id_registry.registry_copy for the directory).

project_dir names the project directory the wheel was built from: its members are then keyed below that directory's path from the registry's root (a registry above the project, a monorepo), as embed-wheel --project-dir keys them. Nothing is read from it; without a registry it has no effect, with one WARNING:.

credentials (:class:~pitloom.core.credential_policy.CredentialPolicy) adds to the credentials an explicit pitloom_config accepts.

An explicit pitloom_config applies in full, identity included: its creators, creation datetime and comment fill in when creation_metadata is not given.

AI models inside the wheel are found; scan_model_usage also records which Python files in it reference them. One model file is copied out of the wheel at a time, each up to max_model_extract_bytes (--max-model-extract-bytes; else the config's max-model-extract-bytes, 512 MiB by default) and four times that in all, counting bytes copied and bytes read from archive members; a model beyond either limit is listed without metadata. Models in a format whose reader a hostile file can crash or hang (fastText, GGUF, HDF5, ONNX, PyTorch .pt/.pth) are listed without metadata too, with one INFO:, unless trust_model_files (for a wheel you trust only; it has no config key, so a config cannot opt in).

extract_file_header/content_type/enrich have no parameter here: reading a built wheel scans no file headers or content types, and its AI models are not enriched (see :data:pitloom.core.inert_options.INERT). content_type_method does apply, because it also steers whether dependency originator enrichment fetches a remote authors file.

Raises:

Type Description
ValueError

The wheel is refused as a whole (:class:~pitloom.core.wheel_dist_info.WheelRefused): not a ZIP archive, a member cannot be read, two members have one name or one holds a NUL; or max_model_extract_bytes is not an integer of at least 1.

FileNotFoundError

Nothing is at wheel_path, or not a regular file; or project_dir is given and is not a directory (input-not-found, carrying the code).

CodedValueError

wheel_path cannot be looked at (file-unreadable: a directory on its way refuses search).

OSError

The file itself cannot be opened (its own permissions, a transient I/O error).

RemoteSourceError

a PyPI URL's wheel could not be fetched or verified (pypi.*).

Source code in pitloom/assemble/_generators_wheel.py
 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
def generate_wheel_sbom(
    wheel_path: Path | str,
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    offline: bool | None = None,
    content_type_method: str | None = None,
    update_id_registry: bool | None = None,
    max_source_metadata_bytes: int | None = None,
    max_model_extract_bytes: int | None = None,
    scan_model_usage: bool | None = None,
    trust_model_files: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    project_dir: Path | str | None = None,
    check_url: Callable[[str], None] | None = None,
    max_download_bytes: int | None = None,
    credentials: CredentialPolicy | None = None,
) -> str:
    """Generate an Analyzed SPDX 3 SBOM for a built Python wheel.

    *wheel_path* may be a PyPI project or release URL (a ``str``; a
    :class:`~pathlib.Path` is always a local file): the release's wheel that
    best matches the running environment is downloaded and read
    (:func:`~pitloom.assemble.generate_pypi_sbom`): *check_url* is called
    with every URL of the release lookup and the download before it is
    requested (a dependency's licence lookup does not pass through it), and
    *max_download_bytes* caps the file. For a local wheel *check_url* is not used
    and *max_download_bytes* has no effect (one ``WARNING:``; an invalid
    value raises all the same).

    A wheel has no ``[tool.pitloom]`` of its own, and none is borrowed: not
    from the current directory, not from beside the wheel -- either may
    belong to an unrelated project. Settings come from the arguments, then
    *pitloom_config* when the caller names one explicitly, then the built-in
    defaults. The same holds for the registry: *id_registry*, else the explicit
    config's ``id-registry``; no ``loom-id-registry.json`` is searched for.
    The copy of that registry a build put in the wheel is left out, with one
    ``WARNING:``, when its path below the project directory is the member's
    (see :func:`~pitloom.id_registry.registry_copy` for the directory).

    *project_dir* names the project directory the wheel was built from: its
    members are then keyed below that directory's path from the registry's
    root (a registry above the project, a monorepo), as ``embed-wheel
    --project-dir`` keys them. Nothing is read from it; without a registry
    it has no effect, with one ``WARNING:``.

    *credentials* (:class:`~pitloom.core.credential_policy.CredentialPolicy`)
    adds to the credentials an explicit *pitloom_config* accepts.

    An explicit *pitloom_config* applies in full, identity included: its
    creators, creation datetime and comment fill in when *creation_metadata*
    is not given.

    AI models inside the wheel are found; *scan_model_usage* also records
    which Python files in it reference them. One model file is copied out
    of the wheel at a time, each up to *max_model_extract_bytes*
    (``--max-model-extract-bytes``; else the config's
    ``max-model-extract-bytes``, 512 MiB by default) and four times that in
    all, counting bytes copied and bytes read from archive
    members; a model beyond either limit is listed without metadata. Models
    in a format whose reader a hostile file can crash or hang (fastText,
    GGUF, HDF5, ONNX, PyTorch ``.pt``/``.pth``) are listed without metadata
    too, with one ``INFO:``, unless *trust_model_files* (for a wheel you
    trust only; it has no config key, so a config cannot opt in).

    ``extract_file_header``/``content_type``/``enrich`` have no parameter
    here: reading a built wheel scans no file headers or content types, and
    its AI models are not enriched (see :data:`pitloom.core.inert_options.INERT`).
    ``content_type_method`` does apply, because it also steers whether
    dependency originator enrichment fetches a remote authors file.

    Raises:
        ValueError: The wheel is refused as a whole
            (:class:`~pitloom.core.wheel_dist_info.WheelRefused`): not a ZIP
            archive, a member cannot be read, two members have one name or
            one holds a NUL; or *max_model_extract_bytes* is not an
            integer of at least 1.
        FileNotFoundError: Nothing is at *wheel_path*, or not a regular
            file; or *project_dir* is given and is not a directory
            (``input-not-found``, carrying the code).
        pitloom.messages.CodedValueError: *wheel_path* cannot be looked at
            (``file-unreadable``: a directory on its way refuses search).
        OSError: The file itself cannot be opened (its own permissions, a
            transient I/O error).
        pitloom.extract.remote.errors.RemoteSourceError: a PyPI URL's
            wheel could not be fetched or verified (``pypi.*``).
    """
    if isinstance(wheel_path, str) and is_pypi_url(wheel_path):
        return generate_pypi_sbom(
            wheel_path,
            kind=WHEEL_FILE,
            check_url=check_url,
            max_download_bytes=max_download_bytes,
            output_path=output_path,
            creation_metadata=creation_metadata,
            pretty=pretty,
            describe_relationship=describe_relationship,
            id_registry=id_registry,
            provenance=provenance,
            offline=offline,
            content_type_method=content_type_method,
            update_id_registry=update_id_registry,
            max_source_metadata_bytes=max_source_metadata_bytes,
            max_model_extract_bytes=max_model_extract_bytes,
            scan_model_usage=scan_model_usage,
            trust_model_files=trust_model_files,
            pitloom_config=pitloom_config,
            project_dir=project_dir,
            credentials=credentials,
        )
    return generate_wheel_sbom_with_metadata(
        wheel_path,
        output_path=output_path,
        creation_metadata=creation_metadata,
        pretty=pretty,
        describe_relationship=describe_relationship,
        id_registry=id_registry,
        provenance=provenance,
        offline=offline,
        content_type_method=content_type_method,
        update_id_registry=update_id_registry,
        max_source_metadata_bytes=max_source_metadata_bytes,
        max_model_extract_bytes=max_model_extract_bytes,
        scan_model_usage=scan_model_usage,
        trust_model_files=trust_model_files,
        pitloom_config=pitloom_config,
        project_dir=project_dir,
        check_url=check_url,
        max_download_bytes=max_download_bytes,
        credentials=credentials,
    )[0]

pitloom.assemble.generate_wheel_sbom_with_metadata

generate_wheel_sbom_with_metadata(
    wheel_path: Path | str,
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    offline: bool | None = None,
    content_type_method: str | None = None,
    update_id_registry: bool | None = None,
    max_source_metadata_bytes: int | None = None,
    max_model_extract_bytes: int | None = None,
    scan_model_usage: bool | None = None,
    trust_model_files: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    project_dir: Path | str | None = None,
    check_url: Callable[[str], None] | None = None,
    max_download_bytes: int | None = None,
    acquisition: Acquisition | None = None,
    credentials: CredentialPolicy | None = None,
) -> tuple[str, ProjectMetadata]

:func:generate_wheel_sbom, and the :class:ProjectMetadata read from the wheel, for a caller that goes on to use the wheel's declared identity (it need not read METADATA again, and warn about it twice).

wheel_path is a local wheel only (a PyPI URL is read by :func:generate_wheel_sbom): check_url is not used and max_download_bytes has no effect (one WARNING:; an invalid value raises all the same). Both are accepted so that a caller forwarding :func:generate_wheel_sbom's options can call this instead.

acquisition records how the wheel was downloaded (set by :func:~pitloom.assemble.generate_pypi_sbom); it adds one provenance record on the main package, and the gated models' INFO: is the one for a download (reader-unsafe/remote, naming the file), not a local wheel's; trust_model_files lifts the gate the same way.

Raises:

Type Description
ValueError

The wheel is refused as a whole (:class:~pitloom.core.wheel_dist_info.WheelRefused): not a ZIP archive, a member cannot be read, two members have one name or one holds a NUL; or max_model_extract_bytes is not an integer of at least 1.

FileNotFoundError

Nothing is at wheel_path, or not a regular file; or project_dir is given and is not a directory (input-not-found, carrying the code).

CodedValueError

wheel_path cannot be looked at (file-unreadable: a directory on its way refuses search).

OSError

The file itself cannot be opened (its own permissions, a transient I/O error).

Source code in pitloom/assemble/_generators_wheel.py
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
def generate_wheel_sbom_with_metadata(
    wheel_path: Path | str,
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    offline: bool | None = None,
    content_type_method: str | None = None,
    update_id_registry: bool | None = None,
    max_source_metadata_bytes: int | None = None,
    max_model_extract_bytes: int | None = None,
    scan_model_usage: bool | None = None,
    trust_model_files: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    project_dir: Path | str | None = None,
    check_url: Callable[[str], None] | None = None,
    max_download_bytes: int | None = None,
    acquisition: Acquisition | None = None,
    credentials: CredentialPolicy | None = None,
) -> tuple[str, ProjectMetadata]:
    """:func:`generate_wheel_sbom`, and the :class:`ProjectMetadata` read from
    the wheel, for a caller that goes on to use the wheel's declared identity
    (it need not read ``METADATA`` again, and warn about it twice).

    *wheel_path* is a local wheel only (a PyPI URL is read by
    :func:`generate_wheel_sbom`): *check_url* is not used and
    *max_download_bytes* has no effect (one ``WARNING:``; an invalid value
    raises all the same). Both are accepted so that a caller forwarding
    :func:`generate_wheel_sbom`'s options can call this instead.

    *acquisition* records how the wheel was downloaded (set by
    :func:`~pitloom.assemble.generate_pypi_sbom`); it adds one provenance
    record on the main package, and the gated models' ``INFO:`` is the one
    for a download (``reader-unsafe/remote``, naming the file), not a local
    wheel's; *trust_model_files* lifts the gate the same way.

    Raises:
        ValueError: The wheel is refused as a whole
            (:class:`~pitloom.core.wheel_dist_info.WheelRefused`): not a ZIP
            archive, a member cannot be read, two members have one name or
            one holds a NUL; or *max_model_extract_bytes* is not an
            integer of at least 1.
        FileNotFoundError: Nothing is at *wheel_path*, or not a regular
            file; or *project_dir* is given and is not a directory
            (``input-not-found``, carrying the code).
        pitloom.messages.CodedValueError: *wheel_path* cannot be looked at
            (``file-unreadable``: a directory on its way refuses search).
        OSError: The file itself cannot be opened (its own permissions, a
            transient I/O error).
    """
    configure_logging()
    del check_url  # nothing is fetched for a local wheel
    if max_download_bytes is not None:
        require_download_override(max_download_bytes)  # even if inert
        settle_inert(WHEEL, wheel_path, {"max_download_bytes": max_download_bytes})
    wheel_path_obj = Path(wheel_path)
    require_wheel_file(wheel_path)
    cfg = resolve_standalone_config(
        pitloom_config,
        ConfigOverrides(
            provenance=provenance,
            offline=offline,
            content_type_method=content_type_method,
            pretty=pretty,
            describe_relationship=describe_relationship,
            update_id_registry=update_id_registry,
            max_source_metadata_bytes=max_source_metadata_bytes,
            max_model_extract_bytes=max_model_extract_bytes,
            scan_model_usage=scan_model_usage,
            credentials=credentials,
        ),
    )
    # Resolved before the expensive read_wheel()/find_phantom_dependencies()
    # calls below -- a declared-but-missing/malformed registry should fail
    # fast, never after paying for a full wheel read first.
    resolved_registry = resolve_registry(
        id_registry,
        cfg.id_registry,
        Path.cwd(),
        refuse_credentials=cfg.credential_policy.refuse,
    )
    origin_dir = archive_project_dir(project_dir, resolved_registry, wheel_path)
    project_metadata, project_files = read_wheel(wheel_path_obj)
    # A copy of an in-tree registry the build put in the wheel: neither a
    # file of the SBOM nor of its Merkle root.
    project_files = without_registry_copies(
        project_files, registry_copy(resolved_registry, origin_dir)
    )
    project_metadata.files = project_files
    ai_models = scan_wheel_for_ai_models(
        wheel_path_obj,
        scan_usage=cfg.scan_model_usage is True,
        usage_hint=lambda: cfg.scan_model_usage is None,
        max_bytes=cfg.max_model_extract_bytes,
        trust=trust_model_files is True,
        # A download is untrusted remote input: its line names the file.
        downloaded_as=None if acquisition is None else acquisition.filename,
    )
    phantom_deps = find_phantom_dependencies(project_files)

    doc = DocumentModel(
        project=project_metadata,
        creation_metadata=creation_metadata or cfg.creation_metadata,
        ai_models=ai_models,
        phantom_dependencies=phantom_deps,
        acquisition=acquisition,
        **wheel_document_identity(project_metadata, wheel_path_obj, origin_dir),
    )
    exporter = build(
        doc,
        merkle_root=merkle_root_of_files(project_files),
        sbom_type=spdx3_bindings.software_SbomType.analyzed,
        registry=resolved_registry,
        **cfg.assemble_options,
    )

    # Before the registry is written: a refused SBOM leaves it unchanged.
    sbom_json = exporter.to_json(
        pretty=cfg.pretty,
        describe_relationship=bool(cfg.describe_relationship),
        credentials=cfg.credential_policy,
    )

    _sync_registry(exporter, resolved_registry, cfg.update_id_registry)

    write_sbom_output(sbom_json, output_path)

    return sbom_json, project_metadata

pitloom.assemble.generate_model_sbom

generate_model_sbom(
    source: Path | str,
    *,
    offline: bool | None = None,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    max_source_metadata_bytes: int | None = None,
    pitloom_config: PitloomConfig | None = None,
    shown: str | None = None,
    max_download_bytes: int | None = None,
    check_url: Callable[[str], None] | None = None,
    credentials: CredentialPolicy | None = None,
) -> str

Generate an Analyzed SPDX 3 AIBOM for a local model file or HF repository.

Settings resolve as :func:~pitloom.assemble.generate_wheel_sbom describes: arguments, then an explicit pitloom_config, then the built-in defaults. Nothing is read from the current directory or from the model file's own directory.

Four parameters apply to one source kind only, and warn when given for the other (see :data:pitloom.core.inert_options.INERT): offline and max_download_bytes for a Hugging Face source (a local file never reaches the network), and enrich/id_registry for a local file; a local folder, its one model file (:func:~pitloom.extract.model_target.model_path_of).

A Hugging Face source's metadata files are downloaded as :func:~pitloom.extract.remote.read_huggingface describes, under the policy every remote route resolves (:func:~pitloom.core.config_cascade.resolve_fetch_policy): with offline (else pitloom_config's) true nothing is fetched (huggingface.offline, offline-unusable); each file is capped at max_download_bytes (else pitloom_config's max-download-bytes, else 512 MiB); check_url is called with each file's URL and each redirect target before it is requested (a local file does not use it).

shown is how messages name a local model file (default: as given): a caller that copied it to a temporary directory names it as its user knows it (its path in a Git repository). The SBOM names the file by its own name alone either way.

credentials (:class:~pitloom.core.credential_policy.CredentialPolicy) adds to the credentials pitloom_config accepts.

Raises:

Type Description
CodedValueError

pypi-url-unusable: source is a PyPI URL (a release is not a model), refused as loom model refuses it, before anything is read or fetched; logged as well.

Source code in pitloom/assemble/_model_generator.py
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
def generate_model_sbom(
    source: Path | str,
    *,
    offline: bool | None = None,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    max_source_metadata_bytes: int | None = None,
    pitloom_config: PitloomConfig | None = None,
    shown: str | None = None,
    max_download_bytes: int | None = None,
    check_url: Callable[[str], None] | None = None,
    credentials: CredentialPolicy | None = None,
) -> str:
    """Generate an Analyzed SPDX 3 AIBOM for a local model file or HF repository.

    Settings resolve as :func:`~pitloom.assemble.generate_wheel_sbom`
    describes: arguments, then an explicit *pitloom_config*, then the
    built-in defaults. Nothing is read from the current directory or from
    the model file's own directory.

    Four parameters apply to one source kind only, and warn when given for
    the other (see :data:`pitloom.core.inert_options.INERT`):
    *offline* and *max_download_bytes* for a Hugging Face source (a local
    file never reaches the network), and *enrich*/*id_registry* for a local
    file; a local folder, its one model file
    (:func:`~pitloom.extract.model_target.model_path_of`).

    A Hugging Face source's metadata files are downloaded as
    :func:`~pitloom.extract.remote.read_huggingface` describes, under the
    policy every remote route resolves
    (:func:`~pitloom.core.config_cascade.resolve_fetch_policy`): with
    *offline* (else *pitloom_config*'s) true nothing is fetched
    (``huggingface.offline``, ``offline-unusable``); each file is capped at
    *max_download_bytes* (else *pitloom_config*'s ``max-download-bytes``,
    else 512 MiB); *check_url* is called with each file's URL and each
    redirect target before it is requested (a local file does not use it).

    *shown* is how messages name a local model file (default: as given): a
    caller that copied it to a temporary directory names it as its user
    knows it (its path in a Git repository). The SBOM names the file by its
    own name alone either way.

    *credentials* (:class:`~pitloom.core.credential_policy.CredentialPolicy`)
    adds to the credentials *pitloom_config* accepts.

    Raises:
        CodedValueError: ``pypi-url-unusable``: *source* is a PyPI URL (a
            release is not a model), refused as ``loom model`` refuses it,
            before anything is read or fetched; logged as well.
    """
    configure_logging()
    _refuse_pypi_url(source)
    if max_download_bytes is not None:
        require_download_override(max_download_bytes)  # even if inert
    source_str = str(source)
    is_hf = is_huggingface_source(source_str)
    if is_hf:
        source_str = source_str.strip()
    settle_inert(
        HF if is_hf else MODEL_FILE,
        source_str,
        {
            "offline": offline,
            "enrich": enrich,
            "id_registry": id_registry,
            "max_download_bytes": max_download_bytes,
        },
    )
    cfg = resolve_standalone_config(
        pitloom_config,
        ConfigOverrides(
            provenance=provenance,
            enrich=enrich,
            offline=offline,
            pretty=pretty,
            describe_relationship=describe_relationship,
            max_source_metadata_bytes=max_source_metadata_bytes,
            credentials=credentials,
        ),
    )
    enrichment_results: list[EnrichmentResult] = []

    resolved_registry: IdRegistry | None = None
    if is_hf:
        policy = resolve_fetch_policy(
            pitloom_config,
            offline=offline,
            max_download_bytes=max_download_bytes,
            check_url=check_url,
        )
        model = read_huggingface(source_str, policy=policy)
        entity_spdx_id = digest = None
    else:
        model_path = model_path_of(Path(source), subject=source_str)
        # Resolved before _read_local_model()/run_enrichers() below -- a
        # declared-but-missing/malformed registry should fail fast, never
        # after paying for a model read and enrichment first.
        resolved_registry = resolve_registry(
            id_registry,
            cfg.id_registry,
            Path.cwd(),
            refuse_credentials=cfg.credential_policy.refuse,
        )
        model = _read_local_model(model_path, shown)
        digest = _model_file_digests(model_path)
        entity_spdx_id = _model_registry_id(
            resolved_registry,
            model,
            model_path,
            lambda: None if digest is None else digest.sha256,
        )
        enrichment_results = run_enrichers(model, cfg.enrich, model_path.parent)

    exporter = build_model(
        model,
        creation_metadata or cfg.creation_metadata,
        entity_spdx_id=entity_spdx_id,
        registry=resolved_registry,
        provenance=cfg.provenance,
        enrichment_results=enrichment_results,
        digest=digest,
    )

    sbom_json = exporter.to_json(
        pretty=cfg.pretty,
        describe_relationship=bool(cfg.describe_relationship),
        credentials=cfg.credential_policy,
    )

    write_sbom_output(sbom_json, output_path)

    return sbom_json

pitloom.assemble.generate_env_sbom

generate_env_sbom(
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    offline: bool | None = None,
    content_type_method: str | None = None,
    update_id_registry: bool | None = None,
    max_source_metadata_bytes: int | None = None,
    pitloom_config: PitloomConfig | None = None,
    credentials: CredentialPolicy | None = None,
) -> str

Generate a Deployed SPDX 3 SBOM for the current installed environment.

Settings and the registry resolve exactly as :func:~pitloom.assemble.generate_wheel_sbom describes: arguments, then an explicit pitloom_config, then the built-in defaults, with nothing borrowed from the current directory.

content_type_method applies here for one of its two jobs only: it steers whether each installed package's originator enrichment fetches a remote authors file. The per-file contentType half needs file scanning, which reading an installed environment never performs.

credentials (:class:~pitloom.core.credential_policy.CredentialPolicy) adds to the credentials pitloom_config accepts.

Source code in pitloom/assemble/_generators_env.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
def generate_env_sbom(
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    provenance: ProvenanceConfig | None = None,
    offline: bool | None = None,
    content_type_method: str | None = None,
    update_id_registry: bool | None = None,
    max_source_metadata_bytes: int | None = None,
    pitloom_config: PitloomConfig | None = None,
    credentials: CredentialPolicy | None = None,
) -> str:
    """Generate a Deployed SPDX 3 SBOM for the current installed environment.

    Settings and the registry resolve exactly as
    :func:`~pitloom.assemble.generate_wheel_sbom` describes: arguments, then
    an explicit *pitloom_config*, then the built-in defaults, with nothing
    borrowed from the current directory.

    ``content_type_method`` applies here for one of its two jobs only: it
    steers whether each installed package's originator enrichment fetches a
    remote authors file. The per-file ``contentType`` half needs file
    scanning, which reading an installed environment never performs.

    *credentials* (:class:`~pitloom.core.credential_policy.CredentialPolicy`)
    adds to the credentials *pitloom_config* accepts.
    """
    configure_logging()
    cfg = resolve_standalone_config(
        pitloom_config,
        ConfigOverrides(
            provenance=provenance,
            offline=offline,
            content_type_method=content_type_method,
            pretty=pretty,
            describe_relationship=describe_relationship,
            update_id_registry=update_id_registry,
            max_source_metadata_bytes=max_source_metadata_bytes,
            credentials=credentials,
        ),
    )
    # Resolved before the expensive read_environment() call (pipdeptree)
    # below -- a declared-but-missing/malformed registry should fail fast,
    # never after paying for a full environment scan first.
    resolved_registry = resolve_registry(
        id_registry,
        cfg.id_registry,
        Path.cwd(),
        refuse_credentials=cfg.credential_policy.refuse,
    )
    project_metadata, env_tree = read_environment()

    doc = DocumentModel(
        project=project_metadata,
        creation_metadata=creation_metadata or cfg.creation_metadata,
        ai_models=[],
    )
    exporter = build_deployed(
        doc,
        env_tree=env_tree,
        registry=resolved_registry,
        **cfg.assemble_options,
    )

    # Before the registry is written: a refused SBOM leaves it unchanged.
    sbom_json = exporter.to_json(
        pretty=cfg.pretty,
        describe_relationship=bool(cfg.describe_relationship),
        credentials=cfg.credential_policy,
    )

    _sync_registry(exporter, resolved_registry, cfg.update_id_registry)

    write_sbom_output(sbom_json, output_path)

    return sbom_json

pitloom.assemble.enrich_model

enrich_model(
    source: Path | str,
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    enrich: bool | None = None,
    project_target: Path | str | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    use_lockfile: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    credentials: CredentialPolicy | None = None,
) -> str

Run enrichment only for a local model file.

Settings come from the arguments, then an explicit pitloom_config, then the built-in defaults; nothing is read from the current directory or from the model file's directory. The registry is id_registry, else the explicit config's id-registry; with project_target, the project's own id-registry key applies instead, since that project is the document the fragment will merge into, and the credentials its config accepts join those of pitloom_config and credentials (:class:~pitloom.core.credential_policy.CredentialPolicy).

Source code in pitloom/assemble/_model_generator.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def enrich_model(
    source: Path | str,
    *,
    output_path: Path | None = None,
    creation_metadata: CreationMetadata | None = None,
    pretty: bool | None = None,
    enrich: bool | None = None,
    project_target: Path | str | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    use_lockfile: bool | None = None,
    pitloom_config: PitloomConfig | None = None,
    credentials: CredentialPolicy | None = None,
) -> str:
    """Run enrichment only for a local model file.

    Settings come from the arguments, then an explicit *pitloom_config*,
    then the built-in defaults; nothing is read from the current directory
    or from the model file's directory. The registry is *id_registry*,
    else the explicit config's ``id-registry``; with *project_target*, the
    project's own ``id-registry`` key applies instead, since that project
    is the document the fragment will merge into, and the credentials its
    config accepts join those of *pitloom_config* and *credentials*
    (:class:`~pitloom.core.credential_policy.CredentialPolicy`).
    """
    configure_logging()
    source_str = str(source)
    if is_huggingface_source(source_str):
        raise invalid_value(Parameter("source"), "local-model", got=source_str)
    # The CLI passes use_lockfile through, so this is the one layer that
    # settles it, before any work (an sdist project target as a project).
    if project_target is None:
        settle_inert(ENRICH_STANDALONE, source_str, {"use_lockfile": use_lockfile})
    elif is_sdist_archive(Path(project_target)):
        settle_inert(SDIST, project_target, {"use_lockfile": use_lockfile})
    cfg = resolve_standalone_config(
        pitloom_config, ConfigOverrides(pretty=pretty, credentials=credentials)
    )
    accepted = cfg.credential_policy

    model_path = Path(source)
    # Registry resolved before _read_local_model()/run_enrichers() below -- a
    # declared-but-missing/malformed registry should fail fast, never
    # after paying for a model read and enrichment first.
    if project_target is None:
        base_doc_identity = None
        resolved_registry = resolve_registry(
            id_registry,
            cfg.id_registry,
            Path.cwd(),
            refuse_credentials=accepted.refuse,
        )
    else:
        # The project the fragment merges into, resolved as its base SBOM
        # is: its identity and registry come from the config that SBOM
        # used (an explicit config, else the project's own). Registry
        # resolved right after resolve_project_with_lockfile(), before
        # _doc_identity_of()'s own file walk.
        project_dir = TypedPath(project_target)  # named as given
        base_metadata, base_config, _ = resolve_project_with_lockfile(
            project_dir, use_lockfile, pitloom_config
        )
        # Accepted, but given for the project's SBOM, not this fragment: a
        # fingerprint of them that matches nothing here is not stale.
        accepted = accepted.inheriting(base_config.credential_policy)
        # An sdist's directory is not its project, as in its base SBOM.
        resolved_registry = resolve_registry(
            id_registry,
            base_config.id_registry,
            registry_base_dir(project_dir),
            refuse_credentials=accepted.refuse,
        )
        base_doc_identity = _doc_identity_of(
            project_dir, base_metadata, resolved_registry
        )

    model = _read_local_model(model_path)
    # Calling enrich_model() is itself the opt-in, so the config's enrich
    # setting is no gate here; only an explicit enrich=False turns it off.
    enrich_config = dataclasses.replace(cfg.enrich, local=enrich is not False)
    results = run_enrichers(model, enrich_config, model_path.parent)

    # Hashed only to gate the lookup: the fragment has no ai_AIPackage. The
    # argument is from the current directory, the key from the registry's
    # root (with --project-dir, the project's registry).
    entity_spdx_id = _model_registry_id(
        resolved_registry,
        model,
        model_path,
        functools.partial(_model_file_sha256, model_path),
    )

    exporter = build_enrichment_fragment(
        model,
        results,
        creation_metadata or cfg.creation_metadata,
        entity_spdx_id=entity_spdx_id,
        base_doc_identity=base_doc_identity,
        registry=resolved_registry,
    )

    fragment_json = exporter.to_json(pretty=cfg.pretty, credentials=accepted)

    write_sbom_output(fragment_json, output_path)

    return fragment_json

Git repositories

pitloom.extract.remote.fetch_git_project

fetch_git_project(
    url: str,
    *,
    policy: RemoteFetchPolicy = RemoteFetchPolicy(),
    trust_model_files: bool = False,
) -> Iterator[GitCheckout]

Fetch the repository url names into a temporary directory (pitloom-git- and eight random characters), removed on exit (no termination guard: Ctrl-C removes it, a process ended by SIGTERM or SIGKILL leaves it); one that cannot be fully removed (a file still held open on Windows) is left behind with one WARNING:, never an error.

Within the block, the reads are a temporary clone's (:func:~pitloom.core.clone_mark.reading_remote_clone, as in :meth:GitCheckout.reading): nothing out of the checkout's root is read, the model readers a wheel scan does not run are not run, and the repository's build-time code is not run. The mark is reset on every exit and belongs to the calling thread's context alone.

With trust_model_files the caller vouches for the repository's model files: the readers a wheel scan does not run are run (the build-time code is still not run). The default is to run none of them.

policy (:func:~pitloom.core.config_cascade.resolve_fetch_policy) says what the fetch may do. Its check_url is called with the URL of every redirect target, without user information, before it is requested and raises for one that must not be fetched; Pitloom does not check the URL it is given (the caller does, as it knows its own policy; the PyPI route, unlike this one, passes its first URLs to its check too). With offline nothing is fetched. The fetch is stopped once the checkout (the .git directory included) takes more disk than max_bytes (git.too-large).

Raises:

Type Description
RemoteSourceError

the URL names no fetchable repository, ref or folder (git.url-invalid, checked before offline; a PyPI URL is catalogued pypi-url-unusable), git is missing, offline is set (git.offline, offline-unusable), git cannot reach the server (git.clone-failed, download-network-failed) or does not finish in time (git.timeout, download-timeout), or the repository is larger than max_bytes (over-cap).

Exception

whatever check_url raises, unchanged.

Source code in pitloom/extract/remote/git.py
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
@contextmanager
def fetch_git_project(
    url: str,
    *,
    policy: RemoteFetchPolicy = RemoteFetchPolicy(),
    trust_model_files: bool = False,
) -> Iterator[GitCheckout]:
    """Fetch the repository *url* names into a temporary directory
    (``pitloom-git-`` and eight random characters), removed on exit (no
    termination guard: Ctrl-C removes it, a process ended by SIGTERM or
    SIGKILL leaves it); one that cannot be fully removed (a file still held
    open on Windows) is left behind with one ``WARNING:``, never an error.

    Within the block, the reads are a temporary clone's
    (:func:`~pitloom.core.clone_mark.reading_remote_clone`, as in
    :meth:`GitCheckout.reading`): nothing out of the checkout's root is read,
    the model readers a wheel scan does not run are not run, and the
    repository's build-time code is not run. The mark is reset on every exit
    and belongs to the calling thread's context alone.

    With *trust_model_files* the caller vouches for the repository's model
    files: the readers a wheel scan does not run are run (the build-time code
    is still not run). The default is to run none of them.

    *policy* (:func:`~pitloom.core.config_cascade.resolve_fetch_policy`)
    says what the fetch may do. Its ``check_url`` is called with the URL of
    every redirect target, without user information, before it is requested
    and raises for one that must not be fetched; Pitloom does not check the
    URL it is given (the caller does, as it knows its own policy; the PyPI
    route, unlike this one, passes its first URLs to its check too). With
    ``offline`` nothing is fetched. The fetch is stopped once the checkout
    (the ``.git`` directory included) takes more disk than ``max_bytes``
    (``git.too-large``).

    Raises:
        RemoteSourceError: the URL names no fetchable repository, ref or
            folder (``git.url-invalid``, checked before ``offline``; a
            PyPI URL is catalogued ``pypi-url-unusable``), ``git`` is
            missing, ``offline`` is set (``git.offline``,
            ``offline-unusable``), git cannot reach the server
            (``git.clone-failed``, ``download-network-failed``) or does not
            finish in time (``git.timeout``, ``download-timeout``), or the
            repository is larger than ``max_bytes`` (``over-cap``).
        Exception: whatever ``check_url`` raises, unchanged.
    """
    runner = GitRunner(max_bytes=policy.max_bytes)
    # Each git call has ended (its process group too) before the removal.
    with temp_dir(CHECKOUT_DIR_PREFIX, frame=GIT_FRAME) as work:
        checkout = _prepare(url, str(work), runner, policy)
        checkout = replace(checkout, trust_model_files=trust_model_files)
        with reading_remote_clone(checkout.root, trust_model_files=trust_model_files):
            yield checkout

pitloom.extract.remote.RemoteSourceError

RemoteSourceError(
    code: str,
    message: str,
    *,
    pitloom_code: str | None = None,
)

A remote source could not be read.

code names the failure for a caller that maps it to its own vocabulary (git.clone-failed, git.timeout, git.not-found, git.offline, git.url-invalid, git.ref-not-found, git.path-not-found, git.too-many-redirects, git.output-too-large, git.too-large, git.no-project; for a PyPI URL pypi.offline, pypi.url-refused, pypi.too-many-redirects, pypi.project-not-found, pypi.release-not-found, pypi.no-wheel, pypi.no-compatible-wheel, pypi.no-sdist, pypi.response-invalid, pypi.digest-mismatch, pypi.too-large, pypi.save-failed, pypi.download-failed, pypi.download-timeout; for a Hugging Face model huggingface.offline and, for one of its files, huggingface.download-failed, huggingface.download-timeout, huggingface.too-large, huggingface.url-refused, huggingface.too-many-redirects, huggingface.save-failed; and any code a caller's own URL check raises through :class:RemoteSourceError); the message is for the user. pitloom_code is the catalogued code of the condition when it has one, shared by the routes: over-cap for git.too-large, git.output-too-large and <route>.too-large; offline-unusable for each .offline; download-timeout for git.timeout; download-network-failed for a git.clone-failed whose cause is the network, git-repository-unusable for any other (git-repository-unusable/empty for an empty repository); every pypi.*, huggingface.* and git.* code has one. It is read by :func:pitloom.messages.code_of.

Source code in pitloom/extract/remote/errors.py
47
48
49
50
51
52
53
54
55
56
57
def __init__(
    self, code: str, message: str, *, pitloom_code: str | None = None
) -> None:
    super().__init__(message)
    self.code = code
    #: The catalogued code of the condition, or ``None``.
    self.pitloom_code = pitloom_code
    #: The catalogue entry and the values its line was written from,
    #: when the error is one: a caller that goes on without the input
    #: says it again as that entry's ``WARNING:`` line.
    self.said: tuple[object, dict[str, object]] | None = None

__reduce__

__reduce__() -> tuple[
    type[RemoteSourceError],
    tuple[str, str],
    dict[str, object],
]

Copied and pickled by its code and message, and every attribute set on it: args holds the message only, so the default would call __init__ without the code.

Source code in pitloom/extract/remote/errors.py
59
60
61
62
63
64
65
def __reduce__(
    self,
) -> tuple[type[RemoteSourceError], tuple[str, str], dict[str, object]]:
    """Copied and pickled by its code and message, and every attribute
    set on it: ``args`` holds the message only, so the default would call
    ``__init__`` without the code."""
    return (type(self), (self.code, str(self)), dict(self.__dict__))

Wheel embedding

pitloom.embed.embed_wheel_sbom

embed_wheel_sbom(
    wheel_path: Path | str,
    *,
    project_dir: Path | str | None = None,
    pitloom_config: PitloomConfig | None = None,
    sbom_path: Path | str | None = None,
    output_path: Path | str | None = None,
    sbom_basename: str | None = None,
    creation_metadata: CreationMetadata | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    overrides: ConfigOverrides | None = None,
    allow_mismatch: bool = False,
    allow_signed_wheel: bool = False,
    file_cache: EmbedFileCache | None = None,
) -> tuple[Path, str, str, tuple[str, ...], bool]

Generate and embed a PEP 770 SBOM into a built Python wheel.

When sbom_path supplies an externally-generated SBOM, its declared subject name/version is cross-checked against the wheel's own .dist-info/METADATA before anything is written -- see :func:_enforce_sbom_name_version. A genuine mismatch raises ValueError unless allow_mismatch. A signed wheel (RECORD.jws/ RECORD.p7s) raises ValueError unless allow_signed_wheel, which removes the signature the embed would invalidate. A Pitloom-generated SBOM (sbom_path unset) is never checked: it is built from the wheel's own metadata.

With project_dir (the project the wheel was built from) the SBOM is a Build SBOM from that directory's rescan and the wheel's own files; without it, an Analyzed SBOM of the wheel alone. pitloom_config replaces the project's own [tool.pitloom]; overrides are the per-run settings (:class:~pitloom.core.config_cascade.ConfigOverrides); sbom_basename, creation_metadata and id_registry are as for :func:~pitloom.assemble.generate. output_path also receives a copy of the SBOM JSON.

file_cache: advanced/batch use only -- share one :class:EmbedFileCache across several calls that target the same project_dir/pitloom_config/overrides.build_options (e.g. one wheel per call, in a loop) to resolve project_dir's file list (and run any --allow-build real PEP 517 build) once for the whole batch instead of once per call. A batch logs each ineffective-option warning, the model-usage INFO: hint and each gated-format INFO: once. Left None (the default), this call resolves and cleans up its own file list. When given, this call does NOT clean up -- make every call of the batch inside one with EmbedFileCache() as file_cache: block, whose exit does; a cache used outside its block raises :class:RuntimeError.

Returns:

Type Description
Path

``(wheel path, SBOM arcname in the wheel, SBOM JSON, arcnames removed,

str

floored)`, as :func:~pitloom._embed_wheel.embed_sbom_in_wheel`

str

returns them, with the SBOM JSON third.

Raises:

Type Description
ValueError

The wheel is refused as a whole (:class:~pitloom.core.wheel_dist_info.WheelRefused: not a ZIP archive, a member cannot be read, two members have one name or one holds a NUL, a member of its own .dist-info has a non-conforming name), it has no single own .dist-info, or the SBOM's name/version mismatches (see above). The wheel is left as it was.

FileNotFoundError

Nothing is at wheel_path, or not a regular file (input-not-found, carrying the code).

CodedValueError

wheel_path cannot be looked at (file-unreadable: a directory on its way refuses search), or a URL field of the SBOM holds a credential the run does not accept in the refuse mode (credentials-unsafe/refused; the SBOM at sbom_path is checked as given, by overrides.credentials alone, and never rewritten). The wheel is left as it was.

CodedOSError

The system refused a write (file-unwritable): the new wheel (named by its file name; the wheel is left as it was) or the -o copy at output_path (as given), written after the wheel, which then holds the SBOM; or a read of a member of the wheel (file-unreadable, an I/O error).

OSError

The file itself cannot be opened (its own permissions, a transient I/O error).

Source code in pitloom/embed.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
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
def embed_wheel_sbom(
    wheel_path: Path | str,
    *,
    project_dir: Path | str | None = None,
    pitloom_config: PitloomConfig | None = None,
    sbom_path: Path | str | None = None,
    output_path: Path | str | None = None,
    sbom_basename: str | None = None,
    creation_metadata: CreationMetadata | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    overrides: ConfigOverrides | None = None,
    allow_mismatch: bool = False,
    allow_signed_wheel: bool = False,
    file_cache: EmbedFileCache | None = None,
) -> tuple[Path, str, str, tuple[str, ...], bool]:
    """Generate and embed a PEP 770 SBOM into a built Python wheel.

    When *sbom_path* supplies an externally-generated SBOM, its declared
    subject name/version is cross-checked against the wheel's own
    ``.dist-info/METADATA`` before anything is written -- see
    :func:`_enforce_sbom_name_version`. A genuine mismatch raises
    ``ValueError`` unless *allow_mismatch*. A signed wheel (``RECORD.jws``/
    ``RECORD.p7s``) raises ``ValueError`` unless *allow_signed_wheel*, which
    removes the signature the embed would invalidate. A Pitloom-generated SBOM
    (*sbom_path* unset) is never checked: it is built from the wheel's own
    metadata.

    With *project_dir* (the project the wheel was built from) the SBOM is a
    Build SBOM from that directory's rescan and the wheel's own files;
    without it, an Analyzed SBOM of the wheel alone. *pitloom_config*
    replaces the project's own ``[tool.pitloom]``; *overrides* are the
    per-run settings (:class:`~pitloom.core.config_cascade.ConfigOverrides`);
    *sbom_basename*, *creation_metadata* and *id_registry* are as for
    :func:`~pitloom.assemble.generate`. *output_path* also receives a copy of
    the SBOM JSON.

    *file_cache*: advanced/batch use only -- share one
    :class:`EmbedFileCache` across several calls that target the same
    *project_dir*/*pitloom_config*/``overrides.build_options`` (e.g. one
    wheel per call, in a loop) to resolve *project_dir*'s file list (and
    run any ``--allow-build`` real PEP 517 build) once for the whole
    batch instead of once per call. A batch logs each ineffective-option
    warning, the model-usage ``INFO:`` hint and each gated-format ``INFO:``
    once. Left ``None`` (the default), this
    call resolves and cleans up its own file list. When given, *this*
    call does NOT clean up -- make every call of the batch inside one
    ``with EmbedFileCache() as file_cache:`` block, whose exit does; a
    cache used outside its block raises :class:`RuntimeError`.

    Returns:
        ``(wheel path, SBOM arcname in the wheel, SBOM JSON, arcnames removed,
        floored)``, as :func:`~pitloom._embed_wheel.embed_sbom_in_wheel`
        returns them, with the SBOM JSON third.

    Raises:
        ValueError: The wheel is refused as a whole
            (:class:`~pitloom.core.wheel_dist_info.WheelRefused`: not a ZIP
            archive, a member cannot be read, two members have one name or
            one holds a NUL, a member of its own ``.dist-info`` has a
            non-conforming name),
            it has no single own ``.dist-info``, or the SBOM's name/version
            mismatches (see above). The wheel is left as it was.
        FileNotFoundError: Nothing is at *wheel_path*, or not a regular
            file (``input-not-found``, carrying the code).
        pitloom.messages.CodedValueError: *wheel_path* cannot be looked at
            (``file-unreadable``: a directory on its way refuses search), or
            a URL field of the SBOM holds a credential the run does not
            accept in the ``refuse`` mode (``credentials-unsafe/refused``;
            the SBOM at *sbom_path* is
            checked as given, by ``overrides.credentials``
            alone, and never rewritten). The wheel is left as it was.
        pitloom.messages.CodedOSError: The system refused a write
            (``file-unwritable``): the new wheel (named by its file name;
            the wheel is left as it was) or the ``-o`` copy at
            *output_path* (as given), written after the wheel, which then
            holds the SBOM; or a read of a member of the wheel
            (``file-unreadable``, an I/O error).
        OSError: The file itself cannot be opened (its own permissions, a
            transient I/O error).
    """
    configure_logging()
    sbom_basename = checked_embed_basename(sbom_basename, _LIBRARY_BASENAME)
    require_wheel_file(wheel_path)
    # Not resolved: a symlink's name is the one judged, and the one the
    # embed reports; ``embed_sbom_in_wheel`` resolves to write.
    wheel_obj = Path(wheel_path).absolute()
    eff_overrides = overrides if overrides is not None else ConfigOverrides()
    if sbom_path is None:
        # Fails on a declared-but-bad registry before the wheel is read. An
        # external SBOM never touches the registry, so only without
        # *sbom_path*. The resolved registry replaces *id_registry*, so
        # _generate_embed_sbom_json() does not load the file again.
        id_registry = _resolve_embed_registry(
            project_dir, pitloom_config, id_registry, eff_overrides.credentials
        )
    # Before the SBOM is generated: that may run a build.
    refuse_unembeddable_wheel(wheel_obj, allow_signed_wheel)
    # The wheel's split Author-email is warned about only where its authors
    # are used.
    author_splits: list[AuthorSplit] = []
    wheel_metadata, _ = read_wheel(wheel_obj, author_splits=author_splits)

    sbom_json, eff_basename = _generate_embed_sbom_json(
        wheel_metadata,
        wheel_path=wheel_obj,
        project_dir=project_dir,
        pitloom_config=pitloom_config,
        sbom_path=sbom_path,
        sbom_basename=sbom_basename,
        creation_metadata=creation_metadata,
        id_registry=id_registry,
        overrides=eff_overrides,
        file_cache=file_cache,
        author_splits=author_splits,
    )
    wheel_name, wheel_version = wheel_identity(wheel_metadata)
    if sbom_path is not None:
        _enforce_sbom_name_version(
            wheel_obj.name,
            wheel_name,
            wheel_version,
            sbom_json,
            allow_mismatch=allow_mismatch,
        )
    # The identity just read goes down, so the embed does not read (and warn
    # about) the same METADATA again.
    res_path, arcname, removed_arcnames, timestamp_floored = embed_sbom_in_wheel(
        wheel_obj,
        sbom_json,
        sbom_filename=embed_filename(eff_basename),
        identity=(wheel_name, wheel_version),
        allow_signed_wheel=allow_signed_wheel,
    )

    write_sbom_copy(sbom_json, output_path)

    return res_path, arcname, sbom_json, removed_arcnames, timestamp_floored

pitloom.embed.embed_sbom_in_wheel

embed_sbom_in_wheel(
    wheel_path: Path | str,
    sbom_content: str | bytes,
    *,
    sbom_filename: str | None = None,
    identity: tuple[str | None, str | None] | None = None,
    allow_signed_wheel: bool = False,
) -> tuple[Path, str, tuple[str, ...], bool]

Embed an SPDX 3 SBOM into a built wheel archive (PEP 770).

A wheel carrying RECORD.jws/RECORD.p7s is refused unless allow_signed_wheel: the embed rewrites RECORD, so the signature would no longer verify, and it is removed (the removed names are in the result, as for a stale SBOM).

identity is the wheel's declared (name, version), where the caller has already read them from its METADATA: the default file name is made from it, and METADATA is not read, or warned about, again.

Returns:

Type Description
Path

(wheel path, SBOM arcname in the wheel, arcnames removed, floored):

str

the removed names are stale SBOMs and signature files; floored is

tuple[str, ...]

true when the ZIP entry timestamp was raised to 1980-01-01, the

bool

earliest a ZIP can hold.

Raises:

Type Description
FileNotFoundError

Nothing is at wheel_path, or not a regular file (input-not-found, carrying the code).

ValueError

sbom_content is empty or white space only (option-invalid), or the wheel's content is bad (missing/ambiguous .dist-info), or the wheel is refused (:class:~pitloom.core.wheel_dist_info.WheelRefused): not a ZIP archive, a member cannot be read (damaged, encrypted, unsupported, badly named), two members have one name or one holds a NUL, or a member of its own .dist-info has a non-conforming name, or it is signed and not allow_signed_wheel. The wheel is left as it was.

CodedValueError

wheel_path cannot be looked at (file-unreadable: a directory on its way refuses search).

CodedOSError

The system refused the write of the new wheel (no write permission on its directory, a full disk): file-unwritable, the wheel named by its file name; or a read of a member (an I/O error): file-unreadable. The wheel is left as it was.

OSError

An environment problem opening the file itself (its own permissions, a transient I/O error) -- kept as its own exception type, not folded into ValueError.

Source code in pitloom/_embed_wheel.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
def embed_sbom_in_wheel(
    wheel_path: Path | str,
    sbom_content: str | bytes,
    *,
    sbom_filename: str | None = None,
    identity: tuple[str | None, str | None] | None = None,
    allow_signed_wheel: bool = False,
) -> tuple[Path, str, tuple[str, ...], bool]:
    """Embed an SPDX 3 SBOM into a built wheel archive (PEP 770).

    A wheel carrying ``RECORD.jws``/``RECORD.p7s`` is refused unless
    *allow_signed_wheel*: the embed rewrites ``RECORD``, so the signature
    would no longer verify, and it is removed (the removed names are in the
    result, as for a stale SBOM).

    *identity* is the wheel's declared (name, version), where the caller has
    already read them from its ``METADATA``: the default file name is made
    from it, and ``METADATA`` is not read, or warned about, again.

    Returns:
        ``(wheel path, SBOM arcname in the wheel, arcnames removed, floored)``:
        the removed names are stale SBOMs and signature files; *floored* is
        true when the ZIP entry timestamp was raised to 1980-01-01, the
        earliest a ZIP can hold.

    Raises:
        FileNotFoundError: Nothing is at *wheel_path*, or not a regular
            file (``input-not-found``, carrying the code).
        ValueError: *sbom_content* is empty or white space only
            (``option-invalid``), or the wheel's content is bad
            (missing/ambiguous ``.dist-info``), or the wheel is refused
            (:class:`~pitloom.core.wheel_dist_info.WheelRefused`): not a ZIP
            archive, a member cannot be read (damaged, encrypted,
            unsupported, badly named), two members have one name or one
            holds a NUL, or a member of its own ``.dist-info`` has a
            non-conforming name, or it is signed and not *allow_signed_wheel*.
            The wheel is left as it was.
        pitloom.messages.CodedValueError: *wheel_path* cannot be looked at
            (``file-unreadable``: a directory on its way refuses search).
        pitloom.messages.CodedOSError: The system refused the write of the
            new wheel (no write permission on its directory, a full disk):
            ``file-unwritable``, the wheel named by its file name; or a read
            of a member (an I/O error): ``file-unreadable``. The wheel is
            left as it was.
        OSError: An environment problem opening the file itself (its own
            permissions, a transient I/O error) -- kept as its own
            exception type, not folded into ``ValueError``.
    """
    configure_logging()
    require_wheel_file(wheel_path)
    wheel_obj = Path(wheel_path).resolve()

    sbom_bytes = (
        sbom_content.encode("utf-8") if isinstance(sbom_content, str) else sbom_content
    )
    if not sbom_bytes.strip():
        raise invalid_value(Parameter("sbom_content"), "sbom-content", got=sbom_content)

    orig_mode = wheel_obj.stat().st_mode if wheel_obj.exists() else None

    # Every use of the file name (which ``.dist-info`` is the wheel's own, what
    # a refusal names) is of the name as given; the resolved path, which a
    # symlink points elsewhere, is for the directory and the write only.
    named = Path(wheel_path).absolute()
    with open_wheel_zip(wheel_obj, name=named) as original_zf:
        members = wheel_members(original_zf, named.name)
        dist_info = _find_dist_info_prefix(original_zf, named, members=members)
        _refuse_unembeddable(named.name, dist_info, members, allow_signed_wheel)
        plan = _plan_embed(
            original_zf,
            dist_info,
            members,
            sbom_filename,
            sbom_bytes,
            identity,
            archive=named.name,
        )
        with _coded_write(named.name):
            temp_path = _rewrite_wheel_archive(
                wheel_obj,
                original_zf,
                plan.sbom_arcname,
                sbom_bytes,
                plan.record_arcname,
                plan.new_record_bytes,
                plan.timestamp,
                plan.stale_arcnames,
                name=named.name,
            )

    try:
        with _coded_write(named.name):
            os.replace(temp_path, wheel_obj)
        if orig_mode is not None:
            try:
                os.chmod(wheel_obj, orig_mode)
            except OSError as exc:
                emit(
                    log,
                    FILE_UNWRITABLE_MODE,
                    logging.WARNING,
                    file=named.name,
                    failure=exc,
                )
    finally:
        if temp_path.exists():
            temp_path.unlink()

    return (
        named,  # as given: later steps judge its name
        plan.sbom_arcname,
        tuple(sorted(plan.stale_arcnames)),
        plan.timestamp_floored,
    )

pitloom.embed.ConfigOverrides dataclass

ConfigOverrides(
    provenance: ProvenanceConfig | None = None,
    enrich: bool | None = None,
    extract_file_header: bool | None = None,
    scan_model_usage: bool | None = None,
    content_type: bool | None = None,
    content_type_method: str | None = None,
    offline: bool | None = None,
    pretty: bool | None = None,
    describe_relationship: bool | None = None,
    update_id_registry: bool | None = None,
    max_source_metadata_bytes: int | None = None,
    max_model_extract_bytes: int | None = None,
    max_download_bytes: int | None = None,
    trust_model_files: bool | None = None,
    credentials: CredentialPolicy | None = None,
    build_options: BuildOptions = BuildOptions(),
)

Per-run overrides layered onto a project's [tool.pitloom] config.

Every field defaults to None, meaning "not given, defer to the config"; any other value wins, including one equal to the built-in default. Each maps to the PitloomConfig field of the same name, except enrich -> enrich_local and content_type -> content_type_enabled.

Attributes:

Name Type Description
provenance ProvenanceConfig | None

Replaces the config's whole provenance settings, not field by field: a field left at its default resets the config's value.

max_source_metadata_bytes int | None

Overrides that one provenance field and leaves the others as the config (or provenance) set them. Applied after provenance, so it wins over that object's own value. Checked by :func:~pitloom.core.provenance.require_max_source_metadata_bytes: 0 or at least 8, else ValueError.

max_model_extract_bytes int | None

--max-model-extract-bytes: the per-model ceiling of a wheel's AI model scan (the wheel's budget is four times it). Only a standalone wheel embed reads it; any other embed warns. Checked by :func:require_model_extract_override even there: at least 1, else ValueError.

max_download_bytes int | None

--max-download-bytes: the most bytes a PyPI URL target or each file of a Hugging Face repository downloads, or a Git URL target's checkout takes on disk. Only those targets read it (:func:resolve_fetch_policy); any other warns. Checked by :func:require_download_override: at least 1, else ValueError.

pretty bool | None

The embed path (embed_wheel_sbom(overrides=...)) always writes JCS-canonical JSON and warns that a given value has no effect, as it does for describe_relationship and update_id_registry (see :data:pitloom.core.inert_options.INERT).

trust_model_files bool | None

--trust-model-files: read a wheel's AI model files with every format reader, including those gated in a wheel. Like build_options, no [tool.pitloom] cascade (a config must not opt in) and :func:apply_overrides never touches it; only a standalone wheel embed reads it, and any other embed warns.

credentials CredentialPolicy | None

--accept-url-credential and --refuse-url-credentials. Unlike every other field it adds to the config rather than replacing it: :func:apply_overrides unites its fingerprints with the config's accept-url-credentials, and its refuse sets url_credentials to "refuse" (a policy without it leaves the config's mode), so a flag never drops a fingerprint the project accepts nor turns its refusal off.

build_options BuildOptions

--allow-build and its companion flags (see :class:~pitloom.core.build_options.BuildOptions). No [tool.pitloom] cascade, and read by embed-wheel alone: :func:apply_overrides never touches it, and generate_project_sbom() takes its own build_options parameter. It reaches the project-directory rescan of _build_sbom_from_project_and_wheel(), which only layers content-type and file-header extras onto the wheel's own file list, so enabling it on a project without a static discovery module runs a real PEP 517 build for those extras alone.

pitloom.embed.EmbedFileCache

EmbedFileCache()

One file discovery, one build-flag settle and one cleanup for a batch of embeds from the same project directory -- e.g. several wheels in one loom embed-wheel run, or a library loop passing file_cache= to :func:~pitloom.embed.embed_wheel_sbom.

Use it as a context manager around the whole batch. Inside the block, :meth:resolve runs discovery (and any --allow-build build) on its first call only, and :meth:settle warns about each ineffective build flag once (:meth:once does the same for any other per-batch warning, e.g. an option the embed cannot use) -- all hold a lock, so threads sharing one batch still get one discovery and one warning each. Leaving the block runs the discovery's cleanup once, after every wheel is done -- never per wheel, as an earlier wheel's cleanup would delete files a later one still reads. The block holds a :class:~pitloom.core.build_signals.TerminationGuard, so a signal during the batch still removes the build's temp directory -- but only for a discovery the block's own thread ran. Guard ownership is thread-local, so one a worker thread ran registers with that thread's own guard. It is removed when the block exits normally, and leaks if a signal ends the process first, or if the block's own exit is interrupted once that discovery is already cached.

Every call in a batch must use the same project directory, file-scan settings and build options: :meth:resolve raises :class:ValueError otherwise. Using it outside the block, or entering it twice, raises :class:RuntimeError. After the block it can be entered again and resolves afresh.

Source code in pitloom/_embed_build_sbom.py
 96
 97
 98
 99
100
101
102
103
104
105
def __init__(self) -> None:
    self._resolved: tuple[list[ProjectFile], Callable[[], None]] | None = None
    # What the cached file list was resolved from; see resolve().
    self._resolved_from: tuple[object, ...] | None = None
    # Batch memo, key -> result; see once() and settle().
    self._settled: dict[Hashable, object] = {}
    # The block's guard; None outside the block.
    self._guard: TerminationGuard | None = None
    # Threads sharing one batch get one discovery and one cleanup.
    self._lock = threading.Lock()

first_use

first_use(key: Hashable) -> bool

Whether this is the first call with key in this block, so a once-per-batch message is emitted by exactly one caller. Shares :meth:once's key space: use a key no :meth:once caller uses.

Raises :class:RuntimeError outside a with block.

Source code in pitloom/_embed_build_sbom.py
293
294
295
296
297
298
299
300
301
302
def first_use(self, key: Hashable) -> bool:
    """Whether this is the first call with *key* in this block, so a
    once-per-batch message is emitted by exactly one caller. Shares
    :meth:`once`'s key space: use a key no :meth:`once` caller uses.

    Raises :class:`RuntimeError` outside a ``with`` block.
    """
    ran: list[bool] = []
    self.once(key, lambda: ran.append(True), "first_use")
    return bool(ran)

identity_info_due

identity_info_due() -> bool

Whether the unknown-identity INFO: is still due in this block: one per batch.

Raises :class:RuntimeError outside a with block.

Source code in pitloom/_embed_build_sbom.py
312
313
314
315
316
317
318
def identity_info_due(self) -> bool:
    """Whether the unknown-identity ``INFO:`` is still due in this
    block: one per batch.

    Raises :class:`RuntimeError` outside a ``with`` block.
    """
    return self.first_use(_IDENTITY_UNKNOWN)

once

once(
    key: Hashable,
    compute: Callable[[], _T],
    method: str = "once",
) -> _T

compute's result, computed on the first call with key in this block and reused after -- so a warning compute logs is logged once for the batch. The caller keys on everything the result depends on.

Raises :class:RuntimeError outside a with block.

Source code in pitloom/_embed_build_sbom.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def once(
    self, key: Hashable, compute: Callable[[], _T], method: str = "once"
) -> _T:
    """*compute*'s result, computed on the first call with *key* in
    this block and reused after -- so a warning *compute* logs is
    logged once for the batch. The caller keys on everything the result
    depends on.

    Raises :class:`RuntimeError` outside a ``with`` block.
    """
    with self._lock:
        self._require_block(method)
        # This block's memo, taken once: __enter__ gives the next
        # block a new one, so a late call here cannot warn into it.
        settled = self._settled
        if key not in settled:
            # Under the lock: a warning is part of computing, so two
            # threads must not both emit it.
            settled[key] = compute()
        return cast(_T, settled[key])

registry_warning_due

registry_warning_due() -> bool

Whether the in-tree registry WARNING: is still due in this block: one per batch, discovery's included.

Raises :class:RuntimeError outside a with block.

Source code in pitloom/_embed_build_sbom.py
304
305
306
307
308
309
310
def registry_warning_due(self) -> bool:
    """Whether the in-tree registry ``WARNING:`` is still due in this
    block: one per batch, discovery's included.

    Raises :class:`RuntimeError` outside a ``with`` block.
    """
    return self.first_use(_REGISTRY_LEFT_OUT)

resolve

resolve(
    project_dir: Path,
    pitloom_config: PitloomConfig,
    build_options: BuildOptions,
    exclude_path: Path | None = None,
) -> list[ProjectFile]

Return the cached file list (without exclude_path, the declared registry), running discovery on first use.

Raises :class:RuntimeError outside a with block, and :class:ValueError when a later call in the block asks for a different project directory, file-scan settings, build options or excluded file than the first -- the cached list would not match.

Source code in pitloom/_embed_build_sbom.py
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
def resolve(
    self,
    project_dir: Path,
    pitloom_config: PitloomConfig,
    build_options: BuildOptions,
    exclude_path: Path | None = None,
) -> list[ProjectFile]:
    """Return the cached file list (without *exclude_path*, the
    declared registry), running discovery on first use.

    Raises :class:`RuntimeError` outside a ``with`` block, and
    :class:`ValueError` when a later call in the block asks for a
    different project directory, file-scan settings, build options
    or excluded file than the first -- the cached list would not match.
    """
    content_type = pitloom_config.content_type
    resolved_from = (
        project_dir,
        pitloom_config.extract_file_header,
        content_type.enabled,
        content_type.method,
        content_type.overrides,
        build_options,
        exclude_path,
    )
    with self._lock:
        # Inside the lock: the block may have closed while another
        # thread's discovery held it.
        self._require_block("resolve")
        if self._resolved is None:
            block = self._guard
            _, project_files, cleanup = get_wheel_files(
                project_dir,
                scan_file_headers=pitloom_config.extract_file_header,
                detect_content_type=content_type.enabled,
                content_type_method=content_type.method,
                content_type_overrides=content_type.overrides,
                skip_merkle_root=True,
                build_options=build_options,
                exclude_path=exclude_path,
                on_left_out=functools.partial(_left_out, self._settled),
            )
            if self._guard is not block:
                # The block this discovery was started for closed
                # while it held the lock (an interrupt in __exit__),
                # and another may already have taken its place --
                # each block gets its own guard, so identity, not
                # mere presence, is what says "still the same one".
                # Nothing else would run this cleanup, and no block
                # may be handed a result it never asked for.
                cleanup()
                self._require_block("resolve")
                raise RuntimeError(
                    "EmbedFileCache.resolve() outlived its with-block: "
                    "the batch it was called for ended while it ran"
                )
            self._resolved = (project_files, cleanup)
            self._resolved_from = resolved_from
        elif resolved_from != self._resolved_from:
            raise ValueError(
                "EmbedFileCache: every call in one batch must use the same "
                "project directory, file-scan settings, build options and registry"
            )
        return self._resolved[0]

settle

settle(
    build_options: BuildOptions,
    subject: object,
    reason: str | None = None,
) -> BuildOptions

Settle build_options -- with :meth:~pitloom.core.build_options.BuildOptions.settle, or with :meth:~pitloom.core.build_options.BuildOptions.settle_not_applicable and reason when given -- once per block for each distinct (build_options, reason) pair, reusing that result on later calls, so each ineffective flag warns once for the batch. A call with other options or another reason settles (and warns) itself.

Raises :class:RuntimeError outside a with block.

Source code in pitloom/_embed_build_sbom.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def settle(
    self, build_options: BuildOptions, subject: object, reason: str | None = None
) -> BuildOptions:
    """Settle *build_options* -- with
    :meth:`~pitloom.core.build_options.BuildOptions.settle`, or with
    :meth:`~pitloom.core.build_options.BuildOptions.settle_not_applicable`
    and *reason* when given -- once per block for each distinct
    (*build_options*, *reason*) pair, reusing that result on later
    calls, so each ineffective flag warns once for the batch. A call
    with other options or another reason settles (and warns) itself.

    Raises :class:`RuntimeError` outside a ``with`` block.
    """
    return self.once(
        ("build_options", build_options, reason),
        lambda: (
            build_options.settle(subject)
            if reason is None
            else build_options.settle_not_applicable(subject, reason)
        ),
        "settle",
    )

pitloom.extract.wheel.wheel_identity

wheel_identity(
    metadata: ProjectMetadata,
) -> tuple[str | None, str | None]

The (name, version) the wheel's METADATA declared, from what :func:read_wheel returned: None for each it did not.

metadata.name is the sentinel "unknown" where the header is absent, so only provenance says whether either was read.

Source code in pitloom/extract/wheel.py
154
155
156
157
158
159
160
161
162
163
164
def wheel_identity(metadata: ProjectMetadata) -> tuple[str | None, str | None]:
    """The (name, version) the wheel's ``METADATA`` declared, from what
    :func:`read_wheel` returned: ``None`` for each it did not.

    ``metadata.name`` is the sentinel ``"unknown"`` where the header is
    absent, so only ``provenance`` says whether either was read.
    """
    return (
        metadata.name if "name" in metadata.provenance else None,
        metadata.version if "version" in metadata.provenance else None,
    )

Build options

pitloom.core.build_options.BuildOptions dataclass

BuildOptions(
    allow: bool = False,
    no_isolation: bool = False,
    timeout: int | None = None,
)

Explicit build-and-read options for one call.

Attributes:

Name Type Description
allow bool

Opt into a real PEP 517 build of the scanned project to discover its wheel file list (--allow-build). SECURITY: executes third-party build-time code. Deliberately has no [tool.pitloom] equivalent: the scanned project's own config must never opt itself in, so a caller passes it explicitly on every call.

no_isolation bool

Use the current environment's build backend instead of an isolated build environment (--no-build-isolation).

timeout int | None

Whole seconds the build may run before it is terminated (--build-timeout); None uses :data:~pitloom.core._models_wheel_types.DEFAULT_BUILD_TIMEOUT_SECONDS.

no_isolation and timeout have no effect without allow. The default instance means "no build flag given".

Raises:

Type Description
TypeError

allow/no_isolation is not a bool (a truthy string such as "false" must never enable code execution), or timeout is not an int.

ValueError

timeout is outside 1..MAX_BUILD_TIMEOUT_SECONDS.

given property

given: tuple[str, ...]

CLI spellings of the explicitly given flags, in CLI order.

settings

settings() -> BuildSettings | None

The resolved settings for a real build, or None when allow is off.

Source code in pitloom/core/build_options.py
136
137
138
139
140
141
142
143
144
def settings(self) -> BuildSettings | None:
    """The resolved settings for a real build, or ``None`` when
    ``allow`` is off."""
    if not self.allow:
        return None
    return BuildSettings(
        isolated=not self.no_isolation,
        timeout=resolve_build_timeout(self.timeout),
    )

settle

settle(subject: object) -> BuildOptions

Resolve a no_isolation/timeout given without allow: log one WARNING: per such flag and return BuildOptions() (defaults) so nothing is left to warn about later. Returns self unchanged when allow is set (nothing stray to resolve) or nothing was given (already settled).

Call this as early as a caller can tell the target will reach file discovery -- before resolving project metadata or a lock file -- so the warning precedes those, not the other way round. Idempotent: settling an already-settled value warns nothing and returns it unchanged, so calling this again downstream (e.g. inside get_wheel_files()) on a value a caller already settled is always a silent no-op.

Source code in pitloom/core/build_options.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def settle(self, subject: object) -> BuildOptions:
    """Resolve a ``no_isolation``/``timeout`` given without ``allow``:
    log one ``WARNING:`` per such flag and return
    ``BuildOptions()`` (defaults) so nothing is left to warn about
    later. Returns ``self`` unchanged when ``allow`` is set (nothing
    stray to resolve) or nothing was given (already settled).

    Call this as early as a caller can tell the target will reach
    file discovery -- before resolving project metadata or a lock
    file -- so the warning precedes those, not the other way round.
    Idempotent: settling an already-settled value warns nothing and
    returns it unchanged, so calling this again downstream (e.g.
    inside ``get_wheel_files()``) on a value a caller already
    settled is always a silent no-op.
    """
    if self.allow or not self.given:
        return self
    warn_no_effect(subject, self.given, f"without {_ALLOW_FLAG}", build=True)
    return BuildOptions()

settle_not_applicable

settle_not_applicable(
    subject: object, reason: str
) -> BuildOptions

Resolve a target a caller already knows will never reach file discovery (e.g. an sdist archive, a non-project target, an externally-supplied --sbom): log one WARNING: per given flag and return BuildOptions() (defaults), so a downstream call on the same value -- one this caller forwards, or one a later layer resolves independently -- has nothing left to warn about.

Call this as early as the caller can tell the target's fate, before reading any project metadata or lock file, so the warning precedes those rather than following them. reason follows "has no effect" (no trailing punctuation), e.g. :data:SDIST_TARGET_REASON. Idempotent the same way :meth:settle is: the returned (defaulted) value has no given flag to warn about.

Source code in pitloom/core/build_options.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def settle_not_applicable(self, subject: object, reason: str) -> BuildOptions:
    """Resolve a target a caller already knows will never reach file
    discovery (e.g. an sdist archive, a non-project target, an
    externally-supplied ``--sbom``): log one ``WARNING:`` per given
    flag and return ``BuildOptions()``
    (defaults), so a downstream call on the same value -- one this
    caller forwards, or one a later layer resolves independently --
    has nothing left to warn about.

    Call this as early as the caller can tell the target's fate,
    before reading any project metadata or lock file, so the
    warning precedes those rather than following them. *reason*
    follows "has no effect" (no trailing punctuation), e.g.
    :data:`SDIST_TARGET_REASON`. Idempotent the same way :meth:`settle`
    is: the returned (defaulted) value has no given flag to warn about.
    """
    warn_no_effect(subject, self.given, reason, build=True)
    return BuildOptions()

settle_target

settle_target(target: Path) -> BuildOptions

Settle for a project-or-sdist target path, following :func:target_settle_plan: an sdist archive gets :meth:settle_not_applicable with :data:SDIST_TARGET_REASON, a directory :meth:settle, anything else nothing.

Source code in pitloom/core/build_options.py
166
167
168
169
170
171
172
173
174
175
176
def settle_target(self, target: Path) -> BuildOptions:
    """Settle for a project-or-sdist *target* path, following
    :func:`target_settle_plan`: an sdist archive gets
    :meth:`settle_not_applicable` with :data:`SDIST_TARGET_REASON`, a
    directory :meth:`settle`, anything else nothing."""
    settle, reason = target_settle_plan(target)
    if not settle:
        return self
    if reason is None:
        return self.settle(target)
    return self.settle_not_applicable(target, reason)

Fragment merging

pitloom.assemble.generate_merged_sbom

generate_merged_sbom(
    fragments_dir: Path | str,
    *,
    output_path: Path | str | None = None,
    pretty: bool = True,
    credentials: CredentialPolicy | None = None,
    on_merged: Callable[[int], None] | None = None,
) -> str

Merge every *.json SPDX 3 fragment in fragments_dir into one SBOM, as loom merge does, and return it as JSON-LD.

The output is one SpdxDocument rooted at what the fragments' own envelopes rooted; equal elements unify as in a project build with fragments. The same fragments give the same bytes, whatever the directory or the order the files were written in.

A fragment field holding a credential that credentials (:class:~pitloom.core.credential_policy.CredentialPolicy) does not accept is warned of, or, in its refuse mode, refused; fragments have no [tool.pitloom] to add to it.

A fragment that cannot be merged is left out with one WARNING: naming it by fragments_dir as given joined with its file name; when none can be, nothing is written. on_merged, when given, is called with the number of fragments merged, once the SBOM is written (loom merge says it).

Raises:

Type Description
FileNotFoundError

fragments_dir does not exist, or is not a directory (input-not-found, carrying the code).

ValueError

it has no *.json file (input-not-found).

FragmentMergeError

no fragment of it could be merged (fragment-missing; each one's WARNING: says why).

FragmentMergeError

the merge left a dangling reference, a root included, or a licence relationship end of the wrong type (a pitloom.assemble.spdx3.fragments. FragmentLicenseRangeError, code license-relationship-invalid).

Source code in pitloom/assemble/_generators_merge.py
 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
def generate_merged_sbom(
    fragments_dir: Path | str,
    *,
    output_path: Path | str | None = None,
    pretty: bool = True,
    credentials: CredentialPolicy | None = None,
    on_merged: Callable[[int], None] | None = None,
) -> str:
    """Merge every ``*.json`` SPDX 3 fragment in *fragments_dir* into one
    SBOM, as ``loom merge`` does, and return it as JSON-LD.

    The output is one ``SpdxDocument`` rooted at what the fragments' own
    envelopes rooted; equal elements unify as in a project build with
    fragments. The same fragments give the same bytes, whatever the
    directory or the order the files were written in.

    A fragment field holding a credential that *credentials*
    (:class:`~pitloom.core.credential_policy.CredentialPolicy`) does not
    accept is warned of, or, in its ``refuse`` mode, refused; fragments
    have no ``[tool.pitloom]`` to add to it.

    A fragment that cannot be merged is left out with one ``WARNING:``
    naming it by *fragments_dir* as given joined with its file name; when
    none can be, nothing is written. *on_merged*, when given, is called with
    the number of fragments merged, once the SBOM is written (``loom
    merge`` says it).

    Raises:
        FileNotFoundError: *fragments_dir* does not exist, or is not a
            directory (``input-not-found``, carrying the code).
        ValueError: it has no ``*.json`` file (``input-not-found``).
        pitloom.assemble.FragmentMergeError: no fragment of it could be
            merged (``fragment-missing``; each one's ``WARNING:`` says why).
        pitloom.assemble.FragmentMergeError: the merge left a dangling
            reference, a root included, or a licence relationship end of the
            wrong type (a ``pitloom.assemble.spdx3.fragments.
            FragmentLicenseRangeError``, code ``license-relationship-invalid``).
    """
    configure_logging()
    # A Path as given (a TypedPath keeps the user's spelling for the lines).
    fragments_dir = (
        fragments_dir if isinstance(fragments_dir, Path) else Path(fragments_dir)
    )
    if not is_input_dir(fragments_dir):
        raise input_not_found("fragments directory", fragments_dir)
    files = fragment_files(fragments_dir)
    if not files:
        raise CodedValueError(
            INPUT_NOT_FOUND, line=NO_FRAGMENT_FILE_LINE, path=fragments_dir
        )
    exporter = new_merge_document(fragments_dir, files)
    merged = merge_fragments(
        fragments_dir,
        [FragmentConfig(path=f) for f in files],
        exporter,
        adopt_fragment_roots=True,
    )
    if not merged:
        raise FragmentMergeError(
            FRAGMENT_MISSING, line=NONE_MERGED_LINE, path=fragments_dir
        )
    finish_merge_document(exporter)
    sbom_json = exporter.to_json(
        pretty=pretty, credentials=credentials or CredentialPolicy()
    )
    write_sbom_output(sbom_json, output_path)
    if on_merged is not None:
        on_merged(merged)
    return sbom_json

pitloom.assemble.merge_fragments

merge_fragments(
    project_dir: Path,
    fragments: list[FragmentConfig],
    exporter: Spdx3JsonExporter,
    *,
    adopt_fragment_roots: bool = False,
) -> int

Load SPDX 3 JSON-LD fragment files and merge them into the exporter; return how many were merged (a missing or unreadable one is not).

The main document's profileConformance gains what the merged fragments' envelopes declared. With adopt_fragment_roots (loom merge), its rootElement also gains what those envelopes rooted, after unification; a project keeps its own roots. Every root goes through the dangling-reference check below.

A fragment whose SpdxDocument id is the exporter's own document (an earlier SBOM of the same project) is skipped with a WARNING:, as a missing one is. An ai_AIPackage of the exporter's takes the name the fragments unifying with it agree on, with one INFO: (see :mod:pitloom.assemble.spdx3._fragments_model_names). A not_measured provenance entry of a field the merged element now holds goes, with one INFO: each (see :mod:pitloom.assemble.spdx3._fragments_evidence).

A fragment left out is said in one WARNING: naming it as configured (with adopt_fragment_roots, the directory project_dir as the caller spelt it joined with its name).

Raises :class:FragmentMergeError (fragment-missing, naming the configured paths) if any required=True fragment (see :class:~pitloom.core.config.FragmentConfig) is missing, couldn't be read or is the document itself, or if the merge leaves the graph referentially broken (reference-not-found, see :func:_raise_on_dangling_references) or has a licence relationship end of the wrong type (see :func:_raise_on_license_range_violations) -- the latter two are skipped when fragments is empty or none of it could be ingested, since there is then nothing new whose references could be dangling.

Source code in pitloom/assemble/spdx3/fragments.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
def merge_fragments(
    project_dir: Path,
    fragments: list[FragmentConfig],
    exporter: Spdx3JsonExporter,
    *,
    adopt_fragment_roots: bool = False,
) -> int:
    """Load SPDX 3 JSON-LD fragment files and merge them into the exporter;
    return how many were merged (a missing or unreadable one is not).

    The main document's ``profileConformance`` gains what the merged
    fragments' envelopes declared. With *adopt_fragment_roots*
    (``loom merge``), its ``rootElement`` also gains what those envelopes
    rooted, after unification; a project keeps its own roots. Every root
    goes through the dangling-reference check below.

    A fragment whose ``SpdxDocument`` id is the exporter's own document
    (an earlier SBOM of the same project) is skipped with a ``WARNING:``,
    as a missing one is. An ``ai_AIPackage`` of the exporter's takes the
    name the fragments unifying with it agree on, with one ``INFO:`` (see
    :mod:`pitloom.assemble.spdx3._fragments_model_names`). A
    ``not_measured`` provenance entry of a field the merged element now
    holds goes, with one ``INFO:`` each (see
    :mod:`pitloom.assemble.spdx3._fragments_evidence`).

    A fragment left out is said in one ``WARNING:`` naming it as
    configured (with *adopt_fragment_roots*, the directory *project_dir* as
    the caller spelt it joined with its name).

    Raises :class:`FragmentMergeError` (``fragment-missing``, naming the
    configured paths) if any ``required=True`` fragment
    (see :class:`~pitloom.core.config.FragmentConfig`) is missing, couldn't
    be read or is the document itself, or if the merge leaves the graph
    referentially broken (``reference-not-found``, see
    :func:`_raise_on_dangling_references`) or has a
    licence relationship end of the wrong type (see
    :func:`_raise_on_license_range_violations`) -- the
    latter two are skipped when *fragments* is empty or none of it could be
    ingested, since there is then nothing new whose references could be
    dangling.
    """
    configure_logging()
    main_doc = _find_main_document(exporter.object_set)
    main_doc_id = str(main_doc.spdxId) if main_doc and main_doc.spdxId else None
    index = _MergeIndex(exporter, main_doc_id)
    events: _UnificationEvents = {}
    fragment_imports: list[spdx3.ExternalMap] = []
    unmet_required: list[str] = []
    roots: list[str] = []
    profiles: set[str] = set()

    loaded_fragments: list[tuple[FragmentConfig, spdx3.SHACLObjectSet, str | None]] = []
    for frag in fragments:
        loaded = _load_fragment(
            _fragment_file(project_dir, frag),
            _shown_fragment(project_dir, frag, of_directory=adopt_fragment_roots),
            frag.required,
            main_doc_id,
        )
        if loaded is None:
            if frag.required:
                unmet_required.append(frag.path)
            continue
        # Noted for every fragment before the first merge: which id is
        # registry-pinned must not depend on the order.
        index.note_source(str(_fragment_file(project_dir, frag)), loaded[0].objects)
        loaded_fragments.append((frag, *loaded))

    for frag, fragment_set, frag_doc_id in loaded_fragments:
        if frag_doc_id and frag_doc_id not in {
            m.externalSpdxId for m in fragment_imports
        }:
            fragment_imports.append(
                spdx3.ExternalMap(externalSpdxId=frag_doc_id, locationHint=frag.path)
            )
        profiles |= _declared_profiles(fragment_set)
        roots.extend(_merge_fragment_set(fragment_set, index, frag.path, events))

    index.finish()
    _dedupe_relationships(exporter)

    if main_doc is not None:
        _update_profile_conformance(main_doc, exporter, profiles)
        _add_fragment_imports(main_doc, fragment_imports)
        _emit_unification_annotations(events, main_doc, exporter)
        _add_model_sbom(main_doc, exporter)
        if adopt_fragment_roots:
            main_doc.rootElement = sorted({*roots, *(main_doc.rootElement or [])})

    # Checked even when no fragment loaded (a missing required fragment may
    # be the only one), and before the dangling-references raise below: a
    # missing required fragment is usually the root cause of any dangling
    # references (other fragments pointing at elements it was to supply),
    # so report it, not the symptom.
    if unmet_required:
        raise FragmentMergeError(
            FRAGMENT_MISSING,
            line=REQUIRED_MISSING_LINE,
            number=len(unmet_required),
            files=missing_files_text(unmet_required),
        )

    if loaded_fragments:
        _raise_on_dangling_references(exporter)
        _raise_on_license_range_violations(exporter)
    return len(loaded_fragments)

pitloom.assemble.project_document_id

project_document_id(project_dir: Path) -> str

The SpdxDocument id a loom project build of project_dir gives (without --allow-build), resolved as :func:_doc_identity_of resolves it; loom fragment list compares fragments with it.

Source code in pitloom/assemble/_model_generator.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def project_document_id(project_dir: Path) -> str:
    """The ``SpdxDocument`` id a ``loom project`` build of *project_dir*
    gives (without ``--allow-build``), resolved as :func:`_doc_identity_of`
    resolves it; ``loom fragment list`` compares fragments with it."""
    configure_logging()
    metadata, config, _path = resolve_project_with_lockfile(project_dir, None)
    registry = resolve_registry(
        None,
        config.id_registry,
        registry_base_dir(project_dir),
        refuse_credentials=config.credential_policy.refuse,
    )
    doc_name, doc_uuid = _doc_identity_of(project_dir, metadata, registry)
    return generate_spdx_id("SpdxDocument", doc_name=doc_name, doc_uuid=doc_uuid)

pitloom.assemble.FragmentMergeError

FragmentMergeError(
    message: Message,
    /,
    *,
    line: Line | None = None,
    **values: object,
)

A merge of fragments that must not succeed, a :class:ValueError carrying its code: a required fragment not merged, or none of loom merge's (fragment-missing), or a merged graph left referentially broken (reference-not-found: see :func:_raise_on_dangling_references).

Source code in pitloom/messages/_emit.py
144
145
146
147
148
149
def __init__(
    self, message: Message, /, *, line: Line | None = None, **values: object
) -> None:
    super().__init__(message.line_for("ERROR", values, line).render(values))
    #: The catalogued code (:data:`~pitloom.logging_config.CODE_ATTR`).
    self.pitloom_code: str = message.code

Tracking decorator

loom.run is the Run class below (run = Run) -- use it as a decorator or a context manager, as shown on the Python API page.

pitloom.loom.Run

Run(
    output_file: str | Path,
    pretty: bool = False,
    creation_metadata: CreationMetadata | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    *,
    pitloom_config: PitloomConfig
    | str
    | Path
    | None = None,
    max_dataset_hash_bytes: int | None = None,
    credentials: CredentialPolicy | None = None,
)

Context manager and decorator for capturing SPDX fragments.

Each Run is a single recording session that weaves metadata about a model and its datasets into an SBOM fragment.

Can be used as a context manager::

with loom.run("fragments/train.spdx3.json") as run:
    run.set_model("my-model", path="model.bin")
    run.add_dataset("train.txt")
    run.add_validation_dataset("valid.txt")
    # ... training code ...
    run.set_model_hyperparameters({"lr": "0.1", "epoch": "5"})

Or as a function decorator::

@loom.run("fragments/preprocess.spdx3.json")
def preprocess():
    loom.add_input_dataset("rawdata/neg.txt")
    loom.add_output_dataset("data/train.txt",
                            data_preprocessing=["tokenization"])

The fragment's SPDX CreationInfo is configurable on par with the CLI and Hatchling build hook: pass a CreationMetadata to name a creator (a person, organisation, or automated agent), or override the tool, timestamp, and comment. With none given, the fragment records the SoftwareAgent "Pitloom" (createdBy) and Tool "Pitloom" (createdUsing) of an unattended run::

loom.run(
    "fragments/train.spdx3.json",
    creation_metadata=CreationMetadata(
        creators=[Creator(name="Alice", type="person")]
    ),
)

Parameters:

Name Type Description Default
output_file str | Path

Path to write the SBOM fragment to.

required
pretty bool

Indent the JSON output with 2 spaces when True.

False
creation_metadata CreationMetadata | None

Creator, tool, timestamp, and comment overrides for the fragment's CreationInfo. See CreationMetadata for all fields. When None (default), the comment defaults to an auto-generated note identifying the loom SDK and its version, and the creator defaults to the SoftwareAgent "Pitloom".

None
id_registry str | Path | IdRegistry | None

A pitloom.id_registry.IdRegistry, a path to a registry JSON file (relative to the current working directory), or None (default): the config's id-registry, else no registry -- never searched for. Datasets, their files, the model, and the generating script all get the registered spdxId when one exists for them, so independently generated fragments can be unified at merge time without name-based matching. Loom writes one kind of entry: a model declared with path= whose file the registry does not know, saved when the run ends, after the fragment.

None
pitloom_config PitloomConfig | str | Path | None

A pitloom.core.config.PitloomConfig, or a path to a config file read like --config (relative to the current working directory; missing or invalid raises ValueError), or None (default): the built-in defaults. No [tool.pitloom] is ever read implicitly. Loom reads only max-dataset-hash-bytes (when max_dataset_hash_bytes is not given), id-registry (when id_registry is not given; a relative path in a config file is relative to that file's directory) and update-id-registry (false: no model is registered), accept-url-credentials and url-credentials. Every other key does not apply to loom.

None
max_dataset_hash_bytes int | None

The most bytes read to hash one dataset (a file, or all files of a directory together); a dataset over it gets no hash and a WARNING:. An integer of at least 1 (0 is an error, not "unlimited"; ValueError at __enter__). Beats the config's max-dataset-hash-bytes; default 4 GiB.

None
credentials CredentialPolicy | None

A pitloom.core.credential_policy.CredentialPolicy naming URL field values that hold a credential and may stay in the fragment, added to the config's accept-url-credentials; its refuse turns the config's url-credentials mode to refuse. A field with a credential that neither accepts is warned of when the run ends (the warn mode, the default), or refused and no fragment written (the refuse mode).

None
Source code in pitloom/loom.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def __init__(
    self,
    output_file: str | Path,
    pretty: bool = False,
    creation_metadata: CreationMetadata | None = None,
    id_registry: str | Path | IdRegistry | None = None,
    *,
    pitloom_config: PitloomConfig | str | Path | None = None,
    max_dataset_hash_bytes: int | None = None,
    credentials: CredentialPolicy | None = None,
):
    self.output_file = str(output_file)
    self.pretty = pretty
    self.creation_metadata = creation_metadata or CreationMetadata()
    self.id_registry = id_registry
    self.pitloom_config = pitloom_config
    self.max_dataset_hash_bytes = max_dataset_hash_bytes
    self.credentials = credentials
    #: The run active at the latest ``__enter__``.
    self.previous_run: _ActiveRun | None = None
    #: One per open ``__enter__``: a recursive ``@loom.run`` function
    #: re-enters this object before the outer call exits.
    self._outer_runs: list[_ActiveRun | None] = []

pitloom.loom.set_model

set_model(
    name: str,
    model_type: str | None = None,
    hyperparameters: dict[str, str] | None = None,
    generated: bool | None = None,
    *,
    path: str | PathLike[str] | None = None,
) -> None

Declare the AI model being trained in the current run.

Resolved when the run ends without an exception: path, the model's file (relative to the current directory at this call), is then hashed; with a registry, the hash gates the lookup of the file's path key (of name outside the registry's root), and a model the registry does not know is registered. Without a usable path, name is looked up ungated. A file rewritten in between is a new model with a new id.

Source code in pitloom/loom.py
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
def set_model(
    name: str,
    model_type: str | None = None,
    hyperparameters: dict[str, str] | None = None,
    generated: bool | None = None,
    *,
    path: str | os.PathLike[str] | None = None,
) -> None:
    """Declare the AI model being trained in the current run.

    Resolved when the run ends without an exception: *path*, the model's
    file (relative to the current directory at this call), is then hashed;
    with a registry, the hash gates the lookup of the file's path key (of
    *name* outside the registry's root), and a model the registry does not
    know is registered. Without a usable *path*, *name* is looked up
    ungated. A file rewritten in between is a new model with a new id.
    """
    if _active_run is None:
        raise _no_active_run("set_model")
    _active_run.set_model(
        name,
        model_type=model_type,
        hyperparameters=hyperparameters,
        generated=generated,
        path=path,
    )

pitloom.loom.use_model

use_model(
    name: str,
    model_type: str | None = None,
    hyperparameters: dict[str, str] | None = None,
    *,
    path: str | PathLike[str] | None = None,
) -> None

Explicitly declare an AI model consumed by the current run (for inference); path as for :func:set_model.

Source code in pitloom/loom.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def use_model(
    name: str,
    model_type: str | None = None,
    hyperparameters: dict[str, str] | None = None,
    *,
    path: str | os.PathLike[str] | None = None,
) -> None:
    """Explicitly declare an AI model consumed by the current run (for
    inference); *path* as for :func:`set_model`."""
    if _active_run is None:
        raise _no_active_run("use_model")
    _active_run.use_model(
        name,
        model_type=model_type,
        hyperparameters=hyperparameters,
        path=path,
    )

pitloom.loom.set_model_hyperparameters

set_model_hyperparameters(
    hyperparameters: dict[str, str],
) -> None

Update the active model with hyperparameters captured after training.

Source code in pitloom/loom.py
235
236
237
238
239
def set_model_hyperparameters(hyperparameters: dict[str, str]) -> None:
    """Update the active model with hyperparameters captured after training."""
    if _active_run is None:
        raise _no_active_run("set_model_hyperparameters")
    _active_run.set_model_hyperparameters(hyperparameters)

pitloom.loom.add_dataset

add_dataset(
    name: str,
    dataset_type: str = "text",
    *,
    croissant: str | PathLike[str] | None = None,
    declared_license: str | None = None,
) -> None

Add a dataset the AI model in the current run uses.

Parameters:

Name Type Description Default
name str

The dataset: a file, a directory, or a name for one that is not local. A directory's dataset card (the YAML frontmatter of its README.md) is read for its license (with license_name/license_link for other), version and tags.

required
dataset_type str

An SPDX dataset_DatasetType name.

'text'
croissant str | PathLike[str] | None

A local Croissant JSON-LD file describing the dataset; its licence, version, description, creator and other dataset fields are written onto the package, each with its provenance. A URL raises ValueError: loom reads no network source.

None
declared_license str | None

The dataset's licence (an SPDX expression or other text) as the caller declares it. Declared on any call for the dataset, it wins over every Croissant file's, which wins over a dataset card's; of two declared, the first call's wins. The caller's NOASSERTION (any case) is written as stated; unknown, blank or a bare other is no licence, as from any source, and the next source may state one.

None

Raises:

Type Description
TypeError

declared_license is not a string.

ValueError

croissant is a URL, not a regular file, or cannot be read as Croissant.

Source code in pitloom/loom.py
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
def add_dataset(
    name: str,
    dataset_type: str = "text",
    *,
    croissant: str | os.PathLike[str] | None = None,
    declared_license: str | None = None,
) -> None:
    """Add a dataset the AI model in the current run uses.

    Args:
        name: The dataset: a file, a directory, or a name for one that is
            not local. A directory's dataset card (the YAML frontmatter of
            its ``README.md``) is read for its ``license`` (with
            ``license_name``/``license_link`` for ``other``), ``version``
            and ``tags``.
        dataset_type: An SPDX ``dataset_DatasetType`` name.
        croissant: A local Croissant JSON-LD file describing the dataset;
            its licence, version, description, creator and other dataset
            fields are written onto the package, each with its provenance.
            A URL raises ``ValueError``: loom reads no network source.
        declared_license: The dataset's licence (an SPDX expression or
            other text) as the caller declares it. Declared on any call for
            the dataset, it wins over every Croissant file's, which wins
            over a dataset card's; of two declared, the first call's wins.
            The caller's ``NOASSERTION`` (any case) is written as stated;
            ``unknown``, blank or a bare ``other`` is no licence, as from
            any source, and the next source may state one.

    Raises:
        TypeError: *declared_license* is not a string.
        ValueError: *croissant* is a URL, not a regular file, or cannot be
            read as Croissant.
    """
    if _active_run is None:
        raise _no_active_run("add_dataset")
    _active_run.add_dataset(
        name, dataset_type, croissant=croissant, declared_license=declared_license
    )

pitloom.loom.add_validation_dataset

add_validation_dataset(
    name: str,
    dataset_type: str = "text",
    *,
    croissant: str | PathLike[str] | None = None,
    declared_license: str | None = None,
) -> None

Add a validation/test dataset in the current run; arguments as for :func:add_dataset.

Source code in pitloom/loom.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def add_validation_dataset(
    name: str,
    dataset_type: str = "text",
    *,
    croissant: str | os.PathLike[str] | None = None,
    declared_license: str | None = None,
) -> None:
    """Add a validation/test dataset in the current run; arguments as for
    :func:`add_dataset`."""
    if _active_run is None:
        raise _no_active_run("add_validation_dataset")
    _active_run.add_validation_dataset(
        name, dataset_type, croissant=croissant, declared_license=declared_license
    )

pitloom.loom.add_input_dataset

add_input_dataset(
    name: str,
    dataset_type: str = "text",
    *,
    croissant: str | PathLike[str] | None = None,
    declared_license: str | None = None,
) -> None

Declare a raw/source dataset consumed by a preprocessing step; arguments as for :func:add_dataset.

Source code in pitloom/loom.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def add_input_dataset(
    name: str,
    dataset_type: str = "text",
    *,
    croissant: str | os.PathLike[str] | None = None,
    declared_license: str | None = None,
) -> None:
    """Declare a raw/source dataset consumed by a preprocessing step;
    arguments as for :func:`add_dataset`."""
    if _active_run is None:
        raise _no_active_run("add_input_dataset")
    _active_run.add_input_dataset(
        name, dataset_type, croissant=croissant, declared_license=declared_license
    )

pitloom.loom.add_output_dataset

add_output_dataset(
    name: str,
    dataset_type: str = "text",
    data_preprocessing: list[str] | None = None,
    input_datasets: list[str] | None = None,
    *,
    croissant: str | PathLike[str] | None = None,
    declared_license: str | None = None,
) -> None

Declare a derived/processed dataset produced by a preprocessing step.

data_preprocessing wins over a source's; input_datasets names the add_input_dataset() declarations it derives from (None: all); the other arguments as for :func:add_dataset.

Source code in pitloom/loom.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def add_output_dataset(
    name: str,
    dataset_type: str = "text",
    data_preprocessing: list[str] | None = None,
    input_datasets: list[str] | None = None,
    *,
    croissant: str | os.PathLike[str] | None = None,
    declared_license: str | None = None,
) -> None:
    """Declare a derived/processed dataset produced by a preprocessing step.

    *data_preprocessing* wins over a source's; *input_datasets* names the
    ``add_input_dataset()`` declarations it derives from (``None``: all);
    the other arguments as for :func:`add_dataset`."""
    if _active_run is None:
        raise _no_active_run("add_output_dataset")
    _active_run.add_output_dataset(
        name,
        dataset_type,
        data_preprocessing=data_preprocessing,
        input_datasets=input_datasets,
        croissant=croissant,
        declared_license=declared_license,
    )

Creation metadata

pitloom.core.creation.CreationMetadata dataclass

CreationMetadata(
    creators: list[Creator] = list(),
    tools: list[Tool] | None = None,
    creation_datetime: str | None = None,
    creation_comment: str | None = None,
    build_datetime: str | None = None,
)

Metadata describing who and what generated an SBOM.

Pitloom's own model for creation provenance -- distinct from, but mapping onto, SPDX 3 CreationInfo: each creator becomes an Agent in createdBy (Person, Organization, SoftwareAgent, or the generic Agent -- see Creator.type), and each tool becomes a Tool in createdUsing. When no creator is named, the assembler records the automated SoftwareAgent "Pitloom" in createdBy -- Pitloom acting on its own -- rather than inventing a Person.

Attributes:

Name Type Description
creators list[Creator]

Named creators, in order. When empty (default), no named creator is asserted and the assembler emits the SoftwareAgent "Pitloom" in createdBy instead. When multiple creators are supplied, each becomes its own Agent; the SPDX 3 suppliedBy of the main package (single-valued) is set to the first named creator that is not a "software-agent" (a program that made the SBOM did not supply the package).

tools list[Tool] | None

Creation tools, in order. None (default) means the default single Tool "Pitloom". An empty list suppresses createdUsing entirely (matches --no-creation-tool). A non-empty list emits one Tool per entry.

creation_datetime str | None

ISO 8601 string for the creation timestamp. Full ISO forms are accepted (e.g. offsets and fractional seconds). Pitloom preserves input precision internally and normalises to SPDX 3 DateTime (YYYY-MM-DDThh:mm:ssZ) only at export time. When None, the assembler falls back to SOURCE_DATE_EPOCH (reproducible-builds.org) if set, else the current UTC time -- see :func:resolve_source_date_epoch.

creation_comment str | None

Optional comment to include on the SPDX CreationInfo element. Callers (CLI, Hatchling build hook, loom SDK) set this to a description of the invocation channel, e.g. "Generated via Pitloom CLI".

build_datetime str | None

ISO 8601 string for when the artifact was built (e.g. the moment the Hatchling hook fires). When set, the assembler records it as builtTime on the main software_Package element. When None (default), builtTime is omitted from the SBOM.

pitloom.core.creation.Creator dataclass

Creator(
    name: str,
    type: str = "person",
    email: str | None = None,
)

A single named creator, mapping onto an SPDX 3 Agent.

Attributes:

Name Type Description
name str

Display name of the person or organisation that initiated the SBOM generation. Stripped in __post_init__: the creator Agent carries the name an author is matched on.

type str

Agent subclass: "person" (default), "organization", "software-agent", or the generic "agent". All four are valid createdBy types per the SPDX 3 spec. Validated (and normalised to lower-case, stripped) in __post_init__.

email str | None

E-mail address of the creator. Recorded as an email external identifier on the creator Agent. Stripped in __post_init__; an empty or whitespace-only address is no address (None).

Raises:

Type Description
ValueError

If name is empty or whitespace-only (no name), or if type (after normalisation) is not one of :data:VALID_CREATOR_TYPES.

pitloom.core.creation.Tool dataclass

Tool(name: str)

A single creation tool, mapping onto an SPDX 3 Tool.

Attributes:

Name Type Description
name str

Name of the tool. A tool literally named "Pitloom" gets a version summary appended automatically.

Raises:

Type Description
ValueError

If name is empty or whitespace-only.

pitloom.core.creation.VALID_CREATOR_TYPES module-attribute

VALID_CREATOR_TYPES: frozenset[str] = frozenset(
    {"person", "organization", "software-agent", "agent"}
)

pitloom.core.creation.resolve_source_date_epoch

resolve_source_date_epoch() -> datetime | None

Read SOURCE_DATE_EPOCH as a UTC datetime, per reproducible-builds.org.

https://reproducible-builds.org/specs/source-date-epoch/: a single environment variable the whole build toolchain honours for every embedded timestamp, so an operator opts a build into reproducibility once rather than configuring each tool individually. Shared by every Pitloom timestamp that should respect it (SBOM created, the Hatchling build hook's builtTime, embedded wheel ZIP entries) so the parsing/validation rule -- and what counts as invalid -- stays in one place.

Returns:

Type Description
datetime | None

The resolved UTC datetime, or None when unset or empty --

datetime | None

callers fall back to their own default.

Raises:

Type Description
ValueError

It is set and not an integer number of seconds, or out of range for a date: the specification says a build should fail on a malformed value, as Hatchling does. Every SBOM entry point reads it, whether or not a creation date is pinned, so each reports the one exception, once.

Source code in pitloom/core/creation.py
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
def resolve_source_date_epoch() -> datetime | None:
    """Read ``SOURCE_DATE_EPOCH`` as a UTC datetime, per reproducible-builds.org.

    <https://reproducible-builds.org/specs/source-date-epoch/>: a single
    environment variable the whole build toolchain honours for every
    embedded timestamp, so an operator opts a build into reproducibility
    once rather than configuring each tool individually. Shared by every
    Pitloom timestamp that should respect it (SBOM ``created``, the
    Hatchling build hook's ``builtTime``, embedded wheel ZIP entries) so
    the parsing/validation rule -- and what counts as invalid -- stays in
    one place.

    Returns:
        The resolved UTC datetime, or ``None`` when unset or empty --
        callers fall back to their own default.

    Raises:
        ValueError: It is set and not an integer number of seconds, or out
            of range for a date: the specification says a build should fail
            on a malformed value, as Hatchling does. Every SBOM entry point
            reads it, whether or not a creation date is pinned, so each
            reports the one exception, once.
    """
    raw = os.environ.get("SOURCE_DATE_EPOCH")
    if not raw:
        return None
    try:
        seconds = int(raw)
    except ValueError:
        raise CodedValueError(
            SOURCE_DATE_EPOCH_INVALID, line=EPOCH_NOT_INTEGER_LINE, value=raw
        ) from None
    try:
        return datetime.fromtimestamp(seconds, tz=timezone.utc)
    except (ValueError, OverflowError, OSError):
        raise CodedValueError(
            SOURCE_DATE_EPOCH_INVALID, line=EPOCH_OUT_OF_RANGE_LINE, value=raw
        ) from None

Provenance configuration

pitloom.core.provenance.ProvenanceConfig dataclass

ProvenanceConfig(
    format: str = "both",
    schema: str = DEFAULT_PROVENANCE_SCHEMA,
    detail: str = "minimal",
    preserve_source_metadata: str = "auto",
    max_source_metadata_bytes: int = 0,
)

Configuration settings for SPDX 3 metadata provenance annotations.

Attributes:

Name Type Description
format str

How to record metadata provenance ("annotation", "comment", "both").

schema str

Schema id for provenance Annotations.

detail str

Provenance detail level ("minimal", "full").

preserve_source_metadata str

How to preserve source metadata ("auto", "always", "never").

max_source_metadata_bytes int

Byte budget for the serialised artifact-metadata Annotation.statement; 0 (default) means unlimited, below :data:MIN_SOURCE_METADATA_BYTES is an error. See :func:require_max_source_metadata_bytes.

__post_init__

__post_init__() -> None

Reject an invalid format, schema, detail, preserve setting or budget when built, however it got here, not when provenance is first written; keep the budget as a plain int.

Raises:

Type Description
CodedValueError

A value is not one the setting takes (option-invalid, a ValueError).

Source code in pitloom/core/provenance.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
def __post_init__(self) -> None:
    """Reject an invalid format, schema, detail, preserve setting or
    budget when built, however it got here, not when provenance is
    first written; keep the budget as a plain int.

    Raises:
        pitloom.messages.CodedValueError: A value is not one the setting
            takes (``option-invalid``, a ``ValueError``).
    """
    require_provenance_choices(
        self.format,
        self.schema,
        self.detail,
        self.preserve_source_metadata,
        owner="ProvenanceConfig.",
    )
    object.__setattr__(
        self,
        "max_source_metadata_bytes",
        require_max_source_metadata_bytes(
            self.max_source_metadata_bytes,
            Parameter("ProvenanceConfig.max_source_metadata_bytes"),
        ),
    )

pitloom.core.provenance.require_max_source_metadata_bytes

require_max_source_metadata_bytes(
    value: object,
    where: ConfigPlace | Parameter = _BUDGET_PARAMETER,
) -> int

value as an int when it is 0 (no cap) or a budget of at least :data:MIN_SOURCE_METADATA_BYTES, the smallest annotation that holds any metadata. A smaller one is an error, never a silent "unlimited".

The one validator for every surface that takes the budget but the command-line flag (:func:budget_problem): the config key, ConfigOverrides and the library kwargs. where is the stage: a :class:~pitloom.messages.config.ConfigPlace (a configuration file) raises config-invalid, a :class:~pitloom.messages.config.Parameter (a library caller's value) option-invalid. Any :func:operator.index-able integer (a numpy.int64) passes; a bool or a float does not.

Raises:

Type Description
ValueError

value is not an integer, is negative, or is below the minimum without being 0 (a :class:~pitloom.messages.CodedValueError).

Source code in pitloom/core/provenance.py
 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 require_max_source_metadata_bytes(
    value: object,
    where: ConfigPlace | Parameter = _BUDGET_PARAMETER,
) -> int:
    """*value* as an ``int`` when it is ``0`` (no cap) or a budget of at least
    :data:`MIN_SOURCE_METADATA_BYTES`, the smallest annotation that holds any
    metadata. A smaller one is an error, never a silent "unlimited".

    The one validator for every surface that takes the budget but the
    command-line flag (:func:`budget_problem`): the config key,
    ``ConfigOverrides`` and the library kwargs. *where* is the stage: a
    :class:`~pitloom.messages.config.ConfigPlace` (a configuration file)
    raises ``config-invalid``, a :class:`~pitloom.messages.config.Parameter`
    (a library caller's value) ``option-invalid``. Any
    :func:`operator.index`-able integer (a ``numpy.int64``) passes; a ``bool``
    or a ``float`` does not.

    Raises:
        ValueError: *value* is not an integer, is negative, or is below the
            minimum without being ``0`` (a
            :class:`~pitloom.messages.CodedValueError`).
    """
    problem = budget_problem(value)
    if problem is not None:
        raise invalid_value(where, problem, got=value)
    return operator.index(value)  # type: ignore[arg-type]

Messages

pitloom.messages.code_of

code_of(exc: BaseException) -> str | None

exc's pitloom_code (:data:~pitloom.logging_config.CODE_ATTR, on the instance or its class) when it is a catalogued code, else None. Any exception class can carry one; another attribute, such as the code of an HTTP error, an exit or a remote-source error (git.too-large), is never read. exc's cause is not consulted: a wrapping exception states its own condition.

Source code in pitloom/messages/_emit.py
114
115
116
117
118
119
120
121
122
def code_of(exc: BaseException) -> str | None:
    """*exc*'s ``pitloom_code`` (:data:`~pitloom.logging_config.CODE_ATTR`,
    on the instance or its class) when it is a catalogued code, else
    ``None``. Any exception class can carry one; another attribute, such as
    the ``code`` of an HTTP error, an exit or a remote-source error
    (``git.too-large``), is never read. *exc*'s cause is not consulted: a
    wrapping exception states its own condition."""
    code = getattr(exc, CODE_ATTR, None)
    return code if isinstance(code, str) and code in MESSAGES else None

pitloom.messages.trusted_message

trusted_message(line: str) -> Message | None

The catalogued message line (one printed line, no line ending) says, or None: no code, an uncatalogued one, a text that is not one of the entry's lines at that level (:func:says), or a line longer than :data:LONGEST_LINE.

Source code in pitloom/messages/_lines.py
67
68
69
70
71
72
73
74
75
76
77
78
79
def trusted_message(line: str) -> Message | None:
    """The catalogued message *line* (one printed line, no line ending)
    says, or ``None``: no code, an uncatalogued one, a text that is not
    one of the entry's lines at that level (:func:`says`), or a line longer
    than :data:`LONGEST_LINE`."""
    if len(line) > LONGEST_LINE:
        return None
    found = LINE_RE.fullmatch(line)
    if found is None:
        return None
    level, text, code = found.groups()
    message = MESSAGES.get(code)
    return message if message is not None and says(message, level, text) else None

pitloom.messages.Message dataclass

Message(
    *,
    code: str,
    condition: str,
    lines: tuple[Line, ...],
    summary: str,
    did: str,
    effect: str,
    actor: str,
    advice: str,
    subject_key: str | None = None,
    since: str = "0.22.0",
)

A catalogued message: what Pitloom prints, what it means, what it did and what a reader (a person, or an agent relaying it) should do.

Raises:

Type Description
ValueError

A field breaks the catalogue's rules (see :meth:__post_init__).

family property

family: str

The code before any /: the group of messages of one condition.

levels property

levels: frozenset[str]

The levels its lines are printed at.

__post_init__

__post_init__() -> None

Check the entry against the catalogue's rules.

Source code in pitloom/messages/_types.py
237
238
239
240
241
242
243
def __post_init__(self) -> None:
    """Check the entry against the catalogue's rules."""
    problem = _code_problem(self.code)
    if problem is None:
        problem = self._field_problem()
    if problem is not None:
        raise ValueError(problem)

line_for

line_for(
    level: str,
    names: Collection[str],
    line: Line | None = None,
) -> Line

Its line at level that names exactly names: line, which must be one of them, else the only one.

Raises:

Type Description
ValueError

No line does, line is not one, or several do and line does not say which.

Source code in pitloom/messages/_types.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def line_for(
    self, level: str, names: Collection[str], line: Line | None = None
) -> Line:
    """Its line at *level* that names exactly *names*: *line*, which
    must be one of them, else the only one.

    Raises:
        ValueError: No line does, *line* is not one, or several do and
            *line* does not say which.
    """
    wanted = frozenset(names)
    found = [ln for ln in self.lines if ln.level == level and ln.fields == wanted]
    if line is not None and line in found:
        return line
    if line is None and len(found) == 1:
        return found[0]
    what = "that line is not one" if line is not None else f"{len(found)} name"
    raise ValueError(f"{self.code}: {what} of its {level} lines {sorted(wanted)}")

ID registry

pitloom.id_registry.IdRegistry

IdRegistry(
    namespace: str,
    elements: dict[tuple[str, str], RegistryEntry]
    | None = None,
    path: Path | None = None,
    project_root: Path | None = None,
    *,
    id_counters: Counters | None = None,
    refuse_credentials: bool = False,
)

A Loom ID registry: stable spdxIds keyed by (compact type, name), persisted as JSON.

Each entry may carry the element's SHA-256. Harvest records what an element has; a lookup decides whether the hash must match (:meth:lookup). :attr:id_counters keeps a retired id from being minted again (:meth:reserve_id).

refuse_credentials is the run's url-credentials mode for a key or file entry that holds a credential (:meth:load, :meth:rebase, :meth:register): True refuses it, False (the warn mode, the default) keeps it with a WARNING:.

Raises:

Type Description
ValueError

namespace cannot be a document namespace (:func:~pitloom.id_registry._credentials.require_registry_namespace: credentials-unsafe/registry when it holds credentials, in either mode), so no id is minted in it.

Source code in pitloom/id_registry/_registry.py
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
def __init__(
    self,
    namespace: str,
    elements: dict[tuple[str, str], RegistryEntry] | None = None,
    path: Path | None = None,
    project_root: Path | None = None,
    *,
    id_counters: Counters | None = None,
    refuse_credentials: bool = False,
) -> None:
    self.namespace = require_registry_namespace(namespace)
    #: The ``refuse`` mode for a key or file entry holding a credential.
    self.refuse_credentials = _require_bool(refuse_credentials)
    #: Keyed by :func:`~pitloom.id_registry._types._element_key`.
    self.elements: dict[tuple[str, str], RegistryEntry] = (
        elements if elements is not None else {}
    )
    #: Id prefix -> the highest number minted or seen in
    #: :attr:`namespace`; never lowered, and never below a held id's.
    self.id_counters: Counters = dict(id_counters or {})
    self.path = path
    #: Absolute and realpath'd; ``None`` until set or saved.
    self.project_root: Path | None = (
        Path(os.path.realpath(project_root)) if project_root is not None else None
    )
    # The table and namespace as last read from or written to `path`:
    # what `rebase` tells this object's own changes apart by. None:
    # neither yet.
    self._on_disk: dict[tuple[str, str], RegistryEntry] | None = None
    self._on_disk_namespace: str | None = None
    self._reserve_held()

generate

generate(
    paths: list[Path],
    project_root: Path,
    *,
    exclude: Path | None = None,
    explicit: bool = True,
) -> None

(Re-)index files under paths into this registry, except the exclude file (the declared registry itself).

Each file is registered as (software_File, path key, sha256) (:func:~pitloom.id_registry.keys.join_key of the project's :func:~pitloom.id_registry.keys.project_prefix and the file's path from project_root). A file a project scan lists as an AI model also registers an ai_AIPackage under the same key and hash, so a retrained model (other bytes) gets a new id. A key new or held with other content whose one layout alias (:func:~pitloom.id_registry.keys.alias_tail) is a held key of the same type and hash takes over that entry, its id kept (:meth:promote_alias). Promotion is one way, from the shorter key to the longer; it is skipped when the shorter key is another walked file's or names a file or directory below the root. Files whose keys are equal once NFC-normalised are all left out, one WARNING:.

A path in paths that is not there raises FileNotFoundError (input-not-found), and one that cannot be read or listed a ValueError (file-unreadable, dir-unlistable), each naming it as given; one outside project_root a ValueError (option-invalid). With explicit false (default roots the caller chose, not the user), a missing path is left out silently, and one that cannot be read or listed with a WARNING:.

Source code in pitloom/id_registry/_registry.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def generate(
    self,
    paths: list[Path],
    project_root: Path,
    *,
    exclude: Path | None = None,
    explicit: bool = True,
) -> None:
    """(Re-)index files under *paths* into this registry, except the
    *exclude* file (the declared registry itself).

    Each file is registered as ``(software_File, path key, sha256)``
    (:func:`~pitloom.id_registry.keys.join_key` of the project's
    :func:`~pitloom.id_registry.keys.project_prefix` and the file's path
    from *project_root*). A file a project scan lists as an AI model
    also registers an ``ai_AIPackage`` under the same key and hash, so
    a retrained model (other bytes) gets a new id. A key new or held
    with other content whose one layout alias
    (:func:`~pitloom.id_registry.keys.alias_tail`) is a held key of the
    same type and hash takes over that entry, its id kept
    (:meth:`promote_alias`). Promotion is one way, from the shorter key
    to the longer; it is skipped when the shorter key is another walked
    file's or names a file or directory below the root. Files whose
    keys are equal once NFC-normalised are all left out, one ``WARNING:``.

    A path in *paths* that is not there raises ``FileNotFoundError``
    (``input-not-found``), and one that cannot be read or listed a
    ``ValueError`` (``file-unreadable``, ``dir-unlistable``), each naming
    it as given; one outside *project_root* a ``ValueError``
    (``option-invalid``). With *explicit* false (default roots the caller
    chose, not the user), a missing path is left out silently, and one
    that cannot be read or listed with a ``WARNING:``.
    """
    index_files(self, paths, project_root, exclude, explicit=explicit)

get

get(type_name: str, name: str) -> RegistryEntry | None

Return the entry for name under type_name, or None.

Source code in pitloom/id_registry/_registry.py
300
301
302
def get(self, type_name: str, name: str) -> RegistryEntry | None:
    """Return the entry for *name* under *type_name*, or ``None``."""
    return self.elements.get(_element_key(type_name=type_name, name=name))

harvest

harvest(
    object_set: SHACLObjectSet,
    keys: RecordedKeys | None = None,
    hashes: RecordedHashes | None = None,
) -> tuple[int, bool]

A run's auto-harvest: every named element in object_set, each under the key keys (spdxId -> (compact type, key), what the run's lookups recorded) holds for it when of its type, else its type and name (see :func:~pitloom.id_registry._harvest._harvest_elements). A file in hashes (spdxId -> SHA-256: a Git LFS pointer's oid) records that hash, not the one its element states.

Returns (new_ids, changed): new_ids counts the distinct spdxIds new to the registry under keys new to it too (a replaced or moved id is an update); changed says whether anything changed, an id counter included: what a caller gates a save() on.

Source code in pitloom/id_registry/_registry.py
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
def harvest(
    self,
    object_set: spdx3.SHACLObjectSet,
    keys: RecordedKeys | None = None,
    hashes: RecordedHashes | None = None,
) -> tuple[int, bool]:
    """A run's auto-harvest: every named element in *object_set*, each
    under the key *keys* (spdxId -> (compact type, key), what the run's
    lookups recorded) holds for it when of its type, else its type and
    name (see :func:`~pitloom.id_registry._harvest._harvest_elements`).
    A file in *hashes* (spdxId -> SHA-256: a Git LFS pointer's ``oid``)
    records that hash, not the one its element states.

    Returns ``(new_ids, changed)``: *new_ids* counts the distinct
    spdxIds new to the registry under keys new to it too (a replaced or
    moved id is an update); *changed* says whether anything changed, an
    id counter included: what a caller gates a ``save()`` on.
    """
    self._reserve_held()
    before, counters = dict(self.elements), dict(self.id_counters)
    _harvest_elements(
        self,
        _sorted_by_spdx_id(object_set),
        imported=False,
        keys=keys,
        hashes=hashes,
    )
    changed = self.elements != before or self.id_counters != counters
    return added_ids(before, self.elements), changed

has_name

has_name(name: str) -> bool

Return whether name is registered under any type, as given or as that type's own key form.

Source code in pitloom/id_registry/_registry.py
368
369
370
371
372
373
374
def has_name(self, name: str) -> bool:
    """Return whether *name* is registered under any type, as given or
    as that type's own key form."""
    return any(
        key[1] == name or key == _element_key(type_name=key[0], name=name)
        for key in self.elements
    )

id_count

id_count() -> int

Return the number of distinct spdxIds.

Source code in pitloom/id_registry/_registry.py
376
377
378
def id_count(self) -> int:
    """Return the number of distinct spdxIds."""
    return len({entry.spdx_id for entry in self.elements.values()})

import_sbom

import_sbom(sbom_path: Path) -> frozenset[tuple[str, str]]

Harvest ids from an existing SPDX 3 JSON-LD SBOM into this registry.

Returns the keys not imported because the SBOM holds several elements under one key (:func:~pitloom.id_registry._ambiguous._ambiguous_keys). An empty registry adopts the SBOM's document id as its namespace when that is a namespace IRI, else keeps its own, one WARNING:. The imported id wins, even over a content-gated entry. A file, a dataset package and a model are written under the key a run looks them up by (:func:~pitloom.id_registry.import_keys.import_keys, whose INFO: lines are logged for the elements written), any other element under its name; none moves an id another key of its type holds.

Source code in pitloom/id_registry/_registry.py
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
def import_sbom(self, sbom_path: Path) -> frozenset[tuple[str, str]]:
    """Harvest ids from an existing SPDX 3 JSON-LD SBOM into this registry.

    Returns the keys not imported because the SBOM holds several
    elements under one key
    (:func:`~pitloom.id_registry._ambiguous._ambiguous_keys`). An empty
    registry adopts the SBOM's document id as its namespace when that
    is a namespace IRI, else keeps its own, one ``WARNING:``. The
    imported id wins, even over a content-gated entry. A file, a
    dataset package and a model are written under the key a run looks
    them up by (:func:`~pitloom.id_registry.import_keys.import_keys`,
    whose ``INFO:`` lines are logged for the elements written), any
    other element under its name; none moves an id another key of its
    type holds.
    """
    sorted_objects = read_sbom_objects(sbom_path)
    self._reserve_held()
    if not self.elements:
        namespace = document_id(sorted_objects)
        if namespace is not None:
            self._adopt_namespace(namespace, sbom_path)
    plan = import_keys(self, sorted_objects)
    skipped = _harvest_elements(self, sorted_objects, imported=True, keys=plan.keys)
    report_imported(self, plan)
    return skipped

load classmethod

load(
    path: str | PathLike[str],
    *,
    refuse_credentials: bool = False,
) -> IdRegistry

Load a registry from path.

A file that is not there (or not a file) raises :class:~pitloom.messages.CodedFileNotFoundError (input-not-found); every other failure raises a ValueError carrying its code (:func:~pitloom.id_registry._format.read_registry_file); it never returns None. A message names path as given (a :class:~pitloom.core.given_path.GivenPath or :class:~pitloom.core.given_path.TypedPath keeps its spelling, and :attr:path keeps it too). Whether a registry exists at all is decided upstream, by :func:~pitloom.id_registry.resolve.resolve_registry. A file with an entry whose key or id holds credentials is refused with refuse_credentials (the refuse mode), else loaded as it is with a WARNING: per entry; one whose namespace does is refused in either mode (credentials-unsafe/registry, the value shown masked): nothing is dropped or rewritten, the user edits the file.

Raises:

Type Description
TypeError

path is not a str or os.PathLike (bytes included), or refuse_credentials is not a bool: a wrong argument, not a bad file.

Source code in pitloom/id_registry/_registry.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
@classmethod
def load(
    cls, path: str | os.PathLike[str], *, refuse_credentials: bool = False
) -> IdRegistry:
    """Load a registry from *path*.

    A file that is not there (or not a file) raises
    :class:`~pitloom.messages.CodedFileNotFoundError`
    (``input-not-found``); every other failure raises a ``ValueError``
    carrying its code (:func:`~pitloom.id_registry._format.read_registry_file`);
    it never returns ``None``. A message names *path* as given (a
    :class:`~pitloom.core.given_path.GivenPath` or
    :class:`~pitloom.core.given_path.TypedPath` keeps its spelling, and
    :attr:`path` keeps it too). Whether a registry
    exists at all is decided upstream, by
    :func:`~pitloom.id_registry.resolve.resolve_registry`. A file with
    an entry whose key or id holds credentials is refused with
    *refuse_credentials* (the ``refuse`` mode), else loaded as it is
    with a ``WARNING:`` per entry; one whose namespace does is refused
    in either mode (``credentials-unsafe/registry``, the value shown
    masked): nothing is dropped or rewritten, the user edits the file.

    Raises:
        TypeError: *path* is not a ``str`` or ``os.PathLike`` (bytes
            included), or *refuse_credentials* is not a ``bool``: a
            wrong argument, not a bad file.
    """
    _require_bool(refuse_credentials)
    if not isinstance(path, (str, os.PathLike)):
        raise TypeError(
            "ID registry file path must be a str or os.PathLike, "
            f"not {type(path).__name__}"
        )
    path = keep_spelling(Path(path), path)
    contents = read_registry_file(path)
    check_entries_credentials(contents.elements, path, refuse=refuse_credentials)
    registry = cls(
        namespace=contents.namespace,
        elements=dict(contents.elements),
        path=path,
        project_root=contents.project_root,
        id_counters=contents.id_counters,
        refuse_credentials=refuse_credentials,
    )
    registry._on_disk = contents.elements
    registry._on_disk_namespace = contents.namespace
    return registry

lookup

lookup(
    type_name: str,
    names: Sequence[str],
    *,
    sha256: str | None = None,
    pin_without_hash: bool = False,
    miss_hashed: bool = False,
) -> str | None

Return the spdxId of the first of names registered under type_name, or None.

With sha256, an entry recording the same SHA-256 (any case) is a hit; an entry with no hash is one only with pin_without_hash (an explicit pin, held for any content), so then only an entry recording another hash misses. Without sha256, the entry's hash is ignored (with miss_hashed, a hashed entry misses: no content vouches for it), and so is pin_without_hash. The first of names to hit wins.

Source code in pitloom/id_registry/_registry.py
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
def lookup(
    self,
    type_name: str,
    names: Sequence[str],
    *,
    sha256: str | None = None,
    pin_without_hash: bool = False,
    miss_hashed: bool = False,
) -> str | None:
    """Return the ``spdxId`` of the first of *names* registered under
    *type_name*, or ``None``.

    With *sha256*, an entry recording the same SHA-256 (any case) is a
    hit; an entry with no hash is one only with *pin_without_hash* (an
    explicit pin, held for any content), so then only an entry
    recording another hash misses. Without *sha256*, the entry's hash is
    ignored (with *miss_hashed*, a hashed entry misses: no content vouches
    for it), and so is *pin_without_hash*. The first of *names* to hit wins."""
    _require_names(names)
    wanted = sha256.lower() if sha256 is not None else None
    for name in names:
        entry = self.get(type_name, name)
        if entry is None:
            continue
        if wanted is None:
            if miss_hashed and entry.sha256 is not None:
                continue
            return entry.spdx_id
        if entry.sha256 == wanted or (pin_without_hash and entry.sha256 is None):
            return entry.spdx_id
    return None

new classmethod

new(
    project_name: str,
    path: Path | None = None,
    *,
    namespace: str | None = None,
    project_root: Path | None = None,
    refuse_credentials: bool = False,
) -> IdRegistry

Create a fresh, empty registry (refuse_credentials: see :class:IdRegistry).

The namespace is namespace (an absolute IRI without # or credentials; a ValueError otherwise, see :class:IdRegistry), else one minted from project_name (the CLI passes the project directory's name) and a random UUID4. It is fixed once the registry is created: the registry file is an input, so a committed one gives identical ids. A name-derived UUID would give two unrelated projects of one name the same ids.

Source code in pitloom/id_registry/_registry.py
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
@classmethod
def new(
    cls,
    project_name: str,
    path: Path | None = None,
    *,
    namespace: str | None = None,
    project_root: Path | None = None,
    refuse_credentials: bool = False,
) -> IdRegistry:
    """Create a fresh, empty registry (*refuse_credentials*: see
    :class:`IdRegistry`).

    The namespace is *namespace* (an absolute IRI without ``#`` or
    credentials; a ``ValueError`` otherwise, see :class:`IdRegistry`),
    else one minted from *project_name* (the
    CLI passes the project directory's name) and a random UUID4. It is
    fixed once the registry is created: the registry file is an input, so
    a committed one gives identical ids.
    A name-derived UUID would give two unrelated projects of one name the
    same ids.
    """
    if namespace is None:
        namespace = doc_namespace(project_name, str(uuid4()))
    return cls(
        namespace=namespace,
        path=path,
        project_root=project_root,
        refuse_credentials=refuse_credentials,
    )

promote_alias

promote_alias(
    type_name: str, old_key: str, new_key: str
) -> bool

Re-key the entry of old_key under type_name as new_key, its spdxId and SHA-256 kept (no mint, no counter); False and no change when old_key is not held, new_key is, or is not UTF-8.

Source code in pitloom/id_registry/_registry.py
390
391
392
393
394
395
396
397
398
399
400
401
def promote_alias(self, type_name: str, old_key: str, new_key: str) -> bool:
    """Re-key the entry of *old_key* under *type_name* as *new_key*, its
    ``spdxId`` and SHA-256 kept (no mint, no counter); ``False`` and no
    change when *old_key* is not held, *new_key* is, or is not UTF-8."""
    old = _element_key(type_name=type_name, name=old_key)
    new = _element_key(type_name=type_name, name=new_key)
    if old not in self.elements or new in self.elements:
        return False
    if not is_utf8_text(new[1]):
        return False
    self.elements[new] = self.elements.pop(old)
    return True

rebase

rebase() -> Rebase

Re-read :attr:path and apply this object's own changes again on top (:func:~pitloom.id_registry._persist.replay_changes), so a save keeps what another run saved meanwhile.

A change is a key whose entry differs from the table this object last read or wrote; for one that has read or written none, every entry is. The project root becomes the file's, and so does the namespace, unless this object changed the one it read (id import adopting an SBOM's) and the file still has that one. The id counters merge by maximum, so neither run lowers one. With no file at :attr:path yet, the registry is left as it is.

Raises:

Type Description
FileNotFoundError

the file is no longer there, or not a file.

ValueError

the file cannot be loaded, or an entry holds a credential in the refuse mode (:meth:load); this object is left unchanged.

Source code in pitloom/id_registry/_registry.py
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
def rebase(self) -> Rebase:
    """Re-read :attr:`path` and apply this object's own changes again on
    top (:func:`~pitloom.id_registry._persist.replay_changes`), so a
    save keeps what another run saved meanwhile.

    A change is a key whose entry differs from the table this object
    last read or wrote; for one that has read or written none, every
    entry is. The project root becomes the file's, and so does the
    namespace, unless this object changed the one it read (``id
    import`` adopting an SBOM's) and the file still has that one. The
    id counters merge by maximum, so neither run lowers one. With no
    file at :attr:`path` yet, the registry is left as it is.

    Raises:
        FileNotFoundError: the file is no longer there, or not a file.
        ValueError: the file cannot be loaded, or an entry holds a
            credential in the ``refuse`` mode (:meth:`load`); this
            object is left unchanged.
    """
    base = self._on_disk or {}
    if self.path is None or (
        self._on_disk is None and not os.path.exists(self.path)
    ):
        return Rebase(
            refused=0, pending=True, added=new_id_count(self.elements, base)
        )
    contents = read_registry_file(self.path)
    # An entry another run saved meanwhile is held to load()'s rule.
    check_entries_credentials(
        contents.elements, self.path, refuse=self.refuse_credentials
    )
    merged, refused = replay_changes(base, self.elements, contents.elements)
    self.elements.clear()
    self.elements.update(merged)
    if contents.namespace != self._on_disk_namespace or (
        self.namespace == self._on_disk_namespace
    ):
        self.namespace = contents.namespace
    self.project_root = contents.project_root
    self.id_counters = merge_counters(self.id_counters, contents.id_counters)
    self._reserve_held()
    self._on_disk = contents.elements
    self._on_disk_namespace = contents.namespace
    return Rebase(
        refused=refused,
        pending=merged != contents.elements
        or self.id_counters != contents.id_counters
        or self.namespace != contents.namespace,
        added=new_id_count(merged, base, contents.elements),
    )

refuse_mode

refuse_mode() -> None

Turn this registry to the refuse mode (a run that refuses was given it loaded), checking its entries as :meth:load would.

Raises:

Type Description
CodedValueError

credentials-unsafe/registry: an entry's key or id holds a credential; the mode is left unchanged.

Source code in pitloom/id_registry/_registry.py
235
236
237
238
239
240
241
242
243
244
245
246
247
def refuse_mode(self) -> None:
    """Turn this registry to the ``refuse`` mode (a run that refuses
    was given it loaded), checking its entries as :meth:`load` would.

    Raises:
        pitloom.messages.CodedValueError: ``credentials-unsafe/registry``:
            an entry's key or id holds a credential; the mode is left
            unchanged.
    """
    check_entries_credentials(
        self.elements, self.path or "(not saved)", refuse=True
    )
    self.refuse_credentials = True

register

register(
    type_name: str, name: str, *, sha256: str | None = None
) -> str

Register name under type_name and return its spdxId.

No entry: mint (prefix :func:type_id_prefix) and store sha256. An entry and no sha256, or an equal one: reuse it unchanged, so an ungated registration never erases a recorded hash. A dataset package pin with no hash given one: keep its id, record sha256 (gated from now on), one INFO:. A sha256 that differs from the entry's, or (any other type) an entry with none: log content changed, mint a new id and replace the entry.

Raises:

Type Description
ValueError

type_name or name cannot be encoded as UTF-8 (the file could never be saved), or name is a URL holding credentials in the refuse mode (credentials-unsafe/registry; the warn mode stores it with a WARNING:).

Source code in pitloom/id_registry/_registry.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def register(self, type_name: str, name: str, *, sha256: str | None = None) -> str:
    """Register *name* under *type_name* and return its ``spdxId``.

    No entry: mint (prefix :func:`type_id_prefix`) and store *sha256*.
    An entry and no *sha256*, or an equal one: reuse it unchanged, so an
    ungated registration never erases a recorded hash. A dataset
    package pin with no hash given one: keep its id, record *sha256*
    (gated from now on), one ``INFO:``. A *sha256* that differs from
    the entry's, or (any other type) an entry with none: log ``content
    changed``, mint a new id and replace the entry.

    Raises:
        ValueError: *type_name* or *name* cannot be encoded as UTF-8
            (the file could never be saved), or *name* is a URL holding
            credentials in the ``refuse`` mode
            (``credentials-unsafe/registry``; the ``warn`` mode stores
            it with a ``WARNING:``).
    """
    for label, text in (("type name", type_name), ("name", name)):
        if not is_utf8_text(text):
            raise registry_name_error(label, text)
    check_key_credentials(type_name, name, refuse=self.refuse_credentials)
    key = _element_key(type_name=type_name, name=name)
    given = sha256.lower() if sha256 is not None else None
    existing = self.elements.get(key)
    if existing is not None:
        if given is None or existing.sha256 == given:
            return existing.spdx_id
        if existing.sha256 is None and type_name == DATASET_PACKAGE_TYPE:
            emit(
                log,
                REGISTRY_HASH_MISSING,
                logging.INFO,
                line=PIN_GATED_LINE,
                entity=name,
            )
            self.elements[key] = RegistryEntry(existing.spdx_id, given)
            return existing.spdx_id
        emit(
            log,
            REGISTRY_HASH_CONFLICT,
            logging.INFO,
            line=HASH_CHANGED_LINE,
            entity=name,
            spdx_id=existing.spdx_id,
        )
    spdx_id = self._mint_id(type_id_prefix(type_name))
    self.elements[key] = RegistryEntry(spdx_id=spdx_id, sha256=given)
    return spdx_id

require_namespace

require_namespace(namespace: str) -> None

Raise ValueError unless this registry's namespace is namespace (id generate --namespace on an existing registry: silently keeping the old one would ignore the flag).

Source code in pitloom/id_registry/_registry.py
341
342
343
344
345
346
347
348
349
350
351
352
def require_namespace(self, namespace: str) -> None:
    """Raise ``ValueError`` unless this registry's namespace is
    *namespace* (``id generate --namespace`` on an existing registry:
    silently keeping the old one would ignore the flag)."""
    if namespace != self.namespace:
        raise CodedValueError(
            OPTION_CONFLICT,
            line=namespace_conflict_line(self.namespace, namespace),
            file=self._named(),
            namespace=self.namespace,
            given_namespace=namespace,
        )

require_project_root

require_project_root(project_root: Path) -> None

Raise ValueError unless this registry's project root (:meth:root_dir) is project_root (same directory, whatever the spelling): keys from two roots in one registry would not match.

Source code in pitloom/id_registry/_registry.py
354
355
356
357
358
359
360
361
362
363
364
365
366
def require_project_root(self, project_root: Path) -> None:
    """Raise ``ValueError`` unless this registry's project root
    (:meth:`root_dir`) is *project_root* (same directory, whatever the
    spelling): keys from two roots in one registry would not match."""
    root = self.root_dir()
    if not same_path(root, project_root):
        raise CodedValueError(
            OPTION_CONFLICT,
            line=PROJECT_ROOT_CONFLICT_LINE,
            file=self._named(),
            path=root,
            root=project_root,
        )

reserve_id

reserve_id(spdx_id: str) -> None

Never mint spdx_id: when it is <namespace>#<prefix>-<n> in this registry's namespace (:func:~pitloom.id_registry._counters.id_number), raise the prefix's counter to n. Any other id is ignored, and so is an n above :data:~pitloom.id_registry._counters.RESERVE_CEILING: an SBOM could otherwise use up every number. :meth:_mint_id skips such an id while the table holds it.

Source code in pitloom/id_registry/_registry.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def reserve_id(self, spdx_id: str) -> None:
    """Never mint *spdx_id*: when it is ``<namespace>#<prefix>-<n>`` in
    this registry's namespace (:func:`~pitloom.id_registry._counters.id_number`),
    raise the prefix's counter to *n*. Any other id is ignored, and so
    is an *n* above
    :data:`~pitloom.id_registry._counters.RESERVE_CEILING`: an SBOM
    could otherwise use up every number. :meth:`_mint_id` skips such an
    id while the table holds it."""
    found = id_number(self.namespace, spdx_id)
    if (
        found is not None
        and self.id_counters.get(found[0], 0) < found[1] <= RESERVE_CEILING
    ):
        self.id_counters[found[0]] = found[1]

root_dir

root_dir() -> Path

Return the project root, else the registry file's directory, else the current directory -- realpath'd (OSError when that directory was deleted).

Source code in pitloom/id_registry/_registry.py
380
381
382
383
384
385
386
387
388
def root_dir(self) -> Path:
    """Return the project root, else the registry file's directory,
    else the current directory -- realpath'd (``OSError`` when that
    directory was deleted)."""
    if self.project_root is not None:
        return Path(os.path.realpath(self.project_root))
    if self.path is not None:
        return registry_dir(self.path)
    return Path(os.path.realpath(os.getcwd()))

save

save(path: Path | None = None) -> None

Write this registry as JSON to path (default: :attr:path).

With no :attr:project_root yet, the registry file's directory becomes the project root. Raises ValueError when there is no path, or when the project root cannot be stored relative to it.

Source code in pitloom/id_registry/_registry.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
def save(self, path: Path | None = None) -> None:
    """Write this registry as JSON to *path* (default: :attr:`path`).

    With no :attr:`project_root` yet, the registry file's directory
    becomes the project root. Raises ``ValueError`` when there is no
    path, or when the project root cannot be stored relative to it.
    """
    target = path or self.path
    if target is None:
        raise ValueError("No path given and registry has no default path")
    root = (
        self.project_root if self.project_root is not None else registry_dir(target)
    )
    self._reserve_held()
    write_registry_file(
        target, self.namespace, self.elements, root, self.id_counters
    )
    self.path = target
    self.project_root = root
    self._on_disk = dict(self.elements)
    self._on_disk_namespace = self.namespace

pitloom.id_registry.IdRegistrySession

IdRegistrySession(registry: IdRegistry | None)

One document's registry lookups, first-claimant-wins.

Every element that would otherwise call registry.lookup directly, across an entire document build (files, directories, AI models, the project's own, dependency and phantom packages, deployed packages, loom fragments), instead goes through one shared session so a registry hit reused by two different elements is claimed by only the first -- see :meth:lookup_key, :meth:lookup_package and :meth:lookup_id.

Source code in pitloom/id_registry/_session.py
130
131
132
133
134
135
136
137
138
139
140
141
142
def __init__(self, registry: IdRegistry | None) -> None:
    self._registry = registry
    #: spdxId -> the claimant key that first claimed it.
    self._claimed: dict[str, str] = {}
    #: spdxId -> (type name, raw key) it is harvested under.
    self._keys: dict[str, tuple[str, str]] = {}
    #: spdxId -> the SHA-256 harvest records for it, when not the one
    #: its element states (a Git LFS pointer's ``oid``).
    self._hashes: dict[str, str] = {}
    #: (type name, key) whose layout-alias tie was logged.
    self._ties: set[tuple[str, str]] = set()
    #: Claimed hits found through a layout alias.
    self._alias_hits = 0

registry property

registry: IdRegistry | None

The underlying :class:IdRegistry, or None when none applies.

claimed_ids

claimed_ids() -> list[str]

Return every id claimed so far in this session, in claim order.

Source code in pitloom/id_registry/_session.py
363
364
365
def claimed_ids(self) -> list[str]:
    """Return every id claimed so far in this session, in claim order."""
    return list(self._claimed)

info_layout_alias_hits

info_layout_alias_hits() -> None

Log the one INFO: (registry-key-moved) counting this session's claimed hits found through a layout alias, if any.

Source code in pitloom/id_registry/_session.py
308
309
310
311
312
313
314
315
316
317
318
def info_layout_alias_hits(self) -> None:
    """Log the one ``INFO:`` (``registry-key-moved``) counting this
    session's claimed hits found through a layout alias, if any."""
    if self._alias_hits:
        emit(
            log,
            REGISTRY_KEY_MOVED,
            logging.INFO,
            line=ALIAS_HITS_LINE,
            number=self._alias_hits,
        )

lookup_id

lookup_id(
    claimant: str,
    type_name: str,
    names: Sequence[str],
    *,
    sha256: str | None = None,
    on_miss: Callable[[], None] | None = None,
) -> str | None

Look up the id registered under type_name for the first of names that hits, claim it, and return it -- or None.

names (a package's or a directory's name) are tried in order, each as given, then display-escaped (:func:~pitloom.core.untrusted_text.escape_display_controls): a registry imported from an SBOM holds a name as the SBOM shows it, escaped. With sha256, only an entry recording that hash is a hit (see :meth:~pitloom.id_registry.IdRegistry.lookup). on_miss is called only when every name is a raw miss -- never when a hit exists but this session's claim is rejected (see :meth:_claim). Returns None immediately, without calling on_miss, when no registry is loaded in this session.

Source code in pitloom/id_registry/_session.py
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
def lookup_id(
    self,
    claimant: str,
    type_name: str,
    names: Sequence[str],
    *,
    sha256: str | None = None,
    on_miss: Callable[[], None] | None = None,
) -> str | None:
    """Look up the id registered under *type_name* for the first of
    *names* that hits, claim it, and return it -- or ``None``.

    *names* (a package's or a directory's name) are tried in order,
    each as given, then display-escaped
    (:func:`~pitloom.core.untrusted_text.escape_display_controls`): a
    registry imported from an SBOM holds a name as the SBOM shows it,
    escaped. With *sha256*, only an entry recording that hash is a hit
    (see :meth:`~pitloom.id_registry.IdRegistry.lookup`). *on_miss* is
    called only when every name is a raw miss -- never when a hit
    exists but this session's claim is rejected (see :meth:`_claim`).
    Returns ``None`` immediately, without calling *on_miss*, when no
    registry is loaded in this session.
    """
    _require_names(names)
    if self._registry is None:
        return None
    spdx_id = self._registry.lookup(type_name, _spellings(names), sha256=sha256)
    if spdx_id is not None:
        return self._claim(claimant, spdx_id)
    if on_miss is not None:
        on_miss()
    return None

lookup_key

lookup_key(
    claimant: str,
    type_name: str,
    lookup: LookupKey,
    *,
    sha256: str | None = None,
    pin_without_hash: bool = False,
    miss_hashed: bool = False,
    on_miss: Callable[[], None] | None = None,
) -> str | None

Look up the id registered under type_name for lookup, claim it, record the key it is harvested under, and return it -- or None.

In order: (1) lookup.key as given; (2) display-escaped (:func:~pitloom.core.untrusted_text.escape_display_controls), as :meth:lookup_id does; (3) only when both miss, lookup.alias is not NONE and sha256 is given: the one held layout alias in lookup.alias's direction (either spelling, below lookup.base) recording sha256 (:func:~pitloom.id_registry.keys.alias_candidates); more than one is a miss with one INFO: per type and key in this session; (4) a hit is claimed (see :meth:_claim); (5) a claimed id records lookup.key (raw), or under LAYOUT the held key it matched (see :meth:recorded_keys). With sha256, only an entry recording that hash is a hit, or in (1) and (2) one recording none with pin_without_hash (see :meth:IdRegistry.lookup); without it, no alias is tried, and with miss_hashed an entry recording a hash misses. A claimed alias hit is counted (:meth:info_layout_alias_hits). on_miss is called on a miss, never on a rejected claim. Returns None without calling on_miss or recording when no registry is loaded.

Source code in pitloom/id_registry/_session.py
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
def lookup_key(
    self,
    claimant: str,
    type_name: str,
    lookup: LookupKey,
    *,
    sha256: str | None = None,
    pin_without_hash: bool = False,
    miss_hashed: bool = False,
    on_miss: Callable[[], None] | None = None,
) -> str | None:
    """Look up the id registered under *type_name* for *lookup*, claim
    it, record the key it is harvested under, and return it -- or
    ``None``.

    In order: (1) ``lookup.key`` as given; (2) display-escaped
    (:func:`~pitloom.core.untrusted_text.escape_display_controls`), as
    :meth:`lookup_id` does; (3) only when both miss, ``lookup.alias`` is
    not ``NONE`` and *sha256* is given: the one held layout alias in
    ``lookup.alias``'s direction (either spelling, below
    ``lookup.base``) recording *sha256*
    (:func:`~pitloom.id_registry.keys.alias_candidates`); more than one
    is a miss with one ``INFO:`` per type and key in this session; (4)
    a hit is claimed (see :meth:`_claim`); (5) a claimed id records
    ``lookup.key`` (raw), or under ``LAYOUT`` the held key it matched
    (see :meth:`recorded_keys`). With *sha256*, only an entry recording
    that hash is a hit, or in (1) and (2) one recording none with
    *pin_without_hash* (see :meth:`IdRegistry.lookup`); without it, no
    alias is tried, and with *miss_hashed* an entry recording a hash
    misses. A claimed alias hit is counted
    (:meth:`info_layout_alias_hits`). *on_miss* is called on a miss,
    never on a rejected claim. Returns ``None`` without calling
    *on_miss* or recording when no registry is loaded.
    """
    registry = self._registry
    if registry is None:
        return None
    key = lookup.key
    spdx_id = registry.lookup(
        type_name,
        _spellings((key,)),
        sha256=sha256,
        pin_without_hash=pin_without_hash,
        miss_hashed=miss_hashed,
    )
    aliased = False
    if spdx_id is None and lookup.alias is not Alias.NONE and sha256 is not None:
        held = self._held_alias(registry, type_name, lookup, sha256)
        if held is not None:
            spdx_id = registry.lookup(type_name, (held,), sha256=sha256)
            key = held if lookup.alias is Alias.LAYOUT else key
            aliased = True
    if spdx_id is None:
        if on_miss is not None:
            on_miss()
        return None
    claimed = self._claim(claimant, spdx_id)
    if claimed is not None:
        self._keys[claimed] = (type_name, key)
        self._alias_hits += aliased
    return claimed

lookup_package

lookup_package(
    claimant: str, name: str, version: str | None
) -> str | None

Look up the id registered for the package name at version, claim it, record its key for harvest, and return it -- or None.

The key is :func:~pitloom.id_registry._types.package_key: with the version a package states, else bare, and a bare key never hits a versioned entry or the reverse. It is tried as built, then built from the display-escaped name and version (a registry imported from an SBOM holds them as the SBOM shows them); a claimed hit records the key as built (see :meth:recorded_keys), the key a harvest of the element derives from its name and version. Ungated, as every package lookup.

Source code in pitloom/id_registry/_session.py
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
def lookup_package(
    self, claimant: str, name: str, version: str | None
) -> str | None:
    """Look up the id registered for the package *name* at *version*,
    claim it, record its key for harvest, and return it -- or ``None``.

    The key is :func:`~pitloom.id_registry._types.package_key`: with
    the version a package states, else bare, and a bare key never hits
    a versioned entry or the reverse. It is tried as built, then built
    from the display-escaped name and version (a registry imported from
    an SBOM holds them as the SBOM shows them); a claimed hit records
    the key as built (see :meth:`recorded_keys`), the key a harvest of
    the element derives from its name and version. Ungated, as every
    package lookup."""
    if self._registry is None:
        return None
    key = package_key(name, version)
    shown = package_key(
        escape_display_controls(name),
        None if version is None else escape_display_controls(version),
    )
    spdx_id = self._registry.lookup(PACKAGE_TYPE, list(dict.fromkeys((key, shown))))
    if spdx_id is None:
        return None
    claimed = self._claim(claimant, spdx_id)
    if claimed is not None:
        self._keys[claimed] = (PACKAGE_TYPE, key)
    return claimed

record_key

record_key(
    spdx_id: str,
    type_name: str,
    key: str,
    *,
    sha256: str | None = None,
) -> None

Record the raw (never display-escaped) key under type_name that spdx_id, minted after a miss, is harvested under. A key recorded by a hit (:meth:lookup_key) wins. sha256, when given, is the SHA-256 harvest records for spdx_id instead of the one its element states (see :meth:recorded_hashes). No-op when no registry is loaded.

Source code in pitloom/id_registry/_session.py
320
321
322
323
324
325
326
327
328
329
330
331
332
def record_key(
    self, spdx_id: str, type_name: str, key: str, *, sha256: str | None = None
) -> None:
    """Record the raw (never display-escaped) *key* under *type_name*
    that *spdx_id*, minted after a miss, is harvested under. A key
    recorded by a hit (:meth:`lookup_key`) wins. *sha256*, when given,
    is the SHA-256 harvest records for *spdx_id* instead of the one its
    element states (see :meth:`recorded_hashes`). No-op when no
    registry is loaded."""
    if self._registry is not None:
        self._keys.setdefault(spdx_id, (type_name, key))
        if sha256 is not None:
            self._hashes[spdx_id] = sha256

recorded_hashes

recorded_hashes() -> Mapping[str, str]

A read-only view of spdxId -> the SHA-256 harvest records for it in place of the one its element states, given to :meth:record_key (a Git LFS pointer's oid, whatever digest the SBOM states); an id with none is absent.

Source code in pitloom/id_registry/_session.py
340
341
342
343
344
345
def recorded_hashes(self) -> Mapping[str, str]:
    """A read-only view of spdxId -> the SHA-256 harvest records for it
    in place of the one its element states, given to :meth:`record_key`
    (a Git LFS pointer's ``oid``, whatever digest the SBOM states); an
    id with none is absent."""
    return MappingProxyType(self._hashes)

recorded_keys

recorded_keys() -> Mapping[str, tuple[str, str]]

A read-only view of spdxId -> (type name, raw key) recorded by :meth:lookup_key and :meth:record_key; an id with no recorded key is absent.

Source code in pitloom/id_registry/_session.py
334
335
336
337
338
def recorded_keys(self) -> Mapping[str, tuple[str, str]]:
    """A read-only view of spdxId -> (type name, raw key) recorded by
    :meth:`lookup_key` and :meth:`record_key`; an id with no recorded
    key is absent."""
    return MappingProxyType(self._keys)

register_id

register_id(
    claimant: str, type_name: str, name: str, *, sha256: str
) -> str | None

Register name under type_name with sha256 (:meth:~pitloom.id_registry.IdRegistry.register) and claim the id for claimant, as a hit would be (see :meth:_claim): a later lookup hitting it in this session mints its own id.

Raises:

Type Description
ValueError

no registry is loaded in this session.

Source code in pitloom/id_registry/_session.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
def register_id(
    self, claimant: str, type_name: str, name: str, *, sha256: str
) -> str | None:
    """Register *name* under *type_name* with *sha256*
    (:meth:`~pitloom.id_registry.IdRegistry.register`) and claim the id
    for *claimant*, as a hit would be (see :meth:`_claim`): a later
    lookup hitting it in this session mints its own id.

    Raises:
        ValueError: no registry is loaded in this session.
    """
    if self._registry is None:
        raise ValueError("no ID registry loaded in this session")
    spdx_id = self._registry.register(type_name, name, sha256=sha256)
    return self._claim(claimant, spdx_id)

pitloom.id_registry.resolve_registry

resolve_registry(
    id_registry: str | Path | IdRegistry | None,
    configured: str | None,
    base_dir: Path,
    *,
    refuse_credentials: bool = False,
) -> IdRegistry | None

Resolve the registry a build should consult -- an explicit source only, never searched for.

Precedence: id_registry (a flag/kwarg, or an already-loaded :class:IdRegistry), else configured (the applicable config's own id-registry: the project's own [tool.pitloom], or an explicit --config, which replaces it). Neither given: None, silently -- no loom-id-registry.json is searched for, near the target or anywhere else. A relative path resolves against base_dir (the project directory, or the current directory for a target with none of its own), itself resolved first, so the loaded registry's path is absolute even for a relative base_dir; an already-absolute path (e.g. a config's own key, made absolute by :func:~pitloom.core.config_cascade.load_config_file, or a CLI flag made absolute against cwd) is used as it is.

A resolved path that is not a file raises the input-not-found FileNotFoundError, naming the path as given: id_registry or configured as passed, or the spelling a :class:~pitloom.core.given_path.GivenPath keeps (the CLI flag, a --config file's key), never the resolved form. One that does not load raises ValueError (via :meth:IdRegistry.load), naming the path as given too -- a declared registry is always meant to load; this function never swallows that failure. refuse_credentials is the run's url-credentials mode (CredentialPolicy.refuse) for a registry loaded here (:class:IdRegistry); one passed in is turned to the refuse mode when the run refuses (:meth:IdRegistry.refuse_mode), never back. That case is the library's only: a registry the caller loaded in the warn mode (its entry that holds a credential already said with a WARNING:) and passed to a run that refuses is checked again here and raises credentials-unsafe/registry for that entry; a registry passed in the refuse mode stays so in a warn run.

Source code in pitloom/id_registry/resolve.py
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
def resolve_registry(
    id_registry: str | Path | IdRegistry | None,
    configured: str | None,
    base_dir: Path,
    *,
    refuse_credentials: bool = False,
) -> IdRegistry | None:
    """Resolve the registry a build should consult -- an explicit source
    only, never searched for.

    Precedence: *id_registry* (a flag/kwarg, or an already-loaded
    :class:`IdRegistry`), else *configured* (the applicable config's own
    ``id-registry``: the project's own ``[tool.pitloom]``, or an explicit
    ``--config``, which replaces it). Neither given: ``None``, silently --
    no ``loom-id-registry.json`` is searched for, near the target or
    anywhere else. A relative path resolves against *base_dir* (the
    project directory, or the current directory for a target with none of
    its own), itself resolved first, so the loaded registry's path is
    absolute even for a relative *base_dir*; an already-absolute path (e.g.
    a config's own key, made absolute by
    :func:`~pitloom.core.config_cascade.load_config_file`, or a CLI flag
    made absolute against cwd) is used as it is.

    A resolved path that is not a file raises the ``input-not-found``
    ``FileNotFoundError``, naming the path as given: *id_registry* or
    *configured* as passed, or the spelling a
    :class:`~pitloom.core.given_path.GivenPath` keeps (the CLI flag, a
    ``--config`` file's key), never the resolved form. One that does not
    load raises ``ValueError`` (via :meth:`IdRegistry.load`), naming the
    path as given too -- a declared registry is always meant to load; this
    function never swallows that failure. *refuse_credentials* is the run's
    ``url-credentials`` mode (``CredentialPolicy.refuse``) for a registry
    loaded here (:class:`IdRegistry`); one passed in is turned to the
    ``refuse`` mode when the run refuses (:meth:`IdRegistry.refuse_mode`),
    never back. That case is the library's only: a registry the caller
    loaded in the ``warn`` mode (its entry that holds a credential already
    said with a ``WARNING:``) and passed to a run that refuses is checked
    again here and raises ``credentials-unsafe/registry`` for that entry;
    a registry passed in the ``refuse`` mode stays so in a ``warn`` run.
    """
    source = id_registry if id_registry is not None else configured
    if source is None:
        return None
    if isinstance(source, IdRegistry):
        if refuse_credentials and not source.refuse_credentials:
            source.refuse_mode()
        return source
    path = Path(source)
    resolved = path if path.is_absolute() else base_dir.resolve() / path
    if not is_input_file(resolved, shown=given_spelling(source)):
        # Named as given, never as resolved: no absolute or temporary path.
        raise input_not_found("ID registry file", given_spelling(source), at=resolved)
    # Named as given, as the line above: a load failure names what was typed.
    return IdRegistry.load(
        TypedPath(GivenPath(resolved, given_spelling(source))),
        refuse_credentials=refuse_credentials,
    )

pitloom.id_registry.registry_base_dir

registry_base_dir(target: Path) -> Path

The base directory a relative declared id-registry path resolves against, for a target that may be either a project directory or a single file (e.g. an sdist archive).

A file target has no directory to resolve a relative registry path against (a registry path is not read from inside an archive), so the current directory is used, as with no project_dir. For every resolve_registry() call site whose target might be an sdist (or, in :mod:pitloom.embed, any single-file project_dir).

Source code in pitloom/id_registry/resolve.py
36
37
38
39
40
41
42
43
44
45
46
47
def registry_base_dir(target: Path) -> Path:
    """The base directory a relative declared ``id-registry`` path
    resolves against, for a *target* that may be either a project
    directory or a single file (e.g. an sdist archive).

    A file target has no directory to resolve a relative registry path
    against (a registry path is not read from inside an archive), so the
    current directory is used, as with no ``project_dir``. For every
    ``resolve_registry()`` call site whose *target* might be an sdist (or,
    in :mod:`pitloom.embed`, any single-file ``project_dir``).
    """
    return Path.cwd() if os.path.isfile(target) else target

pitloom.id_registry.warn_claim_collision

warn_claim_collision(
    spdx_id: str, first: str, second: str
) -> None

Log the one WARNING: (registry-conflict) for spdx_id wanted by second after first already took it; second mints its own id. The fields escape each value: a claimant names a path, or a package and its version, as read.

Source code in pitloom/id_registry/_session.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def warn_claim_collision(spdx_id: str, first: str, second: str) -> None:
    """Log the one ``WARNING:`` (``registry-conflict``) for *spdx_id* wanted
    by *second* after *first* already took it; *second* mints its own id.
    The fields escape each value: a claimant names a path, or a package and
    its version, as read."""
    emit(
        log,
        REGISTRY_CONFLICT,
        logging.WARNING,
        line=CLAIM_LINE,
        spdx_id=spdx_id,
        entity=first,
        claimant=second,
    )

pitloom.id_registry.persist_registry

persist_registry(
    registry: IdRegistry, new_ids: int, changed: bool
) -> None

Save what a run added to registry and log the outcome.

new_ids counts the distinct ids the run added; changed says whether it changed anything at all. With no file path: the no-path WARNING:. Nothing changed: nothing. Else :func:save_registry, and one INFO: summary when it wrote, counting the new ids the save adds to the file, at most new_ids (so neither another run's ids nor a refused one count). A failure, the re-read included, is its own line as one WARNING: (:func:~pitloom.messages.id_registry.say_save_failure) and otherwise ignored: the run's own output is already built.

Source code in pitloom/id_registry/_persist.py
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
def persist_registry(registry: IdRegistry, new_ids: int, changed: bool) -> None:
    """Save what a run added to *registry* and log the outcome.

    *new_ids* counts the distinct ids the run added; *changed* says whether
    it changed anything at all. With no file path: the no-path ``WARNING:``.
    Nothing changed: nothing. Else :func:`save_registry`, and one ``INFO:``
    summary when it wrote, counting the new ids the save adds to the file,
    at most *new_ids* (so neither another run's ids nor a refused one
    count). A failure, the re-read included, is its own line as one
    ``WARNING:`` (:func:`~pitloom.messages.id_registry.say_save_failure`)
    and otherwise ignored: the run's own output is already built.
    """
    if registry.path is None:
        warn_no_registry_path()
        return
    if not changed:
        return
    try:
        rebased = save_registry(registry)
    except (OSError, ValueError) as exc:
        say_save_failure(log, exc, file=registry.path, fatal=False)
        return
    if not rebased.pending:
        return
    added = min(new_ids, rebased.added)
    if added:
        say_summary(log, ADDED_IDS, number=added, path=registry.path)
    else:
        # Changed, but no new id: a stale key was released in the same pass
        # another claimed its id, an id was promoted to its lookup key (see
        # pitloom.id_registry._harvest._release_stale_keys_for_id), or an
        # entry's hash changed.
        say_summary(log, STALE_UPDATED, path=registry.path)

pitloom.id_registry.save_registry

save_registry(registry: IdRegistry) -> Rebase

Re-read registry's file, apply this object's changes again (:meth:~pitloom.id_registry.IdRegistry.rebase) and save the result when it differs from the file; a new file is saved as it is.

Raises:

Type Description
(OSError, ValueError)

the re-read or the write failed; the file is left as it was, unless its directory refuses a temporary file and the write in place fails part-way.

Source code in pitloom/id_registry/_persist.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def save_registry(registry: IdRegistry) -> Rebase:
    """Re-read *registry*'s file, apply this object's changes again
    (:meth:`~pitloom.id_registry.IdRegistry.rebase`) and save the result
    when it differs from the file; a new file is saved as it is.

    Raises:
        OSError, ValueError: the re-read or the write failed; the file is
            left as it was, unless its directory refuses a temporary file
            and the write in place fails part-way.
    """
    rebased = registry.rebase()
    if rebased.pending:
        registry.save()
    return rebased

pitloom.id_registry.registry_key_for_path

registry_key_for_path(
    registry: IdRegistry, path: Path
) -> str | None

path's software_File key in registry, as spelt: :func:~pitloom.id_registry.keys.path_key without the on-disk spelling step. None outside the root; "." for the root. Never raises.

Source code in pitloom/id_registry/resolve.py
160
161
162
163
164
165
def registry_key_for_path(registry: IdRegistry, path: Path) -> str | None:
    """*path*'s ``software_File`` key in *registry*, as spelt:
    :func:`~pitloom.id_registry.keys.path_key` without the on-disk
    spelling step. ``None`` outside the root; ``"."`` for the root. Never
    raises."""
    return path_key(registry, path)

pitloom.id_registry.type_id_prefix

type_id_prefix(type_name: str) -> str

Return the spdxId fragment prefix for a compact type name: the part after the first _ (software_File -> File), else the name.

Source code in pitloom/id_registry/_types.py
189
190
191
192
193
def type_id_prefix(type_name: str) -> str:
    """Return the spdxId fragment prefix for a compact type name: the part
    after the first ``_`` (``software_File`` -> ``File``), else the name."""
    _, _, rest = type_name.partition("_")
    return rest or type_name

pitloom.id_registry.RegistryEntry dataclass

RegistryEntry(spdx_id: str, sha256: str | None = None)

One registered element: its stable spdxId and, when known, the SHA-256 of its content (lowercase hex).

sha256 is None when there is no hash; "" is never a hash and is rejected, so "no hash" has one spelling.

pitloom.id_registry.DEFAULT_ID_REGISTRY_FILENAME module-attribute

DEFAULT_ID_REGISTRY_FILENAME = 'loom-id-registry.json'