dfraw_json_parser 0.17.5

Library which parses Dwarf Fortress raw files into JSON
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
/*!
`dfraw_json_parser` provides a way to turn raw files from Dwarf Fortress into JSON. It's
currently useful for getting some basic information from from a limited set of raw types:

- creatures
- plants
- inorganics (rocks, ores, etc)
- materials
- syndromes
- graphics (sprites and tile pages, some layer support)
- limited template support, creature variations support, and select XX support

## How It Works

It functions using a regular expression to break apart the tokens and then checks the
key in the token against a long list of ones it knows about. Any matches are utilized to
build its own representation of the raw. Optionally you can turn this result into JSON using
the `serde_json` library. Or I guess turn it into anything serde supports.

## Tauri Support

This library was built to provide raw parsing for another project, Overseer's Reference Manual,
which creates a tauri app that lets the user look at the raws on their machine in a searchable
and filterable manner. The "tauri" feature flag enables functions which will emit parsing progress
back to the tauri window.

## Glossary of Terms

### Raw

A raw is a definition used by Dwarf Fortress to create creatures, things and objects in the world.
They can be used to also define how things interact. They are composed of a variety of tokens inside
a raw file, starting with an identifier token of `[#type#:#identifier#]`. Raws can also select and
modify other raws using a `[SELECT:#identifier#]` token.

### Raw File

A raw file is a single text file (with .txt extension) which has the first line as the raw file
identifier, and then defines the type of raw file using the `[OBJECT:#type#]` token. The file can
contain any number of raws of that type.

### Raw File Module, Raw Module

Since Dwarf Fortress 50, raws are organized into directories. (Previously they were in a flat
structure.) This was done to facilitate the steam workshop.

### Raw Module Location, Module Location

Raw file module folders are located in 3 locations that this library recognizes:

- `$df_game_dir/data/vanilla`: the vanilla raws are here
- `$df_game_dir/data/installed_mods`: the workshop mods which have been used in generating a world
are here. They are considered installed because they are in use by at least one world. (Note: these
are never removed even if you delete all worlds which use them.)
- `$df_game_dir/mods`: the workshop mods are stored here to be available when creating a world

### Info Text File

In each raw module, there is an `info.txt` file which contains information about that module, like
author, version, earliest compatible version (for updating in existing saves), and information
for the steam workshop if it is a mod downloaded from the steam workshop.

*/

#![warn(clippy::pedantic)]
#![allow(clippy::must_use_candidate)]

use parser::{
    creature::Creature, creature_variation::CreatureVariation, unprocessed_raw::UnprocessedRaw,
};
use std::path::{Path, PathBuf};
use tracing::{debug, error, info, warn};
use util::validate_options;
use walkdir::{DirEntry, WalkDir};

mod errors;
mod legends_export;
mod options;
/// The parser module contains the functions for parsing raws and info files.
pub mod parser;
mod traits;

/// The errors that may happen.
pub use errors::ParserError;

/// A parsing result that contains the parsed raws and info files.
#[derive(serde::Serialize, serde::Deserialize)]
pub struct ParseResult {
    /// The parsed raw objects.
    pub raws: Vec<Box<dyn RawObject>>,
    /// The parsed module info files.
    pub info_files: Vec<ModuleInfoFile>,
}

#[cfg(feature = "tauri")]
/// # Tauri Support
///
/// This has functions for interacting with the Tauri application.
///
/// This provides the same library functions but also allows for sending progress updates to the Tauri application.
///
/// The main functions:
///
/// - `parse`: Parses the raws in the provided location path, and returns a vector of boxed dynamic raw objects.
/// - `parse_to_json`: Parses the raws in the provided location path, and returns a vector of JSON strings.
mod tauri_lib;

/// This has utility functions for file operations and directory traversal.
///
/// The functions provide functionality for working with directories, files, and paths.
/// It includes functions for getting subdirectories of a given directory, retrieving the name of the parent directory,
/// validating game directories, writing raw objects and string vectors to files, and converting raw objects to JSON strings.
///
/// The main functions:
///
/// - `subdirectories`: Retrieves a vector of subdirectories for a given directory.
/// - `get_parent_dir_name`: Retrieves the name of the parent directory for a given path.
/// - `path_from_game_directory`: Validates and returns a `PathBuf` for a given game directory path.
/// - `write_raw_vec_to_file`: Writes a vector of raw objects to a file in JSON format.
/// - `write_json_string_vec_to_file`: Writes a vector of strings to a file, with each string on a separate line.
/// - `options_has_valid_paths`: Validates the paths in the `ParserOptions` struct.
/// - `raws_to_string`: Converts a vector of raw objects to a JSON string representation.
pub mod util;

/// Option struct for passing to any parse function.
pub use options::ParserOptions;
pub use parser::*;

#[cfg(feature = "tauri")]
pub use tauri_lib::ProgressDetails;
#[cfg(feature = "tauri")]
pub use tauri_lib::ProgressPayload;
#[cfg(feature = "tauri")]
pub use tauri_lib::ProgressTask;

use crate::{
    helpers::clone_raw_object_box,
    util::{log_summary, summarize_raws},
};

#[allow(clippy::too_many_lines)]
/// Given the supplied `ParserOptions`, parse the raws and return a vector of boxed dynamic raw objects.
///
/// Note: This is unable to parse the info.txt file for a module. Use `parse_module_info_file` for that.
///
/// # Arguments
///
/// * `options` - A reference to a `ParserOptions` struct that contains the parsing options.
///
/// # Returns
///
/// A vector of boxed dynamic raw objects.
///
/// # Errors
///
/// * `ParserError::Io` - If we can't read the raws from the Dwarf Fortress directory (various reasons)
/// * `ParserError::InvalidPath` - If the path to the Dwarf Fortress directory is invalid
///
/// Other errors which are returned from the called functions within this function are not propagated, because the
/// only "full" blocker is if the Dwarf Fortress directory is invalid.
///
#[allow(clippy::cognitive_complexity)]
pub fn parse(options: &ParserOptions) -> Result<ParseResult, ParserError> {
    // Guard against invalid paths
    let options = validate_options(options)?;

    let mut results = ParseResult {
        raws: Vec::new(),
        info_files: Vec::new(),
    };
    let mut unprocessed_raws: Vec<UnprocessedRaw> = Vec::new();

    // Locations can only contain the predefined locations.
    if !options.locations_to_parse.is_empty() {
        let target_path = Path::new(&options.dwarf_fortress_directory);

        // Build paths for each location
        let data_path = target_path.join("data");
        let vanilla_path = data_path.join("vanilla");
        let installed_mods_path = data_path.join("installed_mods");
        let workshop_mods_path = target_path.join("mods");

        // Parse each location
        if options
            .locations_to_parse
            .contains(&RawModuleLocation::Vanilla)
        {
            info!("Dispatching parse for vanilla raws");
            let parsed_raws = parse_location(&vanilla_path, &options)?;
            results.raws.extend(parsed_raws.parsed_raws);
            unprocessed_raws.extend(parsed_raws.unprocessed_raws);
        }
        if options
            .locations_to_parse
            .contains(&RawModuleLocation::InstalledMods)
        {
            info!("Dispatching parse for installed mods");
            let parsed_raws = parse_location(&installed_mods_path, &options)?;
            results.raws.extend(parsed_raws.parsed_raws);
            unprocessed_raws.extend(parsed_raws.unprocessed_raws);
        }
        if options
            .locations_to_parse
            .contains(&RawModuleLocation::Mods)
        {
            info!("Dispatching parse for workshop/downloaded mods");
            let parsed_raws = parse_location(&workshop_mods_path, &options)?;
            results.raws.extend(parsed_raws.parsed_raws);
            unprocessed_raws.extend(parsed_raws.unprocessed_raws);
        }
    }

    if !options.raw_modules_to_parse.is_empty() {
        // Loop through over module and parse it.
        for raw_module in &options.raw_modules_to_parse {
            let target_path = Path::new(&raw_module);

            // Check for info.txt
            let info_txt_path = target_path.join("info.txt");
            if info_txt_path.exists() {
                info!(
                    "Dispatching parse for module {:?}",
                    target_path.file_name().unwrap_or_default()
                );
                let parsed_raws = parse_module(&target_path, &options)?;
                results.raws.extend(parsed_raws.parsed_raws);
                unprocessed_raws.extend(parsed_raws.unprocessed_raws);
            }
        }
    }

    // Next we can check if any raw files are specified
    if !options.raw_files_to_parse.is_empty() {
        // Parse all raw files that are specified.
        for raw_file in &options.raw_files_to_parse {
            let target_path = Path::new(&raw_file);
            info!(
                "Dispatching parse for raw file {:?}",
                target_path.file_name().unwrap_or_default()
            );
            let parsed_raws = parser::parse_raw_file(&target_path, &options)?;
            results.raws.extend(parsed_raws.parsed_raws);
            unprocessed_raws.extend(parsed_raws.unprocessed_raws);
        }
    }

    // Finally we can check if any legends exports are specified
    if !options.legends_exports_to_parse.is_empty() {
        // Parse all legends exports that are specified.
        for legends_export in &options.legends_exports_to_parse {
            let target_path = Path::new(&legends_export);

            results
                .raws
                .extend(legends_export::parse(&target_path, &options)?);
        }
    }

    // Resolve the unprocessed creatures
    // Prerequisites: build a list of creature variations
    let creature_variations: Vec<CreatureVariation> = results
        .raws
        .iter()
        .filter_map(|raw| {
            if raw.get_type() == &ObjectType::CreatureVariation {
                if let Some(cv) = raw
                    .as_ref()
                    .as_any()
                    .downcast_ref::<CreatureVariation>()
                    .cloned()
                {
                    return Some(cv);
                }
                error!(
                    "Matched CreatureVariation but failed to downcast for {}",
                    raw.get_identifier()
                );
            }
            None
        })
        .collect();

    info!(
        "Resolving {} unprocessed creatures using {} creature variation definitions",
        unprocessed_raws.len(),
        creature_variations.len()
    );

    // Write the unprocessed raws to a file
    // let _ = serde_json::to_writer_pretty(
    //     std::fs::File::create("unprocessed_raws.json").unwrap(),
    //     &unprocessed_raws,
    // );

    let mut simple_unprocessed: Vec<UnprocessedRaw> = Vec::new();
    let mut complex_unprocessed: Vec<UnprocessedRaw> = Vec::new();

    // Split the unprocessed raws into simple and complex
    for unprocessed_raw in unprocessed_raws {
        if unprocessed_raw.is_simple() {
            simple_unprocessed.push(unprocessed_raw);
        } else {
            complex_unprocessed.push(unprocessed_raw);
        }
    }

    // Resolve the simple creatures first
    let resolved_simple_creatures: Vec<Creature> = simple_unprocessed
        .iter_mut()
        .filter(|raw| raw.raw_type() == ObjectType::Creature)
        .filter_map(|raw| {
            match raw.resolve(creature_variations.as_slice(), results.raws.as_slice()) {
                Ok(c) => Some(c),
                Err(e) => {
                    error!(
                        "Unable to resolve simple creature {}: {:?}",
                        raw.get_identifier(),
                        e
                    );
                    None
                }
            }
        })
        .map(|c| clone_raw_object_box(&c))
        .filter_map(|c| {
            c.as_ref().as_any().downcast_ref::<Creature>().map_or_else(
                || {
                    error!("Downcast failed for simple creature {}", c.get_identifier());
                    None
                },
                |creature| Some(creature.clone()),
            )
        })
        .collect();

    info!(
        "Resolved {} simple creatures",
        resolved_simple_creatures.len()
    );

    results.raws.extend(
        resolved_simple_creatures
            .iter()
            .map(|c| Box::new(c.clone()) as Box<dyn RawObject>),
    );

    // Now we can do the second pass through the unprocessed creatures, but add the complex creatures
    // to the results.raws vector as they are resolved.
    let mut resolved_complex_creatures = 0_usize;
    for unprocessed_raw in &mut complex_unprocessed {
        if unprocessed_raw.raw_type() == ObjectType::Creature {
            match unprocessed_raw.resolve(creature_variations.as_slice(), results.raws.as_slice()) {
                Ok(c) => {
                    resolved_complex_creatures += 1;
                    results.raws.push(clone_raw_object_box(&c));
                }
                Err(e) => {
                    error!(
                        "Unable to resolve complex creature {}: {:?}",
                        unprocessed_raw.get_identifier(),
                        e
                    );
                }
            }
        }
    }

    info!("Resolved {resolved_complex_creatures} complex creatures");

    // Parse the info modules
    results.info_files = parse_module_info_files(&options)?;

    // Print a summary of what we parsed (sum by ObjectType)
    if options.log_summary {
        let summary = summarize_raws(results.raws.as_slice());
        log_summary(&summary);
    }

    Ok(results)
}

/// The function `parse_module_info_files` parses module information files based on the provided options.
///
/// Arguments:
///
/// * `options`: A reference to a `ParserOptions` struct, which contains various options for parsing
/// module information.
///
/// Returns:
///
/// The function `parse_module_info_files` returns a `Vec<ModuleInfoFile>`.
fn parse_module_info_files(options: &ParserOptions) -> Result<Vec<ModuleInfoFile>, ParserError> {
    let mut results = Vec::new();

    if !options.locations_to_parse.is_empty() {
        let target_path = Path::new(&options.dwarf_fortress_directory);

        // Build paths for each location
        let data_path = target_path.join("data");
        let vanilla_path = data_path.join("vanilla");
        let installed_mods_path = data_path.join("installed_mods");
        let workshop_mods_path = target_path.join("mods");

        // Parse each location
        if options
            .locations_to_parse
            .contains(&RawModuleLocation::Vanilla)
        {
            results.extend(parse_module_info_files_at_location(&vanilla_path)?);
        }
        if options
            .locations_to_parse
            .contains(&RawModuleLocation::InstalledMods)
        {
            results.extend(parse_module_info_files_at_location(&installed_mods_path)?);
        }
        if options
            .locations_to_parse
            .contains(&RawModuleLocation::Mods)
        {
            results.extend(parse_module_info_files_at_location(&workshop_mods_path)?);
        }
    }

    // Parse any raw modules that are specified
    if !options.raw_modules_to_parse.is_empty() {
        // Parse all raw modules that are specified.
        for raw_module_path in options.raw_modules_to_parse.as_slice() {
            results.push(parse_module_info_file_in_module(raw_module_path)?);
        }
    }

    // Parse any module info files that are specified directly
    if !options.module_info_files_to_parse.is_empty() {
        // Parse all module info files that are specified.
        for module_info_file_path in options.module_info_files_to_parse.as_slice() {
            results.push(parse_module_info_file_direct(module_info_file_path)?);
        }
    }

    Ok(results)
}

/// Parse the `info.txt` file at the `module_path` provided. Returns a `ModuleInfoFile` if successful.
///
/// Arguments:
///
/// * `module_path`: A reference to a path that points to the module directory.
///
/// Returns:
///
/// A `ModuleInfoFile` or `ParserError`
///
/// ## Errors
///
/// * `ParserError::Io` - If the `info.txt` file cannot be read, doesn't exist, or is an invalid `info.txt` file
fn parse_module_info_file_in_module<P: AsRef<Path>>(
    module_path: &P,
) -> Result<ModuleInfoFile, ParserError> {
    let module_path: PathBuf = module_path.as_ref().to_path_buf();
    let module_info_file_path = module_path.join("info.txt");
    parse_module_info_file_direct(&module_info_file_path)
}

#[cfg(feature = "tauri")]
#[allow(clippy::too_many_lines)]
/// Parse a directory of raws, and return a JSON string of the parsed raws. While parsing, this will
/// emit tauri events to the supplied window. The event has title `PROGRESS` and uses the `ProgressPayload`
/// object for the payload.
///
/// Set the `options` appropriately for the job you want to perform.
///
/// The payload supplies the current progress as a float and the name of the current folder to parse.
///
/// Properties:
///
/// * `options`: The `ParserOptions` to use for parsing.
/// * `window`: A `tauri::Window` to emit `PROGRESS` events to.
///
/// Returns:
///
/// A JSON string with details on all raws in the game path.
///
/// # Errors
///
/// * `ParserError::Io` - If we can't read the raws from the Dwarf Fortress directory (various reasons)
/// * `ParserError::InvalidPath` - If the path to the Dwarf Fortress directory is invalid
///
/// Other errors which are returned from the called functions within this function are not propagated, because the
/// only "full" blocker is if the Dwarf Fortress directory is invalid.
pub fn parse_with_tauri_emit(
    options: &ParserOptions,
    window: tauri::Window,
) -> Result<ParseResult, ParserError> {
    let mut progress_helper = tauri_lib::ProgressHelper::with_tauri_window(window);
    tauri_lib::parse(options, &mut progress_helper)
}

/// Parses the raws in the provided location path, and returns a vector of boxed dynamic raw objects.
///
/// # Arguments
///
/// * `location_path` - A reference to the path to parse.
/// * `options` - A reference to a `ParserOptions` struct that contains the parsing options.
///
/// # Returns
///
/// A vector of boxed dynamic raw objects.
///
/// # Errors
///
/// * `ParserError::Io` - If we can't read the raws from the Dwarf Fortress directory (various reasons)
fn parse_location<P: AsRef<Path>>(
    location_path: &P,
    options: &ParserOptions,
) -> Result<FileParseResults, ParserError> {
    let mut results: Vec<Box<dyn RawObject>> = Vec::new();
    let mut unprocessed_raws: Vec<UnprocessedRaw> = Vec::new();

    let location_path: PathBuf = location_path.as_ref().to_path_buf();
    // Get a list of all subdirectories in the location
    let raw_modules_in_location: Vec<DirEntry> = util::subdirectories(location_path)?;

    info!(
        "Found {} raw modules in {:?}",
        raw_modules_in_location.len(),
        options
            .locations_to_parse
            .first()
            .unwrap_or(&RawModuleLocation::Unknown)
    );

    // Loop over each module and parse it
    for raw_module in raw_modules_in_location {
        match parse_module(&raw_module.path(), options) {
            Ok(module_results) => {
                results.extend(module_results.parsed_raws);
                unprocessed_raws.extend(module_results.unprocessed_raws);
            }
            Err(e) => {
                debug!("Skipping parsing module: {:?}", e);
            }
        }
    }

    Ok(FileParseResults {
        parsed_raws: results,
        unprocessed_raws,
    })
}

/// The function `parse_module_info_files_at_location` takes a location path as input, retrieves a list
/// of subdirectories at that location, and parses each subdirectory's "info.txt" file into a
/// `ModuleInfoFile` struct, returning a vector of these structs.
///
/// # Arguments:
///
/// * `location_path`: the path to the directory where the module info files are.
///
/// # Returns:
///
/// The function `parse_module_info_files_at_location` returns a vector of `ModuleInfoFile` objects.
///
/// # Errors
///
/// * `ParserError::Io` - If we can't read the `info.txt` file properly
fn parse_module_info_files_at_location<P: AsRef<Path>>(
    location_path: &P,
) -> Result<Vec<ModuleInfoFile>, ParserError> {
    let location_path: PathBuf = location_path.as_ref().to_path_buf();

    // Get a list of all subdirectories in the location
    let raw_modules_in_location: Vec<DirEntry> = util::subdirectories(location_path.clone())?;

    info!(
        "Found {} raw modules in {:?}",
        raw_modules_in_location.len(),
        location_path.file_name().unwrap_or_default(),
    );

    Ok(raw_modules_in_location
        .iter()
        .filter_map(
            |raw_module| match parse_module_info_file_in_module(&raw_module.path()) {
                Ok(info_file) => Some(info_file),
                Err(e) => {
                    debug!("Skipping parsing module info file: {:?}", e);
                    None
                }
            },
        )
        .collect::<Vec<ModuleInfoFile>>())
}

/// The function `parse_module_info_file_direct` parses a module info file and returns a
/// `ModuleInfoFile` object.
///
/// Arguments:
///
/// * `module_info_file_path`: A reference to a path that points to the module info file.
///
/// Returns:
///
/// The function `parse_module_info_file_direct` returns a `ModuleInfoFile` object.
fn parse_module_info_file_direct<P: AsRef<Path>>(
    module_info_file_path: &P,
) -> Result<ModuleInfoFile, ParserError> {
    parser::ModuleInfoFile::parse(module_info_file_path)
}

#[allow(clippy::too_many_lines)]
/// The `parse_module` function parses raw files from a module directory and returns a vector of parsed
/// objects.
///
/// Arguments:
///
/// * `module_path`: the path to the module directory that contains the raw files to parse.
/// * `options`: The parsing options which determine what and how to parse the raw files.
///
/// Returns:
///
/// The function `parse_module` returns a vector of boxed dynamic objects (`Vec<Box<dyn RawObject>>`).
///
/// # Errors
///
/// * `ParserError::Io` - If we can't read the raws from the Dwarf Fortress directory (various reasons)
fn parse_module<P: AsRef<Path>>(
    module_path: &P,
    options: &ParserOptions,
) -> Result<FileParseResults, ParserError> {
    // Get information from the module info file
    let module_info_file_path = module_path.as_ref().join("info.txt");
    let module_info_file: ModuleInfoFile =
        match parse_module_info_file_direct(&module_info_file_path) {
            Ok(info_file) => info_file,
            Err(e) => {
                return Err(e);
            }
        };

    // Get a list of all raw files in the module
    let objects_path = module_path.as_ref().join("objects");
    let graphics_path = module_path.as_ref().join("graphics");

    let mut parse_objects = true;
    let mut parse_graphics = options
        .object_types_to_parse
        .contains(&ObjectType::Graphics);

    if !objects_path.exists() {
        debug!(
            "Ignoring objects directory in {:?} because it does not exist",
            module_path.as_ref().file_name().unwrap_or_default(),
        );
        parse_objects = false;
    }

    if parse_objects && !objects_path.is_dir() {
        debug!(
            "Ignoring objects directory in {:?} because it is not a directory",
            module_path.as_ref().file_name().unwrap_or_default(),
        );
        parse_objects = false;
    }

    if !graphics_path.exists() {
        debug!(
            "Ignoring graphics directory in {:?} because it does not exist",
            module_path.as_ref().file_name().unwrap_or_default(),
        );
        parse_graphics = false;
    }

    if parse_graphics && !graphics_path.is_dir() {
        debug!(
            "Ignoring graphics directory in {:?} because it is not a directory",
            module_path.as_ref().file_name().unwrap_or_default(),
        );
        parse_graphics = false;
    }

    // Guard against having nothing to parse.
    if !parse_graphics && !parse_objects {
        return Ok(FileParseResults {
            parsed_raws: Vec::new(),
            unprocessed_raws: Vec::new(),
        });
    }

    let mut results: Vec<Box<dyn RawObject>> = Vec::new();
    let mut unprocessed_raws: Vec<UnprocessedRaw> = Vec::new();

    // Parse the objects
    if parse_objects {
        info!(
            "Parsing objects for {} v{}",
            module_info_file.get_identifier(),
            module_info_file.get_version(),
        );
        for entry in WalkDir::new(objects_path)
            .into_iter()
            .filter_map(std::result::Result::ok)
        {
            if entry.file_type().is_file() {
                let file_path = entry.path();
                let file_name = file_path.file_name().unwrap_or_default();
                let file_name_str = file_name.to_str().unwrap_or_default();

                if Path::new(file_name_str)
                    .extension()
                    .map_or(false, |ext| ext.eq_ignore_ascii_case("txt"))
                {
                    match parser::parse_raw_file(&file_path, options) {
                        Ok(mut file_parse_results) => {
                            results.append(&mut file_parse_results.parsed_raws);
                            unprocessed_raws.append(&mut file_parse_results.unprocessed_raws);
                        }
                        Err(e) => {
                            debug!("Skipping parsing objects: {:?}", e);
                        }
                    }
                }
            }
        }
    }

    // Parse the graphics
    if parse_graphics {
        info!(
            "Parsing graphics for {} v{}",
            module_info_file.get_identifier(),
            module_info_file.get_version(),
        );
        for entry in WalkDir::new(graphics_path)
            .into_iter()
            .filter_map(std::result::Result::ok)
        {
            if entry.file_type().is_file() {
                let file_path = entry.path();
                let file_name = file_path.file_name().unwrap_or_default();
                let file_name_str = file_name.to_str().unwrap_or_default();

                if Path::new(file_name_str)
                    .extension()
                    .map_or(false, |ext| ext.eq_ignore_ascii_case("txt"))
                {
                    match parser::parse_raw_file(&file_path, options) {
                        Ok(mut graphics) => {
                            results.append(&mut graphics.parsed_raws);
                            unprocessed_raws.append(&mut graphics.unprocessed_raws);
                        }
                        Err(e) => {
                            debug!("Skipping parsing graphics: {:?}", e);
                        }
                    }
                }
            }
        }
    }

    Ok(FileParseResults {
        parsed_raws: results,
        unprocessed_raws,
    })
}

/// The function `build_search_string` takes a `raw_object` that implements the `Searchable` trait and
/// returns a string representation of the object for searching purposes.
///
/// Arguments:
///
/// * `raw_object`: The `raw_object` parameter is a reference to an object that implements the
/// `Searchable` trait.
///
/// Returns:
///
/// The function `build_search_string` returns a `String` value.
pub fn build_search_string(raw_object: &dyn Searchable) -> String {
    crate::parser::get_search_string(raw_object)
}