unity-asset-yaml 0.2.0

YAML format support for Unity asset parsing
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
//! YAML-specific Unity document implementation
//!
//! This module provides the concrete implementation of UnityDocument
//! for YAML format files.

use crate::unity_yaml_serializer::UnityYamlSerializer;
use std::fs;
use std::path::Path;
use unity_asset_core::{
    DocumentFormat, LineEnding, Result, UnityAssetError, UnityClass, UnityDocument,
    document::DocumentMetadata,
};

#[cfg(feature = "async")]
use async_trait::async_trait;
#[cfg(feature = "async")]
use unity_asset_core::document::AsyncUnityDocument;

/// A Unity YAML document containing one or more Unity objects
#[derive(Debug)]
pub struct YamlDocument {
    /// The Unity objects in this document
    data: Vec<UnityClass>,
    /// Document metadata
    metadata: DocumentMetadata,
    /// Line ending style used in the original file
    newline: LineEnding,
}

impl YamlDocument {
    /// Create a new empty YAML document
    pub fn new() -> Self {
        Self {
            data: Vec::new(),
            metadata: DocumentMetadata::new(DocumentFormat::Yaml),
            newline: LineEnding::default(),
        }
    }

    /// Load a Unity YAML file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the YAML file to load
    /// * `preserve_types` - If true, try to preserve int/float types instead of converting all to strings
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unity_asset_yaml::YamlDocument;
    ///
    /// let doc = YamlDocument::load_yaml("ProjectSettings.asset", false)?;
    /// # Ok::<(), unity_asset_core::UnityAssetError>(())
    /// ```
    pub fn load_yaml<P: AsRef<Path>>(path: P, _preserve_types: bool) -> Result<Self> {
        Ok(Self::load_yaml_with_warnings(path, _preserve_types)?.0)
    }

    /// Load a Unity YAML file and return non-fatal conversion warnings.
    pub fn load_yaml_with_warnings<P: AsRef<Path>>(
        path: P,
        _preserve_types: bool,
    ) -> Result<(Self, Vec<crate::serde_unity_loader::SerdeUnityWarning>)> {
        use crate::serde_unity_loader::SerdeUnityLoader;
        use std::fs::File;
        use std::io::BufReader;

        let path = path.as_ref();

        // Read the file
        let file = File::open(path).map_err(|e| {
            UnityAssetError::format(format!("Failed to open file {}: {}", path.display(), e))
        })?;
        let reader = BufReader::new(file);

        // Use serde-based loader
        let loader = SerdeUnityLoader::new();
        let (unity_classes, warnings) = loader.load_from_reader_detailed(reader)?;

        // Create YamlDocument with metadata
        let mut yaml_doc = YamlDocument::new();
        yaml_doc.metadata.file_path = Some(path.to_path_buf());

        // Add all loaded classes
        for unity_class in unity_classes {
            yaml_doc.add_entry(unity_class);
        }

        Ok((yaml_doc, warnings))
    }

    /// Load a Unity YAML file asynchronously
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the YAML file to load
    /// * `preserve_types` - If true, try to preserve int/float types instead of converting all to strings
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "async")]
    /// # {
    /// use unity_asset_yaml::YamlDocument;
    ///
    /// # tokio_test::block_on(async {
    /// let doc = YamlDocument::load_yaml_async("ProjectSettings.asset", false).await?;
    /// # Ok::<(), unity_asset_core::UnityAssetError>(())
    /// # }).unwrap();
    /// # }
    /// ```
    #[cfg(feature = "async")]
    pub async fn load_yaml_async<P: AsRef<Path> + Send>(
        path: P,
        _preserve_types: bool,
    ) -> Result<Self> {
        Ok(Self::load_yaml_async_with_warnings(path, _preserve_types)
            .await?
            .0)
    }

    #[cfg(feature = "async")]
    pub async fn load_yaml_async_with_warnings<P: AsRef<Path> + Send>(
        path: P,
        _preserve_types: bool,
    ) -> Result<(Self, Vec<crate::serde_unity_loader::SerdeUnityWarning>)> {
        use crate::serde_unity_loader::SerdeUnityLoader;
        use tokio::fs::File;
        use tokio::io::BufReader;

        let path = path.as_ref();

        // Read the file asynchronously
        let file = File::open(path).await.map_err(|e| {
            UnityAssetError::format(format!("Failed to open file {}: {}", path.display(), e))
        })?;
        let reader = BufReader::new(file);

        // Use serde-based loader (we'll need to make this async too)
        let loader = SerdeUnityLoader::new();
        let (unity_classes, warnings) = loader.load_from_async_reader_detailed(reader).await?;

        // Create YamlDocument with metadata
        let mut yaml_doc = YamlDocument::new();
        yaml_doc.metadata.file_path = Some(path.to_path_buf());

        // Add all loaded classes
        for unity_class in unity_classes {
            yaml_doc.add_entry(unity_class);
        }

        Ok((yaml_doc, warnings))
    }

    /// Get the line ending style
    pub fn line_ending(&self) -> LineEnding {
        self.newline
    }

    /// Set the line ending style
    pub fn set_line_ending(&mut self, newline: LineEnding) {
        self.newline = newline;
    }

    /// Get the YAML version
    pub fn version(&self) -> Option<&str> {
        self.metadata.version.as_deref()
    }

    /// Get the YAML metadata
    pub fn yaml_metadata(&self) -> &std::collections::HashMap<String, String> {
        &self.metadata.metadata
    }

    /// Save document to its original file
    ///
    /// This method saves the document back to the file it was loaded from.
    /// If the document was not loaded from a file, this will return an error.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unity_asset_yaml::YamlDocument;
    ///
    /// let mut doc = YamlDocument::load_yaml("ProjectSettings.asset", false)?;
    /// // ... modify the document ...
    /// doc.save()?;  // Save back to original file
    /// # Ok::<(), unity_asset_core::UnityAssetError>(())
    /// ```
    pub fn save(&self) -> Result<()> {
        if let Some(path) = &self.metadata.file_path {
            self.save_to(path)
        } else {
            Err(UnityAssetError::format(
                "Cannot save document: no file path available. Use save_to() instead.".to_string(),
            ))
        }
    }

    /// Save document to a specific file
    ///
    /// This method serializes the document to Unity YAML format and saves it
    /// to the specified file path.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unity_asset_yaml::YamlDocument;
    ///
    /// let doc = YamlDocument::load_yaml("ProjectSettings.asset", false)?;
    /// doc.save_to("ProjectSettings_backup.asset")?;
    /// # Ok::<(), unity_asset_core::UnityAssetError>(())
    /// ```
    pub fn save_to<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let path = path.as_ref();

        // Create serializer with document settings
        let mut serializer = UnityYamlSerializer::new().with_line_ending(self.newline);

        // Serialize to string
        let yaml_content = serializer.serialize_to_string(&self.data)?;

        // Write to file
        fs::write(path, yaml_content).map_err(UnityAssetError::from)?;

        Ok(())
    }

    /// Get YAML content as string
    ///
    /// This method serializes the document to Unity YAML format and returns
    /// it as a string without writing to a file.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unity_asset_yaml::YamlDocument;
    ///
    /// let doc = YamlDocument::load_yaml("ProjectSettings.asset", false)?;
    /// let yaml_string = doc.dump_yaml()?;
    /// println!("{}", yaml_string);
    /// # Ok::<(), unity_asset_core::UnityAssetError>(())
    /// ```
    pub fn dump_yaml(&self) -> Result<String> {
        let mut serializer = UnityYamlSerializer::new().with_line_ending(self.newline);

        serializer.serialize_to_string(&self.data)
    }

    /// Filter entries by class names and/or attributes
    ///
    /// This method provides advanced filtering capabilities similar to the
    /// Python reference library's filter() method.
    ///
    /// # Arguments
    ///
    /// * `class_names` - Optional list of class names to filter by
    /// * `attributes` - Optional list of attribute names that entries must have
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unity_asset_yaml::YamlDocument;
    ///
    /// let doc = YamlDocument::load_yaml("scene.unity", false)?;
    ///
    /// // Find all GameObjects
    /// let gameobjects = doc.filter(Some(&["GameObject"]), None);
    ///
    /// // Find all objects with m_Enabled property
    /// let enabled_objects = doc.filter(None, Some(&["m_Enabled"]));
    ///
    /// // Find MonoBehaviours with m_Script property
    /// let scripts = doc.filter(Some(&["MonoBehaviour"]), Some(&["m_Script"]));
    /// # Ok::<(), unity_asset_core::UnityAssetError>(())
    /// ```
    pub fn filter(
        &self,
        class_names: Option<&[&str]>,
        attributes: Option<&[&str]>,
    ) -> Vec<&UnityClass> {
        self.data
            .iter()
            .filter(|entry| {
                // Check class name filter
                if let Some(names) = class_names
                    && !names.is_empty()
                    && !names.contains(&entry.class_name.as_str())
                {
                    return false;
                }

                // Check attribute filter
                if let Some(attrs) = attributes
                    && !attrs.is_empty()
                {
                    for attr in attrs {
                        if !entry.has_property(attr) {
                            return false;
                        }
                    }
                }

                true
            })
            .collect()
    }

    /// Get a single entry by class name and/or attributes
    ///
    /// This method returns the first entry that matches the criteria.
    /// Returns an error if no matching entry is found or if multiple entries match.
    ///
    /// # Arguments
    ///
    /// * `class_name` - Optional class name to match
    /// * `attributes` - Optional list of attribute names that the entry must have
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use unity_asset_yaml::YamlDocument;
    ///
    /// let doc = YamlDocument::load_yaml("scene.unity", false)?;
    ///
    /// // Get the first GameObject
    /// let gameobject = doc.get(Some("GameObject"), None)?;
    ///
    /// // Get an object with specific attributes
    /// let script = doc.get(Some("MonoBehaviour"), Some(&["m_Script", "m_Enabled"]))?;
    /// # Ok::<(), unity_asset_core::UnityAssetError>(())
    /// ```
    pub fn get(
        &self,
        class_name: Option<&str>,
        attributes: Option<&[&str]>,
    ) -> Result<&UnityClass> {
        let class_names = class_name.map(|name| vec![name]);
        let filtered = self.filter(class_names.as_deref(), attributes);

        match filtered.len() {
            0 => Err(UnityAssetError::format(format!(
                "No entry found matching criteria: class_name={:?}, attributes={:?}",
                class_name, attributes
            ))),
            1 => Ok(filtered[0]),
            n => Err(UnityAssetError::format(format!(
                "Multiple entries ({}) found matching criteria: class_name={:?}, attributes={:?}. Use filter() instead.",
                n, class_name, attributes
            ))),
        }
    }
}

impl UnityDocument for YamlDocument {
    fn entry(&self) -> Option<&UnityClass> {
        self.data.first()
    }

    fn entry_mut(&mut self) -> Option<&mut UnityClass> {
        self.data.first_mut()
    }

    fn entries(&self) -> &[UnityClass] {
        &self.data
    }

    fn entries_mut(&mut self) -> &mut Vec<UnityClass> {
        &mut self.data
    }

    fn add_entry(&mut self, entry: UnityClass) {
        self.data.push(entry);
    }

    fn file_path(&self) -> Option<&Path> {
        self.metadata.file_path.as_deref()
    }

    fn save(&self) -> Result<()> {
        match &self.metadata.file_path {
            Some(path) => self.save_to(path),
            None => Err(UnityAssetError::format("No file path specified for save")),
        }
    }

    fn save_to<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let path = path.as_ref();

        // Serialize the document to YAML format
        let yaml_content = self.dump_yaml()?;

        // Write to file
        std::fs::write(path, yaml_content)
            .map_err(|e| UnityAssetError::format(format!("Failed to write YAML file: {}", e)))?;

        Ok(())
    }

    fn format(&self) -> DocumentFormat {
        DocumentFormat::Yaml
    }
}

impl Default for YamlDocument {
    fn default() -> Self {
        Self::new()
    }
}

/// Async implementation of UnityDocument trait for YamlDocument
#[cfg(feature = "async")]
#[async_trait]
impl AsyncUnityDocument for YamlDocument {
    async fn load_from_path_async<P: AsRef<Path> + Send>(path: P) -> Result<Self>
    where
        Self: Sized,
    {
        Self::load_yaml_async(path, false).await
    }

    async fn save_to_path_async<P: AsRef<Path> + Send>(&self, path: P) -> Result<()> {
        // For now, use the sync version wrapped in spawn_blocking
        let content = self.dump_yaml()?;
        let path = path.as_ref().to_path_buf();

        tokio::task::spawn_blocking(move || {
            std::fs::write(&path, content).map_err(|e| {
                UnityAssetError::format(format!("Failed to write file {}: {}", path.display(), e))
            })
        })
        .await
        .map_err(|e| UnityAssetError::format(format!("Task join error: {}", e)))??;

        Ok(())
    }

    fn entries(&self) -> &[UnityClass] {
        &self.data
    }

    fn file_path(&self) -> Option<&Path> {
        self.metadata.file_path.as_deref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use unity_asset_core::UnityClass;

    #[test]
    fn test_yaml_document_creation() {
        let doc = YamlDocument::new();
        assert!(doc.is_empty());
        assert_eq!(doc.len(), 0);
        assert_eq!(doc.format(), DocumentFormat::Yaml);
    }

    #[test]
    fn test_yaml_document_add_entry() {
        let mut doc = YamlDocument::new();
        let class = UnityClass::new(1, "GameObject".to_string(), "123".to_string());

        doc.add_entry(class);
        assert_eq!(doc.len(), 1);
        assert!(!doc.is_empty());
    }

    #[test]
    fn test_yaml_document_filter() {
        let mut doc = YamlDocument::new();

        let class1 = UnityClass::new(1, "GameObject".to_string(), "123".to_string());
        let class2 = UnityClass::new(114, "MonoBehaviour".to_string(), "456".to_string());

        doc.add_entry(class1);
        doc.add_entry(class2);

        let game_objects = doc.filter_by_class("GameObject");
        assert_eq!(game_objects.len(), 1);

        let behaviours = doc.filter_by_class("MonoBehaviour");
        assert_eq!(behaviours.len(), 1);
    }

    #[test]
    fn test_yaml_document_metadata() {
        let doc = YamlDocument::new();
        assert_eq!(doc.format(), DocumentFormat::Yaml);
        assert_eq!(doc.line_ending(), LineEnding::default());
        assert!(doc.version().is_none());
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_async_yaml_document_creation() {
        use futures::StreamExt;
        use unity_asset_core::document::AsyncUnityDocument;

        // Test that the async trait methods compile and work
        let doc = YamlDocument::new();
        assert!(AsyncUnityDocument::entries(&doc).is_empty());
        assert!(AsyncUnityDocument::entry(&doc).is_none());
        assert!(AsyncUnityDocument::file_path(&doc).is_none());

        // Test stream functionality
        let mut stream = doc.entries_stream();
        assert!(stream.next().await.is_none());
    }
}