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
use std::{
    io::{BufRead, BufReader},
    path::Path,
};

use encoding_rs_io::DecodeReaderBytesBuilder;
use serde::{Deserialize, Serialize};
use slug::slugify;
use tracing::{debug, error, trace, warn};

use crate::{
    parser::{RawModuleLocation, DF_ENCODING, NON_DIGIT_RE, RAW_TOKEN_RE},
    util::{get_parent_dir_name, try_get_file},
    ParserError,
};

use super::steam_data::SteamData;

/// Represents the `info.txt` file for a raw module
#[derive(Serialize, Deserialize, Default, Clone, Debug, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct InfoFile {
    identifier: String,
    object_id: String,
    location: RawModuleLocation,
    parent_directory: String,
    numeric_version: u32,
    displayed_version: String,
    earliest_compatible_numeric_version: u32,
    earliest_compatible_displayed_version: String,
    author: String,
    name: String,
    description: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    requires_ids: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    conflicts_with_ids: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    requires_ids_before: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    requires_ids_after: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    steam_data: Option<SteamData>,
}

impl InfoFile {
    /// Creates a new `InfoFile` with the passed identifier, location, and parent directory
    ///
    /// # Arguments
    ///
    /// * `id` - The identifier for the `InfoFile`
    /// * `location` - The location the `InfoFile` was parsed from
    /// * `parent_directory` - The directory the `InfoFile` was parsed from
    ///
    /// # Returns
    ///
    /// * The `InfoFile`
    #[must_use]
    pub fn new(id: &str, location: RawModuleLocation, parent_directory: &str) -> Self {
        Self {
            identifier: String::from(id),
            location,
            parent_directory: String::from(parent_directory),
            object_id: format!("{}-{}-{}", location, "MODULE", slugify(id)),
            ..Default::default()
        }
    }
    /// Creates a new empty `InfoFile`
    ///
    /// # Returns
    ///
    /// * The empty `InfoFile`
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }
    /// Creates a new `InfoFile` from the passed `info.txt` file path
    ///
    /// # Arguments
    ///
    /// * `full_path` - The full path to the `info.txt` file
    ///
    /// # Returns
    ///
    /// * `Result<InfoFile, ParserError>` - The parsed `InfoFile` or an error
    ///
    /// # Errors
    ///
    /// * `ParserError::FileNotFound` - If the passed file path does not exist
    /// * `ParserError::IOError` - If there is an error reading the file
    pub fn from_raw_file_path<P: AsRef<Path>>(full_path: &P) -> Result<Self, ParserError> {
        // Validate that the passed file exists
        let _ = try_get_file(full_path)?;

        // Take the full path for the raw file and navigate up to the parent directory
        // e.g from `data/vanilla/vanilla_creatures/objects/creature_standard.txt` to `data/vanilla/vanilla_creatures`
        // Then run parse on `data/vanilla/vanilla_creatures/info.txt`
        let parent_directory = full_path
            .as_ref()
            .parent()
            .unwrap_or_else(|| Path::new(""))
            .parent()
            .unwrap_or_else(|| Path::new(""))
            .to_string_lossy()
            .to_string();
        let info_file_path = Path::new(parent_directory.as_str()).join("info.txt");
        Self::parse(&info_file_path)
    }
    /// Parses the `info.txt` file at the passed path
    ///
    /// # Arguments
    ///
    /// * `info_file_path` - The path to the `info.txt` file
    ///
    /// # Returns
    ///
    /// * `Result<InfoFile, ParserError>` - The parsed `InfoFile` or an error
    ///
    /// # Errors
    ///
    /// * `ParserError::FileNotFound` - If the passed file path does not exist
    /// * `ParserError::IOError` - If there is an error reading the file
    #[allow(clippy::cognitive_complexity, clippy::too_many_lines)]
    pub fn parse<P: AsRef<Path>>(info_file_path: &P) -> Result<Self, ParserError> {
        let parent_dir = get_parent_dir_name(info_file_path);
        let location = RawModuleLocation::from_info_text_file_path(info_file_path);

        let file = match try_get_file(info_file_path) {
            Ok(f) => f,
            Err(e) => {
                error!("ModuleInfoFile::parse: try_get_file error");
                debug!("{:?}", e);
                return Err(ParserError::NothingToParse(
                    info_file_path.as_ref().display().to_string(),
                ));
            }
        };

        let decoding_reader = DecodeReaderBytesBuilder::new()
            .encoding(Some(*DF_ENCODING))
            .build(file);
        let reader = BufReader::new(decoding_reader);

        // info.txt details
        let mut info_file_data: Self = Self::new("", location, &parent_dir);

        for (index, line) in reader.lines().enumerate() {
            if line.is_err() {
                error!("parse: Error processing {:?}:{}", parent_dir, index);
                continue;
            }
            let line = match line {
                Ok(l) => l,
                Err(e) => {
                    error!("parse:  Line-reading error");
                    debug!("{:?}", e);
                    continue;
                }
            };
            for cap in RAW_TOKEN_RE.captures_iter(&line) {
                let captured_key = match cap.get(2) {
                    Some(v) => v.as_str(),
                    _ => {
                        continue;
                    }
                };
                let captured_value = match cap.get(3) {
                    Some(v) => v.as_str(),
                    _ => {
                        continue;
                    }
                };

                trace!(
                    "ModuleInfoFile::parse: Key: {} Value: {}",
                    captured_key,
                    captured_value
                );

                match captured_key {
                    // SECTION FOR MATCHING info.txt DATA
                    "ID" => {
                        // the [ID:identifier] tag should be the top of the info.txt file
                        info_file_data = Self::new(captured_value, location, &parent_dir);
                    }
                    "NUMERIC_VERSION" => match captured_value.parse() {
                        Ok(n) => info_file_data.numeric_version = n,
                        Err(_e) => {
                            warn!(
                                "ModuleInfoFile::parse: 'NUMERIC_VERSION' should be integer '{}' in {}",
                                captured_value,
                                info_file_path.as_ref().display()
                            );
                            // match on \D to replace any non-digit characters with empty string
                            let digits_only =
                                NON_DIGIT_RE.replace_all(captured_value, "").to_string();
                            match digits_only.parse() {
                                Ok(n) => info_file_data.numeric_version = n,
                                Err(_e) => {
                                    debug!(
                                        "ModuleInfoFile::parse: Unable to parse any numbers from {} for NUMERIC_VERSION",
                                        captured_value
                                    );
                                }
                            }
                        }
                    },
                    "EARLIEST_COMPATIBLE_NUMERIC_VERSION" => match captured_value.parse() {
                        Ok(n) => info_file_data.earliest_compatible_numeric_version = n,
                        Err(_e) => {
                            warn!(
                                "ModuleInfoFile::parse: 'EARLIEST_COMPATIBLE_NUMERIC_VERSION' should be integer '{}' in {:?}",
                                captured_value,
                                info_file_path.as_ref().display()
                            );
                            // match on \D to replace any non-digit characters with empty string
                            let digits_only =
                                NON_DIGIT_RE.replace_all(captured_value, "").to_string();
                            match digits_only.parse() {
                                Ok(n) => info_file_data.earliest_compatible_numeric_version = n,
                                Err(_e) => {
                                    debug!(
                                        "ModuleInfoFile::parse: Unable to parse any numbers from {} for EARLIEST_COMPATIBLE_NUMERIC_VERSION",
                                        captured_value
                                    );
                                }
                            }
                        }
                    },
                    "DISPLAYED_VERSION" => {
                        info_file_data.displayed_version = String::from(captured_value);
                    }
                    "EARLIEST_COMPATIBLE_DISPLAYED_VERSION" => {
                        info_file_data.earliest_compatible_displayed_version =
                            String::from(captured_value);
                    }
                    "AUTHOR" => {
                        info_file_data.author = String::from(captured_value);
                    }
                    "NAME" => {
                        info_file_data.name = String::from(captured_value);
                    }
                    "DESCRIPTION" => {
                        info_file_data.description = String::from(captured_value);
                    }
                    "REQUIRES_ID" => {
                        if info_file_data.requires_ids.is_none() {
                            info_file_data.requires_ids = Some(Vec::new());
                        }

                        if let Some(requires_ids) = info_file_data.requires_ids.as_mut() {
                            requires_ids.push(String::from(captured_value));
                        }
                    }
                    "CONFLICTS_WITH_ID" => {
                        if info_file_data.conflicts_with_ids.is_none() {
                            info_file_data.conflicts_with_ids = Some(Vec::new());
                        }

                        if let Some(conflicts_with_ids) = info_file_data.conflicts_with_ids.as_mut()
                        {
                            conflicts_with_ids.push(String::from(captured_value));
                        }
                    }
                    "REQUIRES_ID_BEFORE_ME" => {
                        if info_file_data.requires_ids_before.is_none() {
                            info_file_data.requires_ids_before = Some(Vec::new());
                        }

                        if let Some(requires_ids_before) =
                            info_file_data.requires_ids_before.as_mut()
                        {
                            requires_ids_before.push(String::from(captured_value));
                        }
                    }
                    "REQUIRES_ID_AFTER_ME" => {
                        if info_file_data.requires_ids_after.is_none() {
                            info_file_data.requires_ids_after = Some(Vec::new());
                        }

                        if let Some(requires_ids_after) = info_file_data.requires_ids_after.as_mut()
                        {
                            requires_ids_after.push(String::from(captured_value));
                        }
                    }
                    "STEAM_TITLE" => {
                        if info_file_data.steam_data.is_none() {
                            info_file_data.steam_data = Some(SteamData::default());
                        }

                        if let Some(steam_data) = info_file_data.steam_data.as_mut() {
                            steam_data.set_title(&String::from(captured_value));
                        }
                    }
                    "STEAM_DESCRIPTION" => {
                        if info_file_data.steam_data.is_none() {
                            info_file_data.steam_data = Some(SteamData::default());
                        }

                        if let Some(steam_data) = info_file_data.steam_data.as_mut() {
                            steam_data.set_description(&String::from(captured_value));
                        }
                    }
                    "STEAM_TAG" => {
                        if info_file_data.steam_data.is_none() {
                            info_file_data.steam_data = Some(SteamData::default());
                        }

                        if let Some(steam_data) = info_file_data.steam_data.as_mut() {
                            steam_data.add_tag(&String::from(captured_value));
                        }
                    }
                    "STEAM_KEY_VALUE_TAG" => {
                        if info_file_data.steam_data.is_none() {
                            info_file_data.steam_data = Some(SteamData::default());
                        }

                        if let Some(steam_data) = info_file_data.steam_data.as_mut() {
                            steam_data.add_key_value_tag(&String::from(captured_value));
                        }
                    }
                    "STEAM_METADATA" => {
                        if info_file_data.steam_data.is_none() {
                            info_file_data.steam_data = Some(SteamData::default());
                        }

                        if let Some(steam_data) = info_file_data.steam_data.as_mut() {
                            steam_data.add_metadata(&String::from(captured_value));
                        }
                    }
                    "STEAM_CHANGELOG" => {
                        if info_file_data.steam_data.is_none() {
                            info_file_data.steam_data = Some(SteamData::default());
                        }

                        if let Some(steam_data) = info_file_data.steam_data.as_mut() {
                            steam_data.set_changelog(&String::from(captured_value));
                        }
                    }
                    "STEAM_FILE_ID" => match captured_value.parse() {
                        Ok(n) => {
                            if info_file_data.steam_data.is_none() {
                                info_file_data.steam_data = Some(SteamData::default());
                            }

                            if let Some(steam_data) = info_file_data.steam_data.as_mut() {
                                steam_data.set_file_id(n);
                            }
                        }
                        Err(_e) => {
                            warn!(
                                "ModuleInfoFile::parse: 'STEAM_FILE_ID' should be integer, was {} in {}",
                                captured_value,
                                info_file_path.as_ref().display()
                            );
                            // match on \D to replace any non-digit characters with empty string
                            let digits_only =
                                NON_DIGIT_RE.replace_all(captured_value, "").to_string();
                            match digits_only.parse() {
                                Ok(n) => {
                                    if info_file_data.steam_data.is_none() {
                                        info_file_data.steam_data = Some(SteamData::default());
                                    }

                                    if let Some(steam_data) = info_file_data.steam_data.as_mut() {
                                        steam_data.set_file_id(n);
                                    }
                                }
                                Err(_e) => {
                                    debug!(
                                        "ModuleInfoFile::parse: Unable to parse any numbers from {} for STEAM_FILE_ID",
                                        captured_value
                                    );
                                }
                            }
                        }
                    },
                    &_ => (),
                }
            }
        }

        // Do some final checks to confirm that the name is set. Specifically in "Dark Ages V - War & Mythos" the
        // [name] Token in the info.txt is written incorrectly as "[name]X" instead of [name:X]
        if info_file_data.name.is_empty() || info_file_data.name.is_empty() {
            info_file_data.name = info_file_data.get_identifier();
        }

        // Check for 'unknown' identifier and try to provide any extra info
        if info_file_data.get_identifier() == "unknown" {
            error!(
                "Failure parsing proper info from {}",
                info_file_path.as_ref().display()
            );
        }

        Ok(info_file_data)
    }
    /// Returns the identifier for the `InfoFile`
    pub fn get_identifier(&self) -> String {
        String::from(&self.identifier)
    }
    /// Returns the location the `InfoFile` was parsed from
    pub const fn get_location(&self) -> RawModuleLocation {
        self.location
    }
    /// Returns the description for the `InfoFile`
    pub fn get_description(&self) -> String {
        String::from(&self.description)
    }
    /// Returns the name for the `InfoFile`
    pub fn get_name(&self) -> String {
        String::from(&self.name)
    }
    /// Returns the displayed version for the `InfoFile`
    pub fn get_version(&self) -> String {
        String::from(&self.displayed_version)
    }
    /// Returns the module's object id
    pub fn get_object_id(&self) -> String {
        String::from(&self.object_id)
    }
    /// Returns the directory the `InfoFile` was parsed from
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::path::Path;
    /// use dfraw_json_parser::{ModuleInfoFile, RawModuleLocation};
    ///
    /// let mut info_file = ModuleInfoFile::new("vanilla_creatures", RawModuleLocation::Vanilla, "vanilla_creatures");
    ///
    /// assert_eq!(info_file.get_parent_directory(), "vanilla_creatures");
    /// ```
    pub fn get_parent_directory(&self) -> String {
        String::from(&self.parent_directory)
    }
    /// Set the name of the module the `InfoFile` was parsed in
    ///
    /// # Arguments
    ///
    /// * `arg` - The name of the module
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::path::Path;
    /// use dfraw_json_parser::{ModuleInfoFile, RawModuleLocation};
    ///
    /// let mut info_file = ModuleInfoFile::new("vanilla_creatures", RawModuleLocation::Vanilla, "vanilla_creatures");
    ///
    /// info_file.set_module_name("vanilla_creatures_2");
    /// assert_eq!(info_file.get_name(), "vanilla_creatures_2");
    /// ```
    pub fn set_module_name(&mut self, arg: &str) {
        self.name = String::from(arg);
    }
}