wdl-doc 0.15.0

Documentation generator for Workflow Description Language (WDL) documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! HTML generation for WDL runnables (workflows and tasks).

pub mod task;
pub mod workflow;

use std::collections::BTreeSet;
use std::path::MAIN_SEPARATOR;
use std::path::Path;

use maud::Markup;
use maud::PreEscaped;
use maud::html;
use wdl_ast::AstToken;
use wdl_ast::Documented;
use wdl_ast::v1::Decl;
use wdl_ast::v1::InputSection;
use wdl_ast::v1::MetadataValue;
use wdl_ast::v1::OutputSection;

use crate::VersionBadge;
use crate::docs_tree::Header;
use crate::docs_tree::PageSections;
use crate::meta::DESCRIPTION_KEY;
use crate::meta::DefinitionMeta;
use crate::meta::MetaMap;
use crate::meta::MetaMapExt;
use crate::meta::MetaMapValueSource;
use crate::meta::doc_comments;
use crate::parameter::Group;
use crate::parameter::InputOutput;
use crate::parameter::Parameter;
use crate::parameter::render_non_required_parameters_table;

/// A runnable (workflow or task) in a WDL document.
pub(crate) trait Runnable: DefinitionMeta {
    /// Get the name of the runnable.
    fn name(&self) -> &str;

    /// Get the inputs of the runnable.
    fn inputs(&self) -> &[Parameter];

    /// Get the outputs of the runnable.
    fn outputs(&self) -> &[Parameter];

    /// Get the [`VersionBadge`] of the runnable.
    fn version(&self) -> &VersionBadge;

    /// Get the path from the root of the WDL workspace to the WDL document
    /// which contains this runnable.
    fn wdl_path(&self) -> Option<&Path>;

    /// Get the required input parameters of the runnable.
    fn required_inputs(&self) -> impl Iterator<Item = &Parameter> {
        self.inputs().iter().filter(|param| {
            param
                .required()
                .expect("inputs should return Some(required)")
        })
    }

    /// Get the sorted set of unique `group` values of the inputs.
    ///
    /// The `Common` group, if present, will always be first in the set,
    /// followed by any other groups in alphabetical order, and lastly
    /// the `Resources` group.
    fn input_groups(&self) -> BTreeSet<Group> {
        self.inputs()
            .iter()
            .filter_map(|param| param.group())
            .map(|arg0: Group| Group(arg0.0.clone()))
            .collect()
    }

    /// Get the inputs of the runnable that are part of `group`.
    fn inputs_in_group<'a>(&'a self, group: &'a Group) -> impl Iterator<Item = &'a Parameter> {
        self.inputs().iter().filter(move |param| {
            if let Some(param_group) = param.group()
                && param_group == *group
            {
                return true;
            }
            false
        })
    }

    /// Get the inputs of the runnable that are neither required nor part of a
    /// group.
    fn other_inputs(&self) -> impl Iterator<Item = &Parameter> {
        self.inputs().iter().filter(|param| {
            !param
                .required()
                .expect("inputs should return Some(required)")
                && param.group().is_none()
        })
    }

    /// Render the version of the runnable as a badge.
    fn render_version(&self) -> Markup {
        self.version().render()
    }

    /// Render the "run with" component of the runnable.
    fn render_run_with(&self, _assets: &Path) -> Markup {
        if let Some(wdl_path) = self.wdl_path() {
            let unix_path = wdl_path.to_string_lossy().replace(MAIN_SEPARATOR, "/");
            let windows_path = wdl_path.to_string_lossy().replace(MAIN_SEPARATOR, "\\");
            html! {
                div x-data="{ run_with: (localStorage.getItem('run_with') ?? 'unix') }" class="main__run-with-container" data-pagefind-ignore="all" {
                    div class="main__run-with-label" {
                        span class="main__run-with-label-text" {
                            "RUN WITH"
                        }
                        button x-on:click="
                        run_with = run_with == 'unix' ? 'windows' : 'unix'
                        localStorage.setItem('run_with', run_with)
                        "
                        class="main__run-with-toggle" {
                            div x-bind:class="run_with == 'unix' ? 'main__run-with-toggle-label--active' : 'main__run-with-toggle-label--inactive'" {
                                "Unix"
                            }
                            div x-bind:class="run_with == 'windows' ? 'main__run-with-toggle-label--active' : 'main__run-with-toggle-label--inactive'" {
                                "Windows"
                            }
                        }
                    }
                    div class="main__run-with-content" {
                        p class="main__run-with-content-text" {
                            "sprocket run --target "
                            (self.name())
                            " "
                            span x-show="run_with == 'unix'" {
                                (unix_path)
                            }
                            span x-show="run_with == 'windows'" {
                                (windows_path)
                            }
                            " [INPUTS]..."
                        }
                    }
                }
            }
        } else {
            html! {}
        }
    }

    /// Render the required inputs of the runnable if present.
    fn render_required_inputs(&self, assets: &Path) -> Option<Markup> {
        let mut iter = self.required_inputs().peekable();
        iter.peek()?;

        let rows = iter
            .map(|param| param.render(assets).into_string())
            .collect::<Vec<_>>()
            .join(&html! { div class="main__grid-row-separator" {} }.into_string());

        Some(html! {
            h3 id="required-inputs" class="main__section-subheader" { "Required Inputs" }
            div class="main__grid-container" {
                div class="main__grid-req-inputs-container" {
                    div class="main__grid-header-cell" { "Name" }
                    div class="main__grid-header-cell" { "Type" }
                    div class="main__grid-header-cell" { "Description" }
                    div class="main__grid-header-separator" {}
                    (PreEscaped(rows))
                }
            }
        })
    }

    /// Render the inputs with a group of the runnable if present.
    ///
    /// This will render each group with a subheader and a table
    /// of parameters that are part of that group.
    fn render_group_inputs(&self, assets: &Path) -> Option<Markup> {
        let mut group_tables = self
            .input_groups()
            .into_iter()
            .map(|group| {
                html! {
                    h3 id=(group.id()) class="main__section-subheader" { (group.display_name()) }
                    (render_non_required_parameters_table(self.inputs_in_group(&group), assets))
                }
            })
            .peekable();
        group_tables.peek()?;

        Some(html! {
            @for group_table in group_tables {
                (group_table)
            }
        })
    }

    /// Render the inputs that are neither required nor part of a group if
    /// present.
    fn render_other_inputs(&self, assets: &Path) -> Option<Markup> {
        let mut iter = self.other_inputs().peekable();
        iter.peek()?;

        Some(html! {
            h3 id="other-inputs" class="main__section-subheader" { "Other Inputs" }
            (render_non_required_parameters_table(iter, assets))
        })
    }

    /// Render the inputs of the runnable.
    fn render_inputs(&self, assets: &Path) -> (Markup, PageSections) {
        let mut inner_markup = Vec::new();
        let mut headers = PageSections::default();
        headers.push(Header::Header("Inputs".to_string(), "inputs".to_string()));
        if let Some(req) = self.render_required_inputs(assets) {
            inner_markup.push(req);
            headers.push(Header::SubHeader(
                "Required Inputs".to_string(),
                "required-inputs".to_string(),
            ));
        }
        if let Some(group) = self.render_group_inputs(assets) {
            inner_markup.push(group);
            for group in self.input_groups() {
                headers.push(Header::SubHeader(
                    group.display_name().to_string(),
                    group.id(),
                ));
            }
        }
        if let Some(other) = self.render_other_inputs(assets) {
            inner_markup.push(other);
            headers.push(Header::SubHeader(
                "Other Inputs".to_string(),
                "other-inputs".to_string(),
            ));
        }
        let markup = html! {
            div class="main__section" {
                h2 id="inputs" class="main__section-header" { "Inputs" }
                @for section in inner_markup {
                    (section)
                }
            }
        };

        (markup, headers)
    }

    /// Render the outputs of the runnable.
    fn render_outputs(&self, assets: &Path) -> Markup {
        html! {
            div class="main__section" {
                h2 id="outputs" class="main__section-header" { "Outputs" }
                (render_non_required_parameters_table(self.outputs().iter(), assets))
            }
        }
    }
}

/// Attempts to convert a [`MetaMapValueSource`] to a [`MetaMap`] with a
/// description.
fn meta_to_description(value: &MetaMapValueSource) -> Option<MetaMap> {
    match value {
        MetaMapValueSource::Comment(_) => Some(MetaMap::from([(
            DESCRIPTION_KEY.to_string(),
            value.clone(),
        )])),
        MetaMapValueSource::MetaValue(meta) => match meta {
            MetadataValue::Object(o) => Some(
                o.items()
                    .map(|item| {
                        (
                            item.name().text().to_string(),
                            MetaMapValueSource::MetaValue(item.value().clone()),
                        )
                    })
                    .collect(),
            ),
            MetadataValue::String(_s) => Some(MetaMap::from([(
                DESCRIPTION_KEY.to_string(),
                value.clone(),
            )])),
            _ => {
                // If it's not an object or string, we don't know how to handle it.
                None
            }
        },
    }
}

/// Parse the [`InputSection`] into a vector of [`Parameter`]s.
fn parse_inputs(
    input_section: &InputSection,
    parameter_meta: &MetaMap,
    enable_doc_comments: bool,
) -> Vec<Parameter> {
    input_section
        .declarations()
        .map(|decl| {
            let name = decl.name().text().to_owned();
            let mut meta = parameter_meta
                .get(&name)
                .and_then(meta_to_description)
                .unwrap_or_default();

            if enable_doc_comments {
                let comments = match &decl {
                    Decl::Bound(decl) => decl.doc_comments(),
                    Decl::Unbound(decl) => decl.doc_comments(),
                };

                if let Some(comments) = comments {
                    // Doc comments take precedence
                    meta.append(&mut doc_comments(comments));
                }
            }

            Parameter::new(decl.clone(), meta, InputOutput::Input)
        })
        .collect()
}

/// Parse the [`OutputSection`] into a vector of [`Parameter`]s.
fn parse_outputs(
    output_section: &OutputSection,
    meta: &MetaMap,
    parameter_meta: &MetaMap,
    enable_doc_comments: bool,
) -> Vec<Parameter> {
    let output_meta: MetaMap = meta
        .get("outputs")
        .and_then(|v| match v {
            MetaMapValueSource::MetaValue(MetadataValue::Object(o)) => Some(o),
            _ => None,
        })
        .map(|o| {
            o.items()
                .map(|i| {
                    (
                        i.name().text().to_owned(),
                        MetaMapValueSource::MetaValue(i.value().clone()),
                    )
                })
                .collect()
        })
        .unwrap_or_default();

    output_section
        .declarations()
        .map(|decl| {
            let name = decl.name().text().to_owned();
            let mut meta = parameter_meta
                .get(&name)
                .or_else(|| output_meta.get(&name))
                .and_then(meta_to_description)
                .unwrap_or_default();

            if enable_doc_comments && let Some(comments) = decl.doc_comments() {
                // Doc comments take precedence
                meta.append(&mut doc_comments(comments));
            }

            Parameter::new(
                wdl_ast::v1::Decl::Bound(decl.clone()),
                meta,
                InputOutput::Output,
            )
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use wdl_ast::Document;

    use super::*;
    use crate::meta::DEFAULT_DESCRIPTION;
    use crate::meta::parse_metadata_items;
    use crate::parameter::Group;

    #[test]
    fn test_group_cmp() {
        let common = Group("Common".to_string());
        let resources = Group("Resources".to_string());
        let a = Group("A".to_string());
        let b = Group("B".to_string());
        let c = Group("C".to_string());

        let mut groups = vec![c, a, resources, common, b];
        groups.sort();
        assert_eq!(
            groups,
            vec![
                Group("Common".to_string()),
                Group("A".to_string()),
                Group("B".to_string()),
                Group("C".to_string()),
                Group("Resources".to_string()),
            ]
        );
    }

    #[test]
    fn test_parse_meta() {
        let wdl = r#"
        version 1.1

        workflow wf {
            meta {
                name: "Workflow"
                description: "A workflow"
            }
        }
        "#;

        let (doc, _) = Document::parse(wdl, None);
        let doc_item = doc.ast().into_v1().unwrap().items().next().unwrap();
        let meta_map = parse_metadata_items(
            doc_item
                .as_workflow_definition()
                .unwrap()
                .metadata()
                .unwrap()
                .items(),
        );
        assert_eq!(meta_map.len(), 2);
        assert_eq!(
            meta_map
                .get("name")
                .unwrap()
                .clone()
                .into_meta()
                .unwrap()
                .unwrap_string()
                .text()
                .unwrap()
                .text(),
            "Workflow"
        );
        assert_eq!(
            meta_map
                .get("description")
                .unwrap()
                .clone()
                .into_meta()
                .unwrap()
                .unwrap_string()
                .text()
                .unwrap()
                .text(),
            "A workflow"
        );
    }

    #[test]
    fn test_parse_parameter_meta() {
        let wdl = r#"
        version 1.1

        workflow wf {
            input {
                Int a
            }
            parameter_meta {
                a: {
                    description: "An integer"
                }
            }
        }
        "#;

        let (doc, _) = Document::parse(wdl, None);
        let doc_item = doc.ast().into_v1().unwrap().items().next().unwrap();
        let meta_map = parse_metadata_items(
            doc_item
                .as_workflow_definition()
                .unwrap()
                .parameter_metadata()
                .unwrap()
                .items(),
        );
        assert_eq!(meta_map.len(), 1);
        assert_eq!(
            meta_map
                .get("a")
                .unwrap()
                .clone()
                .into_meta()
                .unwrap()
                .unwrap_object()
                .items()
                .next()
                .unwrap()
                .value()
                .clone()
                .unwrap_string()
                .text()
                .unwrap()
                .text(),
            "An integer"
        );
    }

    #[test]
    fn test_parse_inputs() {
        let wdl = r#"
        version 1.1

        workflow wf {
            input {
                Int a
                Int b
                Int c
            }
            parameter_meta {
                a: "An integer"
                c: {
                    description: "Another integer"
                }
            }
        }
        "#;

        let (doc, _) = Document::parse(wdl, None);
        let doc_item = doc.ast().into_v1().unwrap().items().next().unwrap();
        let meta_map = parse_metadata_items(
            doc_item
                .as_workflow_definition()
                .unwrap()
                .parameter_metadata()
                .unwrap()
                .items(),
        );
        let inputs = parse_inputs(
            &doc_item.as_workflow_definition().unwrap().input().unwrap(),
            &meta_map,
            false,
        );
        assert_eq!(inputs.len(), 3);
        assert_eq!(inputs[0].name(), "a");
        assert_eq!(
            inputs[0].render_description(false).into_string(),
            "An integer"
        );
        assert_eq!(inputs[1].name(), "b");
        assert_eq!(
            inputs[1].render_description(false).into_string(),
            DEFAULT_DESCRIPTION
        );
        assert_eq!(inputs[2].name(), "c");
        assert_eq!(
            inputs[2].render_description(false).into_string(),
            "Another integer"
        );
    }

    #[test]
    fn test_parse_outputs() {
        let wdl = r#"
        version 1.1

        workflow wf {
            output {
                Int a = 1
                Int b = 2
                Int c = 3
            }
            meta {
                outputs: {
                    a: "An integer"
                    c: {
                        description: "Another integer"
                    }
                }
            }
            parameter_meta {
                b: "A different place!"
            }
        }
        "#;

        let (doc, _) = Document::parse(wdl, None);
        let doc_item = doc.ast().into_v1().unwrap().items().next().unwrap();
        let meta_map = parse_metadata_items(
            doc_item
                .as_workflow_definition()
                .unwrap()
                .metadata()
                .unwrap()
                .items(),
        );
        let parameter_meta = parse_metadata_items(
            doc_item
                .as_workflow_definition()
                .unwrap()
                .parameter_metadata()
                .unwrap()
                .items(),
        );
        let outputs = parse_outputs(
            &doc_item.as_workflow_definition().unwrap().output().unwrap(),
            &meta_map,
            &parameter_meta,
            false,
        );
        assert_eq!(outputs.len(), 3);
        assert_eq!(outputs[0].name(), "a");
        assert_eq!(
            outputs[0].render_description(false).into_string(),
            "An integer"
        );
        assert_eq!(outputs[1].name(), "b");
        assert_eq!(
            outputs[1].render_description(false).into_string(),
            "A different place!"
        );
        assert_eq!(outputs[2].name(), "c");
        assert_eq!(
            outputs[2].render_description(false).into_string(),
            "Another integer"
        );
    }
}