API reference

Load CWL documents from a location, string, stream, or parsed YAML mapping, and serialize the resulting processes back to YAML.

cwl_loader

Load, normalize, and serialize CWL documents while preserving metadata.

load_cwl_from_location(path: str, cwl_version: str = __TARGET_CWL_VERSION__, sort: bool = True, session: requests.Session = _global_session) -> Process | list[Process]

Load a CWL document from an HTTP(S) URL, local path, or local file URI.

Local file URIs may use an empty authority or localhost. Percent-encoded paths are decoded before opening; relative references use the file URI. As for other sources, URI fragments do not select a process: the complete document is loaded.

Parameters:
  • path (str) –

    HTTP(S) URL, local file path, or local file URI.

  • cwl_version (str, default: __TARGET_CWL_VERSION__ ) –

    Target CWL version. Defaults to v1.2.

  • sort (bool, default: True ) –

    Whether to order processes by their dependencies.

  • session (Session, default: _global_session ) –

    HTTP session used to retrieve remote documents.

Returns:
  • Process | list[Process] –

    The parsed process, or a list of processes for a multi-process document.

Source code in src/cwl_loader/__init__.py
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
def load_cwl_from_location(
    path: str,
    cwl_version: str = __TARGET_CWL_VERSION__,
    sort: bool = True,
    session: requests.Session = _global_session,
) -> Process | list[Process]:
    """Load a CWL document from an HTTP(S) URL, local path, or local file URI.

    Local file URIs may use an empty authority or localhost. Percent-encoded
    paths are decoded before opening; relative references use the file URI.
    As for other sources, URI fragments do not select a process: the complete
    document is loaded.

    Args:
        path: HTTP(S) URL, local file path, or local file URI.
        cwl_version: Target CWL version. Defaults to ``v1.2``.
        sort: Whether to order processes by their dependencies.
        session: HTTP session used to retrieve remote documents.

    Returns:
        The parsed process, or a list of processes for a multi-process document.
    """
    logger.debug(f"Loading CWL document from {path}...")

    document_uri = path
    source_path = _local_source_path(path, session)

    if source_path is not None:
        document_uri = source_path.resolve().as_uri()

    def _load_cwl_from_stream(stream: TextIO) -> Process | list[Process]:
        """Load a stream using the resolved source URI and requested options."""
        logger.debug(f"Reading stream from {path}...")

        loaded = load_cwl_from_stream(
            content=stream,
            uri=document_uri,
            cwl_version=cwl_version,
            sort=sort,
            session=session,
        )

        logger.debug(f"Stream from {path} successfully load!")

        return loaded

    if source_path is None:
        response = session.get(path, stream=True)
        response.raise_for_status()

        # Read first 2 bytes to check for gzip
        magic = response.raw.read(2)
        remaining = response.raw.read()  # Read rest of the stream
        combined = BytesIO(magic + remaining)

        buffer = GzipFile(fileobj=combined) if magic == b"\x1f\x8b" else combined

        return _load_cwl_from_stream(TextIOWrapper(buffer, encoding=__DEFAULT_ENCODING__))
    if source_path.is_file():
        with source_path.open(encoding=__DEFAULT_ENCODING__) as f:
            return _load_cwl_from_stream(f)
    else:
        raise ValueError(f"Invalid source {path}: not a URL or existing file path")

load_cwl_from_string_content(content: str, uri: str = __DEFAULT_BASE_URI__, cwl_version: str = __TARGET_CWL_VERSION__, sort: bool = True) -> Process | list[Process]

Load a CWL document from its textual representation.

Parameters:
  • content (str) –

    YAML text representing the CWL document.

  • uri (str, default: __DEFAULT_BASE_URI__ ) –

    Base URI used to resolve relative references. Defaults to io://.

  • cwl_version (str, default: __TARGET_CWL_VERSION__ ) –

    Target CWL version. Defaults to v1.2.

  • sort (bool, default: True ) –

    Whether to order processes by their dependencies.

Returns:
  • Process | list[Process] –

    The parsed process, or a list of processes for a multi-process document.

Source code in src/cwl_loader/__init__.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
def load_cwl_from_string_content(
    content: str,
    uri: str = __DEFAULT_BASE_URI__,
    cwl_version: str = __TARGET_CWL_VERSION__,
    sort: bool = True,
) -> Process | list[Process]:
    """Load a CWL document from its textual representation.

    Args:
        content: YAML text representing the CWL document.
        uri: Base URI used to resolve relative references. Defaults to ``io://``.
        cwl_version: Target CWL version. Defaults to ``v1.2``.
        sort: Whether to order processes by their dependencies.

    Returns:
        The parsed process, or a list of processes for a multi-process document.
    """
    return load_cwl_from_stream(
        content=StringIO(content), uri=uri, cwl_version=cwl_version, sort=sort
    )

load_cwl_from_stream(content: TextIO, uri: str = __DEFAULT_BASE_URI__, cwl_version: str = __TARGET_CWL_VERSION__, sort: bool = True, session: requests.Session = _global_session) -> Process | list[Process]

Load a CWL document from a stream of data.

Parameters:
  • content (TextIO) –

    Text stream containing the CWL document.

  • uri (str, default: __DEFAULT_BASE_URI__ ) –

    Base URI used to resolve relative references. Defaults to io://.

  • cwl_version (str, default: __TARGET_CWL_VERSION__ ) –

    Target CWL version. Defaults to v1.2.

  • sort (bool, default: True ) –

    Whether to order processes by their dependencies.

  • session (Session, default: _global_session ) –

    HTTP session used to retrieve remote documents.

Returns:
  • Process | list[Process] –

    The parsed process, or a list of processes for a multi-process document.

Source code in src/cwl_loader/__init__.py
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
def load_cwl_from_stream(
    content: TextIO,
    uri: str = __DEFAULT_BASE_URI__,
    cwl_version: str = __TARGET_CWL_VERSION__,
    sort: bool = True,
    session: requests.Session = _global_session,
) -> Process | list[Process]:
    """Load a CWL document from a stream of data.

    Args:
        content: Text stream containing the CWL document.
        uri: Base URI used to resolve relative references. Defaults to ``io://``.
        cwl_version: Target CWL version. Defaults to ``v1.2``.
        sort: Whether to order processes by their dependencies.
        session: HTTP session used to retrieve remote documents.

    Returns:
        The parsed process, or a list of processes for a multi-process document.
    """
    cwl_content = _yaml.load(content)

    logger.debug(f"CWL data of type {type(cwl_content)} successfully loaded from stream")

    return load_cwl_from_yaml(
        raw_process=cwl_content,
        uri=uri,
        cwl_version=cwl_version,
        sort=sort,
        session=session,
    )

load_cwl_from_yaml(raw_process: Mapping[str, Any] | CommentedMap, uri: str = __DEFAULT_BASE_URI__, cwl_version: str = __TARGET_CWL_VERSION__, sort: bool = True, session: requests.Session = _global_session) -> Process | list[Process]

Load a CWL document from a raw dictionary.

Parameters:
  • raw_process (Mapping[str, Any] | CommentedMap) –

    Mapping representing the CWL document.

  • uri (str, default: __DEFAULT_BASE_URI__ ) –

    Base URI used to resolve relative references. Defaults to io://.

  • cwl_version (str, default: __TARGET_CWL_VERSION__ ) –

    Target CWL version. Defaults to v1.2.

  • sort (bool, default: True ) –

    Whether to order processes by their dependencies.

  • session (Session, default: _global_session ) –

    HTTP session used to retrieve remote documents.

Returns:
  • Process | list[Process] –

    The parsed process, or a list of processes for a multi-process document.

Source code in src/cwl_loader/__init__.py
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
def load_cwl_from_yaml(
    raw_process: Mapping[str, Any] | CommentedMap,
    uri: str = __DEFAULT_BASE_URI__,
    cwl_version: str = __TARGET_CWL_VERSION__,
    sort: bool = True,
    session: requests.Session = _global_session,
) -> Process | list[Process]:
    """Load a CWL document from a raw dictionary.

    Args:
        raw_process: Mapping representing the CWL document.
        uri: Base URI used to resolve relative references. Defaults to ``io://``.
        cwl_version: Target CWL version. Defaults to ``v1.2``.
        sort: Whether to order processes by their dependencies.
        session: HTTP session used to retrieve remote documents.

    Returns:
        The parsed process, or a list of processes for a multi-process document.
    """
    updated_process = raw_process
    document_has_graph = __CWL_GRAPH__ in raw_process

    if cwl_version != raw_process[__CWL_VERSION__]:
        logger.debug(
            f"Updating the model from version '{raw_process[__CWL_VERSION__]}' to version '{cwl_version}'..."
        )

        updated_process = _upgrade_document(
            raw_process=raw_process,
            cwl_version=cwl_version,
            uri=uri,
        )

        logger.debug(f"Raw CWL document successfully updated to {cwl_version}!")
    else:
        logger.debug(
            f"No needs to update the Raw CWL document since it targets already the {cwl_version}"
        )

    logger.debug("Parsing the raw CWL document to the CWL Utils DOM...")

    clean_uri, fragment = urldefrag(uri)

    if fragment:
        logger.debug(f"Ignoring fragment #{fragment} from URI {clean_uri}")

    process = load_scoped_document(
        document=updated_process,
        uri=clean_uri,
        options=requirement_loading_options(cwl_version, clean_uri),
    )

    logger.debug("Raw CWL document successfully parsed to the CWL Utils DOM!")

    logger.debug("Dereferencing the steps[].run...")

    dereferenced_process = _dereference_steps(
        process=process,
        uri=uri,
        session=session,
        loader=load_cwl_from_location,
    )

    logger.debug("steps[].run successfully dereferenced! Dereferencing the FQNs...")

    remove_refs(dereferenced_process)

    logger.debug("CWL document successfully dereferenced! Now verifying steps[].run integrity...")

    assert_connected_graph(dereferenced_process)

    logger.debug("All steps[].run link are resolvable! ")

    if sort:
        logger.debug("Sorting Process instances by dependencies....")
        dereferenced_process = order_graph_by_dependencies(dereferenced_process)
        logger.debug("Sorting process is over.")

    document_metadata = _extract_document_metadata(raw_process, process=dereferenced_process)
    _preserve_document_metadata(
        process=dereferenced_process,
        document_metadata=document_metadata,
        document_has_graph=document_has_graph,
    )

    return dereferenced_process if len(dereferenced_process) > 1 else dereferenced_process[0]

dump_cwl(process: Process | list[Process], stream: TextIO) -> None

Write a CWL process or graph to a text stream as YAML.

Parameters:
  • process (Process | list[Process]) –

    Process or graph to serialize with preserved document metadata.

  • stream (TextIO) –

    Destination for the serialized document.

Source code in src/cwl_loader/__init__.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
def dump_cwl(process: Process | list[Process], stream: TextIO) -> None:
    """Write a CWL process or graph to a text stream as YAML.

    Args:
        process: Process or graph to serialize with preserved document metadata.
        stream: Destination for the serialized document.
    """
    data = save(
        val=process,  # type: ignore
        relative_uris=False,
    )
    data = _restore_document_metadata(data=data, process=process)
    normalize_serialized_document(data)

    _yaml.dump(data=data, stream=stream)