lerna 2.0.3

Lerna is a framework for elegantly configuring complex applications
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
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
//! ListConfig implementation for OmegaConf
//!
//! ListConfig is a list-like container that supports:
//! - Integer indices
//! - Type validation for elements
//! - Flags (readonly)
//! - Interpolation
//! - MISSING values

use std::sync::{Arc, RwLock, Weak};

use super::base::{
    Box as OmegaBox, Container, ContainerMetadata, Metadata, Node, NodeContent, NodeKey, NodeType,
    NodeValue,
};
use super::errors::{
    ConfigTypeError, KeyValidationError, ReadonlyConfigError, Result, ValidationError,
};
use super::nodes::AnyNode;

/// A list configuration node
#[derive(Debug)]
pub struct ListConfig {
    /// Container metadata
    metadata: ContainerMetadata,
    /// The content
    content: ListContent,
    /// Parent reference
    parent: Option<Weak<RwLock<dyn Node>>>,
}

/// The internal content of a ListConfig
pub enum ListContent {
    /// Actual list content
    List(Vec<Arc<RwLock<dyn Node>>>),
    /// None value
    None,
    /// Missing value
    Missing,
    /// Interpolation
    Interpolation(String),
}

impl Clone for ListContent {
    fn clone(&self) -> Self {
        match self {
            ListContent::List(vec) => ListContent::List(vec.clone()),
            ListContent::None => ListContent::None,
            ListContent::Missing => ListContent::Missing,
            ListContent::Interpolation(s) => ListContent::Interpolation(s.clone()),
        }
    }
}

impl std::fmt::Debug for ListContent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ListContent::List(vec) => f.debug_struct("List").field("len", &vec.len()).finish(),
            ListContent::None => write!(f, "None"),
            ListContent::Missing => write!(f, "Missing"),
            ListContent::Interpolation(s) => f.debug_tuple("Interpolation").field(s).finish(),
        }
    }
}

impl ListConfig {
    /// Create a new empty ListConfig
    pub fn new() -> Self {
        Self {
            metadata: ContainerMetadata::default(),
            content: ListContent::List(Vec::new()),
            parent: None,
        }
    }

    /// Create a ListConfig representing None
    pub fn none() -> Self {
        Self {
            metadata: ContainerMetadata::default(),
            content: ListContent::None,
            parent: None,
        }
    }

    /// Create a ListConfig representing MISSING
    pub fn missing() -> Self {
        Self {
            metadata: ContainerMetadata::default(),
            content: ListContent::Missing,
            parent: None,
        }
    }

    /// Create a ListConfig from an interpolation
    pub fn interpolation(expr: impl Into<String>) -> Self {
        Self {
            metadata: ContainerMetadata::default(),
            content: ListContent::Interpolation(expr.into()),
            parent: None,
        }
    }

    /// Create a ListConfig from a vector of values
    pub fn from_vec<V: Into<NodeValue>>(items: Vec<V>) -> Self {
        let content: Vec<Arc<RwLock<dyn Node>>> = items
            .into_iter()
            .enumerate()
            .map(|(i, v)| {
                let mut node = AnyNode::with_value(v.into());
                node.set_key(Some(NodeKey::Int(i as i64)));
                Arc::new(RwLock::new(node)) as Arc<RwLock<dyn Node>>
            })
            .collect();
        Self {
            metadata: ContainerMetadata::default(),
            content: ListContent::List(content),
            parent: None,
        }
    }

    /// Get an item by index
    pub fn get(&self, index: usize) -> Option<Arc<RwLock<dyn Node>>> {
        match &self.content {
            ListContent::List(list) => list.get(index).cloned(),
            _ => None,
        }
    }

    /// Set an item by index
    pub fn set(&mut self, index: usize, value: Arc<RwLock<dyn Node>>) -> Result<()> {
        if self.is_readonly() {
            return Err(ReadonlyConfigError::new("Cannot modify read-only ListConfig").into());
        }

        if let ListContent::List(ref mut list) = self.content {
            if index >= list.len() {
                return Err(KeyValidationError::new(format!(
                    "Index {} out of range for list of length {}",
                    index,
                    list.len()
                ))
                .into());
            }

            // Set key on the value
            if let Ok(mut node) = value.write() {
                node.set_key(Some(NodeKey::Int(index as i64)));
            }
            list[index] = value;
            Ok(())
        } else {
            Err(ConfigTypeError::new("Cannot set value on non-list ListConfig").into())
        }
    }

    /// Set a primitive value at index
    pub fn set_value<V: Into<NodeValue>>(&mut self, index: usize, value: V) -> Result<()> {
        let node = AnyNode::with_value(value.into());
        self.set(index, Arc::new(RwLock::new(node)))
    }

    /// Append an item to the list
    pub fn append(&mut self, value: Arc<RwLock<dyn Node>>) -> Result<()> {
        if self.is_readonly() {
            return Err(ReadonlyConfigError::new("Cannot append to read-only ListConfig").into());
        }

        if let ListContent::List(ref mut list) = self.content {
            let index = list.len();
            if let Ok(mut node) = value.write() {
                node.set_key(Some(NodeKey::Int(index as i64)));
            }
            list.push(value);
            Ok(())
        } else {
            Err(ConfigTypeError::new("Cannot append to non-list ListConfig").into())
        }
    }

    /// Append a primitive value
    pub fn append_value<V: Into<NodeValue>>(&mut self, value: V) -> Result<()> {
        let node = AnyNode::with_value(value.into());
        self.append(Arc::new(RwLock::new(node)))
    }

    /// Insert an item at an index
    pub fn insert(&mut self, index: usize, value: Arc<RwLock<dyn Node>>) -> Result<()> {
        if self.is_readonly() {
            return Err(ReadonlyConfigError::new("Cannot insert into read-only ListConfig").into());
        }

        if let ListContent::List(ref mut list) = self.content {
            if index > list.len() {
                return Err(KeyValidationError::new(format!(
                    "Index {} out of range for list of length {}",
                    index,
                    list.len()
                ))
                .into());
            }

            if let Ok(mut node) = value.write() {
                node.set_key(Some(NodeKey::Int(index as i64)));
            }
            list.insert(index, value);

            // Update keys for subsequent elements
            self.update_keys();
            Ok(())
        } else {
            Err(ConfigTypeError::new("Cannot insert into non-list ListConfig").into())
        }
    }

    /// Remove an item by index
    pub fn remove(&mut self, index: usize) -> Result<Arc<RwLock<dyn Node>>> {
        if self.is_readonly() {
            return Err(ReadonlyConfigError::new("Cannot remove from read-only ListConfig").into());
        }

        if let ListContent::List(ref mut list) = self.content {
            if index >= list.len() {
                return Err(KeyValidationError::new(format!(
                    "Index {} out of range for list of length {}",
                    index,
                    list.len()
                ))
                .into());
            }

            let removed = list.remove(index);
            self.update_keys();
            Ok(removed)
        } else {
            Err(ConfigTypeError::new("Cannot remove from non-list ListConfig").into())
        }
    }

    /// Pop the last item
    pub fn pop(&mut self) -> Result<Option<Arc<RwLock<dyn Node>>>> {
        if self.is_readonly() {
            return Err(ReadonlyConfigError::new("Cannot pop from read-only ListConfig").into());
        }

        if let ListContent::List(ref mut list) = self.content {
            Ok(list.pop())
        } else {
            Err(ConfigTypeError::new("Cannot pop from non-list ListConfig").into())
        }
    }

    /// Extend with items from another iterator
    pub fn extend<I>(&mut self, items: I) -> Result<()>
    where
        I: IntoIterator<Item = Arc<RwLock<dyn Node>>>,
    {
        if self.is_readonly() {
            return Err(ReadonlyConfigError::new("Cannot extend read-only ListConfig").into());
        }

        if let ListContent::List(ref mut list) = self.content {
            for item in items {
                let index = list.len();
                if let Ok(mut node) = item.write() {
                    node.set_key(Some(NodeKey::Int(index as i64)));
                }
                list.push(item);
            }
            Ok(())
        } else {
            Err(ConfigTypeError::new("Cannot extend non-list ListConfig").into())
        }
    }

    /// Clear the list
    pub fn clear(&mut self) -> Result<()> {
        if self.is_readonly() {
            return Err(ReadonlyConfigError::new("Cannot clear read-only ListConfig").into());
        }

        if let ListContent::List(ref mut list) = self.content {
            list.clear();
            Ok(())
        } else {
            Err(ConfigTypeError::new("Cannot clear non-list ListConfig").into())
        }
    }

    /// Get the length
    pub fn len_internal(&self) -> usize {
        match &self.content {
            ListContent::List(list) => list.len(),
            _ => 0,
        }
    }

    /// Public len() method for convenience
    pub fn len(&self) -> usize {
        self.len_internal()
    }

    /// Check if empty
    pub fn is_empty_internal(&self) -> bool {
        self.len_internal() == 0
    }

    /// Public is_empty() method for convenience
    pub fn is_empty(&self) -> bool {
        self.is_empty_internal()
    }

    /// Update keys after insert/remove
    fn update_keys(&mut self) {
        if let ListContent::List(ref list) = self.content {
            for (i, item) in list.iter().enumerate() {
                if let Ok(mut node) = item.write() {
                    node.set_key(Some(NodeKey::Int(i as i64)));
                }
            }
        }
    }

    /// Iterate over items
    pub fn iter(&self) -> impl Iterator<Item = &Arc<RwLock<dyn Node>>> {
        match &self.content {
            ListContent::List(list) => list.iter().collect::<Vec<_>>().into_iter(),
            _ => vec![].into_iter(),
        }
    }
}

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

impl Clone for ListConfig {
    fn clone(&self) -> Self {
        Self {
            metadata: self.metadata.clone(),
            content: self.content.clone(),
            parent: None, // Don't clone parent reference
        }
    }
}

impl Node for ListConfig {
    fn node_type(&self) -> NodeType {
        NodeType::List
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn metadata(&self) -> &Metadata {
        &self.metadata.base
    }

    fn metadata_mut(&mut self) -> &mut Metadata {
        &mut self.metadata.base
    }

    fn parent(&self) -> Option<Arc<RwLock<dyn Node>>> {
        self.parent.as_ref().and_then(|w| w.upgrade())
    }

    fn set_parent(&mut self, parent: Option<Weak<RwLock<dyn Node>>>) {
        self.parent = parent;
    }

    fn content(&self) -> &NodeContent {
        match &self.content {
            ListContent::None => &NodeContent::None,
            ListContent::Missing => &NodeContent::Missing,
            _ => &NodeContent::None, // Placeholder
        }
    }

    fn set_content(&mut self, content: NodeContent) -> Result<()> {
        match content {
            NodeContent::None => {
                self.content = ListContent::None;
            }
            NodeContent::Missing => {
                self.content = ListContent::Missing;
            }
            NodeContent::Interpolation(s) => {
                self.content = ListContent::Interpolation(s);
            }
            NodeContent::Value(_) => {
                return Err(ValidationError::new("Cannot set value content on ListConfig").into());
            }
        }
        Ok(())
    }

    fn is_none(&self) -> bool {
        matches!(self.content, ListContent::None)
    }

    fn is_missing(&self) -> bool {
        matches!(self.content, ListContent::Missing)
    }

    fn is_interpolation(&self) -> bool {
        matches!(self.content, ListContent::Interpolation(_))
    }
}

impl OmegaBox for ListConfig {
    fn re_parent(&mut self) {
        // Would need Arc<RwLock<Self>> to properly implement
    }
}

impl Container for ListConfig {
    fn container_metadata(&self) -> &ContainerMetadata {
        &self.metadata
    }

    fn container_metadata_mut(&mut self) -> &mut ContainerMetadata {
        &mut self.metadata
    }

    fn get_child(&self, key: &NodeKey) -> Option<Arc<RwLock<dyn Node>>> {
        match key {
            NodeKey::Int(i) if *i >= 0 => self.get(*i as usize),
            NodeKey::String(s) => s.parse::<usize>().ok().and_then(|i| self.get(i)),
            _ => None,
        }
    }

    fn set_child(&mut self, key: NodeKey, value: Arc<RwLock<dyn Node>>) -> Result<()> {
        match key {
            NodeKey::Int(i) if i >= 0 => self.set(i as usize, value),
            NodeKey::String(s) => {
                let i = s
                    .parse::<usize>()
                    .map_err(|_| KeyValidationError::new(format!("Invalid list index: {}", s)))?;
                self.set(i, value)
            }
            _ => Err(KeyValidationError::new("Invalid list index").into()),
        }
    }

    fn delete_child(&mut self, key: &NodeKey) -> Result<()> {
        match key {
            NodeKey::Int(i) if *i >= 0 => {
                self.remove(*i as usize)?;
                Ok(())
            }
            NodeKey::String(s) => {
                let i = s
                    .parse::<usize>()
                    .map_err(|_| KeyValidationError::new(format!("Invalid list index: {}", s)))?;
                self.remove(i)?;
                Ok(())
            }
            _ => Err(KeyValidationError::new("Invalid list index").into()),
        }
    }

    fn len(&self) -> usize {
        self.len_internal()
    }

    fn keys(&self) -> Vec<NodeKey> {
        (0..self.len_internal())
            .map(|i| NodeKey::Int(i as i64))
            .collect()
    }

    fn validate_get(&self, key: &NodeKey) -> Result<()> {
        match key {
            NodeKey::Int(i) if *i >= 0 => Ok(()),
            NodeKey::Int(_) => {
                Err(KeyValidationError::new("ListConfig indices must be non-negative").into())
            }
            _ => Err(KeyValidationError::new(
                "ListConfig indices must be integers or slices, not $KEY_TYPE",
            )
            .into()),
        }
    }

    fn validate_set(&self, key: &NodeKey, _value: &dyn Node) -> Result<()> {
        if self.is_readonly() {
            return Err(ReadonlyConfigError::new("Cannot modify read-only ListConfig").into());
        }
        self.validate_get(key)
    }

    fn merge_with(&mut self, other: &dyn Container) -> Result<()> {
        // For lists, we typically replace the content
        if let ListContent::List(ref mut list) = self.content {
            list.clear();
            for key in other.keys() {
                if let Some(value) = other.get_child(&key) {
                    self.append(value)?;
                }
            }
        }
        Ok(())
    }
}

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

    #[test]
    fn test_listconfig_new() {
        let lc = ListConfig::new();
        assert!(lc.is_empty_internal());
        assert!(!lc.is_none());
        assert!(!lc.is_missing());
    }

    #[test]
    fn test_listconfig_append() {
        let mut lc = ListConfig::new();
        lc.append_value(1i64).unwrap();
        lc.append_value(2i64).unwrap();
        lc.append_value(3i64).unwrap();

        assert_eq!(lc.len_internal(), 3);
    }

    #[test]
    fn test_listconfig_from_vec() {
        let lc = ListConfig::from_vec(vec![1i64, 2i64, 3i64]);
        assert_eq!(lc.len_internal(), 3);
    }

    #[test]
    fn test_listconfig_readonly() {
        let mut lc = ListConfig::new();
        lc.append_value(1i64).unwrap();
        lc.set_flag("readonly", Some(true));

        let result = lc.append_value(2i64);
        assert!(result.is_err());
    }

    #[test]
    fn test_listconfig_pop() {
        let mut lc = ListConfig::new();
        lc.append_value(1i64).unwrap();
        lc.append_value(2i64).unwrap();

        let popped = lc.pop().unwrap();
        assert!(popped.is_some());
        assert_eq!(lc.len_internal(), 1);
    }

    #[test]
    fn test_listconfig_none() {
        let lc = ListConfig::none();
        assert!(lc.is_none());
    }

    #[test]
    fn test_listconfig_missing() {
        let lc = ListConfig::missing();
        assert!(lc.is_missing());
    }
}