deepwoken 0.2.59

A library for interacting with Deepwoken data in a more convenient format, with a few added utilities.
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
use crate::Stat;
use crate::error::{DeepError, Result};
use crate::model::opt::OptionalGroup;
use crate::model::req::{Requirement, Timing};
use crate::model::reqfile::Reqfile;
use crate::model::stat::StatRange;
use crate::util::reqtree::ReqTree;
use crate::util::traits::ReqVecExt;
use std::collections::{HashMap, HashSet};
use std::ops::RangeInclusive;
use std::path::Path;
use winnow::ascii::{digit1, multispace0};
use winnow::combinator::{alt, eof, separated};
use winnow::prelude::*;

use super::req::{identifier, requirement, stat};

enum BaseReqfileLine {
    Requirement(Requirement),
    DependencyWithIdentifier {
        prereqs: Vec<String>,
        dependent: String,
    },
}

/// A full reqfile line.
/// Note a required requirement cannot have optional prereqs.
enum ReqfileLine {
    /// The regular requirement line.
    Unspecified(BaseReqfileLine),
    /// A line with the prefix '+', that forces it and its dependents to all be required.
    /// Used to force a prereq of an optional req to be required.
    ForceRequired(BaseReqfileLine),
    /// A line with the prefix 'n ;', where n is an integer from 0-5. Marks the req as optional
    /// and assigns n as the weight. Recursively marks all prereqs as optional and ties their obtainment
    /// to each other.  
    Optional { base: BaseReqfileLine, weight: i64 },
    /// A line of the form 'n <= STAT <= m'
    /// Used to specify a range of stats for the final stat stage (OINLY FINAL SUPPORTED FOR NOW,
    /// maybe preshrine soon)
    RangeSpecifier {
        stat: Stat,
        range: RangeInclusive<u32>,
    },
}

impl ReqfileLine {
    pub fn base(&self) -> Option<&BaseReqfileLine> {
        match self {
            ReqfileLine::Unspecified(base)
            | ReqfileLine::ForceRequired(base)
            | ReqfileLine::Optional { base, .. } => Some(base),
            ReqfileLine::RangeSpecifier { .. } => None,
        }
    }

    pub fn base_mut(&mut self) -> Option<&mut BaseReqfileLine> {
        match self {
            ReqfileLine::Unspecified(base)
            | ReqfileLine::ForceRequired(base)
            | ReqfileLine::Optional { base, .. } => Some(base),
            ReqfileLine::RangeSpecifier { .. } => None,
        }
    }

    pub fn is_explicit_optional(&self) -> bool {
        matches!(self, ReqfileLine::Optional { .. })
    }
}

fn parse_reqfile_line(input: &str) -> std::result::Result<ReqfileLine, String> {
    let input = input.trim();
    reqfile_line
        .parse(input)
        .map_err(|e| format!("Parse error: {e}"))
}

fn reqfile_line(input: &mut &str) -> ModalResult<ReqfileLine> {
    let _ = multispace0.parse_next(input)?;
    alt((
        optional_line,
        force_required_line,
        range_specifier,
        base_reqfile_line.map(ReqfileLine::Unspecified),
    ))
    .parse_next(input)
}

// optional_line = weight ';' base_reqfile_line
fn optional_line(input: &mut &str) -> ModalResult<ReqfileLine> {
    let weight = digit1
        .try_map(|s: &str| s.parse::<i64>())
        .verify(|&n| (1..=20).contains(&n))
        .parse_next(input)?;

    let _ = (multispace0, ';', multispace0).parse_next(input)?;
    let base = base_reqfile_line.parse_next(input)?;
    Ok(ReqfileLine::Optional { base, weight })
}

// force_reqfile_line = '+' base_reqfile_line
fn force_required_line(input: &mut &str) -> ModalResult<ReqfileLine> {
    let _ = ('+', multispace0).parse_next(input)?;
    let base = base_reqfile_line.parse_next(input)?;
    Ok(ReqfileLine::ForceRequired(base))
}

// range_specifier = number "<=" stat "<=" number eof
fn range_specifier(input: &mut &str) -> ModalResult<ReqfileLine> {
    let lower = range_bound.parse_next(input)?;

    let _ = multispace0.parse_next(input)?;
    let _ = "<=".parse_next(input)?;
    let _ = multispace0.parse_next(input)?;

    let s = stat.parse_next(input)?;

    let _ = multispace0.parse_next(input)?;
    let _ = "<=".parse_next(input)?;
    let _ = multispace0.parse_next(input)?;

    let upper = range_bound.parse_next(input)?;

    let _ = multispace0.parse_next(input)?;
    eof.parse_next(input)?;

    Ok(ReqfileLine::RangeSpecifier {
        stat: s,
        range: lower..=upper,
    })
}

fn range_bound(input: &mut &str) -> ModalResult<u32> {
    digit1.try_map(|s: &str| s.parse::<u32>()).parse_next(input)
}

// base_reqfile_line = dependency_with_identifier | requirement
fn base_reqfile_line(input: &mut &str) -> ModalResult<BaseReqfileLine> {
    let _ = multispace0.parse_next(input)?;

    alt((
        dependency_with_identifier,
        requirement.map(BaseReqfileLine::Requirement),
    ))
    .parse_next(input)
}

// dependency_with_identifier = identifier (',' identifier)* '=>' identifier eof
// links prereqs to an existing named requirement (no inline definition)
fn dependency_with_identifier(input: &mut &str) -> ModalResult<BaseReqfileLine> {
    let prereqs: Vec<String> =
        separated(1.., identifier, (multispace0, ',', multispace0)).parse_next(input)?;

    let _ = multispace0.parse_next(input)?;
    let _ = "=>".parse_next(input)?;
    let _ = multispace0.parse_next(input)?;

    let dependent = identifier.parse_next(input)?;

    let _ = multispace0.parse_next(input)?;
    eof.parse_next(input)?;

    Ok(BaseReqfileLine::DependencyWithIdentifier { prereqs, dependent })
}

struct ParsedLine {
    rf_line: ReqfileLine,
    line_num: usize,
    timing: Timing,
}

struct ReqfileIndex {
    named: HashMap<String, usize>,
    str_to_idx: HashMap<String, usize>,
    dependency_statements: Vec<(Vec<String>, String, u64)>,
}

fn build_index(lines: &[ParsedLine]) -> Result<ReqfileIndex> {
    let mut named: HashMap<String, usize> = HashMap::new();
    let mut dependency_statements: Vec<(Vec<String>, String, u64)> = vec![];

    let str_to_idx: HashMap<String, usize> = lines
        .iter()
        .enumerate()
        .filter_map(|(i, l)| match l.rf_line.base() {
            Some(BaseReqfileLine::Requirement(req)) => Some((req.name_or_default(), i)),
            _ => None,
        })
        .collect();

    for (vec_idx, line) in lines.iter().enumerate() {
        let Some(base) = line.rf_line.base() else {
            continue;
        };

        match base {
            BaseReqfileLine::DependencyWithIdentifier { prereqs, dependent } => {
                // TODO! DependencyWithId should actually be a top level enum variant.
                // since its not affected by required, forced, unmarked semantics
                // so yea for now we error if the user misuses the api (FOR NOW)
                if let ReqfileLine::Unspecified(_) = &line.rf_line {
                } else {
                    return Err(DeepError::Reqfile {
                        line: line.line_num,
                        message: "Optional annotations '+' or ';' must be used \
                        at the requirement definition, not in a dependency statement, unless \
                        the definition is in the dependency statement itself."
                            .into(),
                    });
                }

                dependency_statements.push((
                    prereqs.clone(),
                    dependent.clone(),
                    line.line_num as u64,
                ));
            }
            BaseReqfileLine::Requirement(req) => {
                if let Some(name) = &req.name
                    && named.insert(name.clone(), vec_idx).is_some()
                {
                    return Err(DeepError::Reqfile {
                        line: line.line_num + 1,
                        message: format!("Duplicate identifier: {name}"),
                    });
                }
            }
        }
    }

    Ok(ReqfileIndex {
        named,
        str_to_idx,
        dependency_statements,
    })
}

fn validate_no_ambiguous_anonymous(lines: &[ParsedLine]) -> Result<()> {
    for line in lines {
        if let Some(BaseReqfileLine::Requirement(req)) = line.rf_line.base() {
            // only lf anon reqs
            if req.name.is_some() {
                continue;
            }

            let other_anon = lines
                .iter()
                .filter_map(|line| line.rf_line.base())
                .find(|other| {
                    if let BaseReqfileLine::Requirement(other_req) = other {
                        other_req.name.is_none()
                    && other_req.name_or_default() == req.name_or_default()
                    // if any one of them has prereqs, we want to raise this err
                    && (!other_req.prereqs.is_empty() || !req.prereqs.is_empty())
                    && other_req != req
                    } else {
                        false
                    }
                });

            if other_anon.is_some() {
                return Err(DeepError::Reqfile {
                    line: line.line_num,
                    message: format!(
                        "You may not have duplicate anonymous requirements if either of them have prerequisites: {}",
                        req.name_or_default()
                    ),
                });
            }
        }
    }

    Ok(())
}

fn resolve_dependencies(lines: &mut [ParsedLine], index: &ReqfileIndex) -> Result<()> {
    #[allow(
        clippy::cast_possible_truncation,
        reason = "line numbers will never get to u32 big"
    )]
    for (prereqs, name, line_num) in &index.dependency_statements {
        match index.named.get(name) {
            Some(vec_idx) => {
                // prereqs that don't resolve to an in-file req aren't a parse error since they may be
                // implicit talents (resolved from game data), which parsing is deliberately unaware of. actual
                // missing prereq errors are caught at solve-time.
                let line = &mut lines[*vec_idx];

                if let Some(BaseReqfileLine::Requirement(req)) = line.rf_line.base_mut() {
                    if !req.prereqs.is_empty() {
                        return Err(DeepError::Reqfile {
                            line: *line_num as usize,
                            message: format!("'{name}' has multiple prerequisite assignments."),
                        });
                    }

                    req.prereqs = prereqs.iter().cloned().collect();
                }
            }
            None => {
                return Err(DeepError::Reqfile {
                    line: *line_num as usize,
                    message: format!("Dependent: no variable named '{name}'."),
                });
            }
        }
    }

    Ok(())
}

fn build_req_tree(lines: &[ParsedLine]) -> ReqTree {
    let mut tree = ReqTree::new();

    for line in lines {
        if let Some(BaseReqfileLine::Requirement(req)) = line.rf_line.base() {
            tree.insert(req.clone());
        }
    }

    tree
}

fn validate_tree(
    lines: &[ParsedLine],
    tree: &ReqTree,
    str_to_idx: &HashMap<String, usize>,
) -> Result<()> {
    if let Some(cycle) = tree.find_cycle() {
        return Err(DeepError::Reqfile {
            line: 0,
            message: format!(
                "Prereqs cannot be dependent on each other. Found cycle: {}",
                cycle.join(" => ")
            ),
        });
    }

    // a required req cannot have an optional prereq
    for line in lines {
        if let ReqfileLine::Optional { base, .. } = &line.rf_line
            && let BaseReqfileLine::Requirement(req) = base
            && let Some(name) = &req.name
        {
            for dependent in tree.all_dependents(name) {
                let vec_idx = str_to_idx[&dependent];
                let dependent_line = &lines[vec_idx];

                if !dependent_line.rf_line.is_explicit_optional() {
                    return Err(DeepError::Reqfile {
                        line: line.line_num,
                        message: format!(
                            "'{}' was declared as optional, however one of its \
                                    dependents are required: '{} at line {}'.\n\
                                    Try marking '{}' as optional instead.",
                            name, dependent, dependent_line.line_num, dependent
                        ),
                    });
                }
            }
        }
    }

    Ok(())
}

fn build_optional_groups(
    lines: &[ParsedLine],
    tree: &ReqTree,
    str_to_idx: &HashMap<String, usize>,
) -> (Vec<OptionalGroup>, HashSet<String>) {
    let mut optional: Vec<OptionalGroup> = vec![];
    let mut marked_opt: HashSet<String> = HashSet::new();

    for line in lines {
        if let ReqfileLine::Optional { base, weight } = &line.rf_line
            && let BaseReqfileLine::Requirement(req) = base
        {
            let mut group = OptionalGroup {
                general: HashSet::new(),
                post: HashSet::new(),
                weight: *weight,
            };

            for req in tree
                .all_prereqs(&req.name_or_default())
                .iter()
                .chain(&[req.name_or_default()])
            {
                let vec_idx = str_to_idx[req];
                let req_line = &lines[vec_idx];

                if let Some(BaseReqfileLine::Requirement(req)) = req_line.rf_line.base() {
                    group.get_set(req_line.timing).insert(req.clone());
                }

                marked_opt.insert(req.clone());
            }

            optional.push(group);
        }
    }

    (optional, marked_opt)
}

fn apply_force_required(
    lines: &[ParsedLine],
    tree: &ReqTree,
    str_to_idx: &HashMap<String, usize>,
    optional: &mut [OptionalGroup],
    marked_opt: &mut HashSet<String>,
) {
    for line in lines {
        if let ReqfileLine::ForceRequired(base) = &line.rf_line
            && let BaseReqfileLine::Requirement(req) = base
        {
            for req in tree
                .all_prereqs(&req.name_or_default())
                .iter()
                .chain(&[req.name_or_default()])
            {
                let vec_idx = str_to_idx[req];
                let req_line = &lines[vec_idx];

                if let Some(BaseReqfileLine::Requirement(req)) = req_line.rf_line.base() {
                    for group in optional.iter_mut() {
                        group.get_set(req_line.timing).remove(req);
                    }
                }

                marked_opt.remove(req);
            }
        }
    }
}

fn collect_required_reqs(
    lines: &[ParsedLine],
    marked_opt: &HashSet<String>,
) -> (Vec<Requirement>, Vec<Requirement>) {
    let mut general: Vec<Requirement> = vec![];
    let mut post: Vec<Requirement> = vec![];

    for line in lines {
        if let Some(BaseReqfileLine::Requirement(req)) = line.rf_line.base() {
            if marked_opt.contains(&req.name_or_default()) {
                continue;
            }

            match line.timing {
                Timing::Free => general.push(req.clone()),
                Timing::Post => post.push(req.clone()),
            }
        }
    }

    (general, post)
}

/// Collect the post-shrine stat ranges, validating that range directives only
/// appear in the Post stage and that each stat is constrained at most once per stage.
fn build_final_ranges(lines: &[ParsedLine]) -> Result<Vec<StatRange>> {
    let mut ranges: Vec<StatRange> = vec![];
    let mut seen: HashSet<Stat> = HashSet::new();

    for line in lines {
        if let ReqfileLine::RangeSpecifier { stat, range } = &line.rf_line {
            if !matches!(line.timing, Timing::Post) {
                return Err(DeepError::Reqfile {
                    line: line.line_num,
                    message: format!(
                        "Range directives are only allowed in the Post stage for now, \
                        but one was found not in Post: '{}'.",
                        stat.name()
                    ),
                });
            }

            if range.start() > range.end() {
                return Err(DeepError::Reqfile {
                    line: line.line_num,
                    message: format!(
                        "Range directive for '{}' is inverted. The lower bound must not \
                        exceed the upper bound.",
                        stat.name()
                    ),
                });
            }

            if !seen.insert(*stat) {
                return Err(DeepError::Reqfile {
                    line: line.line_num,
                    message: format!(
                        "'{}' already has a range directive in this stage.",
                        stat.name()
                    ),
                });
            }

            ranges.push(StatRange {
                stat: *stat,
                range: range.clone(),
            });
        }
    }

    Ok(ranges)
}

fn validate_and_transform(mut lines: Vec<ParsedLine>) -> Result<Reqfile> {
    let index = build_index(&lines)?;
    validate_no_ambiguous_anonymous(&lines)?;
    resolve_dependencies(&mut lines, &index)?;

    let tree = build_req_tree(&lines);
    validate_tree(&lines, &tree, &index.str_to_idx)?;

    let (mut optional, mut marked_opt) = build_optional_groups(&lines, &tree, &index.str_to_idx);
    apply_force_required(
        &lines,
        &tree,
        &index.str_to_idx,
        &mut optional,
        &mut marked_opt,
    );

    let (general, post) = collect_required_reqs(&lines, &marked_opt);
    let final_ranges = build_final_ranges(&lines)?;

    Ok(Reqfile {
        general,
        post,
        final_ranges,
        optional,
        implicit: HashMap::new(),
    })
}

// TODO! this should really be the only entry point to create a Reqfile,
// since it also validates if the payload will be semantically correct
pub(crate) fn parse_reqfile_str(content: &str) -> Result<Reqfile> {
    let mut lines: Vec<ParsedLine> = vec![];

    let mut current = Timing::Free;

    for (i, line) in content.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') || line.starts_with("//") {
            continue;
        }

        if line.to_uppercase().starts_with("FREE") {
            current = Timing::Free;
            continue;
        }

        if line.to_uppercase().starts_with("POST") {
            current = Timing::Post;
            continue;
        }

        let parsed = parse_reqfile_line(line).map_err(|e| DeepError::Reqfile {
            line: i + 1,
            message: e,
        })?;

        lines.push(ParsedLine {
            rf_line: parsed,
            line_num: i,
            timing: current,
        });
    }

    validate_and_transform(lines)
}

/// Parse '.req' files into a Reqfile struct
pub(crate) fn parse_reqfile(path: &Path) -> Result<Reqfile> {
    use std::fs;

    let content = fs::read_to_string(path)?;

    parse_reqfile_str(&content)
}

/// Generate a reqfile string from a Reqfile struct.
pub(crate) fn gen_reqfile(payload: &Reqfile) -> String {
    use std::fmt::Write as _;

    let mut output = String::new();

    output.push_str("# Auto-generated reqfile\n\n");

    // remove spaces from names
    //
    // we also give anonymous reqs with prereqs an identifier
    // (we don't assign names to potentially unnammed prereqs bc
    // it is a requirement that prereqs are already named)

    let clean_name = |name: &str| {
        name.replace(' ', "_")
            .replace(['[', ']', '\'', ':', '(', ')'], "")
    };

    let mut i = 0;

    let mut name_anon = |req: &Requirement| {
        i += 1;

        let mut req = req.clone();

        req.name = req.name.clone().or_else(|| {
            if req.prereqs.is_empty() {
                None
            } else {
                Some(format!("id_{i}"))
            }
        });

        req
    };

    let mut general = payload.general.iter().map(&mut name_anon).collect::<Vec<_>>();
    let mut post = payload.post.iter().map(&mut name_anon).collect::<Vec<_>>();

    let mut root_weights: HashMap<String, i64> = HashMap::new();

    for group in &payload.optional {
        let members: Vec<&Requirement> = group.general.iter().chain(group.post.iter()).collect();

        let referenced: HashSet<&String> =
            members.iter().flat_map(|r| r.prereqs.iter()).collect();

        for req in members {
            if req.name.as_ref().is_none_or(|n| !referenced.contains(n)) {
                root_weights
                    .entry(req.name_or_default())
                    .or_insert(group.weight.clamp(1, 20));
            }
        }
    }

    let mut opt_general: Vec<(Requirement, Option<i64>)> = vec![];
    let mut opt_post: Vec<(Requirement, Option<i64>)> = vec![];
    let mut seen: HashSet<String> = HashSet::new();
    let mut opt_prereq_refs: HashSet<String> = HashSet::new();

    for group in &payload.optional {
        let members = group
            .general
            .iter()
            .map(|r| (r, Timing::Free))
            .chain(group.post.iter().map(|r| (r, Timing::Post)));

        for (req, timing) in members {
            opt_prereq_refs.extend(req.prereqs.iter().cloned());

            let key = req.name_or_default();
            if !seen.insert(key.clone()) {
                continue;
            }

            let line = (name_anon(req), root_weights.get(&key).copied());
            match timing {
                Timing::Free => opt_general.push(line),
                Timing::Post => opt_post.push(line),
            }
        }
    }

    let is_forced =
        |req: &Requirement| req.name.as_ref().is_some_and(|n| opt_prereq_refs.contains(n));
    let general_forced = general.iter().map(is_forced).collect::<Vec<_>>();
    let post_forced = post.iter().map(is_forced).collect::<Vec<_>>();

    general.map_names(clean_name);
    post.map_names(clean_name);

    for (req, _) in opt_general.iter_mut().chain(opt_post.iter_mut()) {
        req.name = req.name.take().map(|n| clean_name(&n));
        req.prereqs = req.prereqs.iter().map(|n| clean_name(n)).collect();
    }

    output.push_str("# USER REQS\n\n");
    output.push_str("Free:\n");

    for (req, forced) in general.iter().zip(&general_forced) {
        let _ = writeln!(output, "{}{req}", if *forced { "+ " } else { "" });
    }

    if !post.is_empty() || !payload.final_ranges.is_empty() {
        output.push_str("\nPost:\n");

        for (req, forced) in post.iter().zip(&post_forced) {
            let _ = writeln!(output, "{}{req}", if *forced { "+ " } else { "" });
        }

        for r in &payload.final_ranges {
            let _ = writeln!(
                output,
                "{} <= {} <= {}",
                r.range.start(),
                r.stat.short_name(),
                r.range.end()
            );
        }
    }

    if !opt_general.is_empty() || !opt_post.is_empty() {
        output.push_str("\n# OPTIONAL PRESETS\n");

        if !opt_general.is_empty() {
            output.push_str("\nFree:\n");

            for (req, weight) in &opt_general {
                match weight {
                    Some(w) => {
                        let _ = writeln!(output, "{w}; {req}");
                    }
                    None => {
                        let _ = writeln!(output, "{req}");
                    }
                }
            }
        }

        if !opt_post.is_empty() {
            output.push_str("\nPost:\n");

            for (req, weight) in &opt_post {
                match weight {
                    Some(w) => {
                        let _ = writeln!(output, "{w}; {req}");
                    }
                    None => {
                        let _ = writeln!(output, "{req}");
                    }
                }
            }
        }
    }

    output
}