ocd 0.8.0

Organize current dotfiles
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
// SPDX-FileCopyrightText: 2025 Jason Pena <jasonpena@awkless.com>
// SPDX-License-Identifier: MIT

//! Cluster definition parser.
//!
//! Provides methods to parse, deserialize, and manipulate the cluster definition.

use super::{config_dir, glob_match, home_dir};

use anyhow::{anyhow, Result};
use beau_collector::BeauCollector as _;
use config::{Config, File};
use serde::{
    de::{MapAccess, Visitor},
    Deserialize, Deserializer,
};
use std::{
    collections::{HashMap, HashSet, VecDeque},
    ffi::OsString,
    fmt,
    marker::PhantomData,
    path::PathBuf,
    str::FromStr,
};
use tracing::{debug, instrument, trace, warn};

/// Cluster definition handler.
///
/// A cluster definition simply defines the entries of a given cluster that OCD must manage through
/// the repository store. A cluster is comprised of two basic entry types: __root__ and __node__.
/// The root is always bare-alias, and is always deployed, because it contains the cluster
/// definition itself. There can only be one root for any given cluster that the user defines.
/// A node entry can either be normal or bare-alias. The user can define zero or more nodes within
/// a given cluster, while root must always exist.
///
/// Each entry in the cluster definition receives its own configuration file in the TOML format.
/// The root of a cluster is stored at the top-level of OCD's configuration directory as
/// `$XDG_CONFIG_HOME/ocd/root.toml`, while nodes are stored in a sub-directory at
/// `$XDG_CONFIG_HOME/ocd/nodes`. The name of a given configuration file is the name that it will
/// be given within the repository store (excluding file extension).
///
/// # Invariants
///
/// - Root always exists.
/// - All node dependencies are acyclic.
/// - Working directory aliases are expanded.
/// - Node dependencies are defined.
#[derive(Debug, PartialEq, Eq)]
pub struct Cluster {
    /// Root entry of cluster.
    pub root: RootEntry,

    /// Node entries of cluster represented as DAG.
    pub nodes: HashMap<String, NodeEntry>,
}

impl Cluster {
    /// Construct new cluster definition by reading and deserializing configuration files.
    ///
    /// # Errors
    ///
    /// - Will fail if `root.toml` does not exist.
    /// - Will fail if _any_ configuration file contains invalid TOML formatting.
    #[instrument(level = "debug")]
    pub fn new() -> Result<Self> {
        trace!("Load cluster configuration");

        let path = config_dir()?.join("root.toml");
        debug!("Load root at {path:?}");
        let root: RootEntry =
            Config::builder().add_source(File::from(path)).build()?.try_deserialize()?;
        let pattern = config_dir()?.join("nodes").join("*.toml").to_string_lossy().into_owned();
        let mut nodes = HashMap::new();
        for entry in glob::glob(pattern.as_str())? {
            // INVARIANT: The name of a node is the file name itself without the extension.
            let path = entry?;
            let name = path.file_stem().unwrap().to_string_lossy().into_owned();

            debug!("Load node {name:?} at {path:?}");
            let node: NodeEntry = Config::builder()
                .add_source(File::from(path).required(false))
                .build()?
                .try_deserialize()?;
            nodes.insert(name, node);
        }

        let mut cluster = Self { root, nodes };
        cluster.dependency_existence_check()?;
        cluster.acyclic_check()?;
        cluster.expand_work_dir_aliases()?;

        Ok(cluster)
    }

    /// Iterate through node dependencies of target node entry inclusively.
    ///
    /// There is no specific ordering for node dependencies being iterated through.
    pub fn dependency_iter(&self, node: impl Into<String>) -> DependencyIter<'_> {
        let mut stack = VecDeque::new();
        stack.push_front(node.into());
        DependencyIter { graph: &self.nodes, visited: HashSet::new(), stack }
    }

    /// Match list of targets to entries in cluster.
    ///
    /// # Errors
    ///
    /// May fail if targets do not match.
    pub fn match_targets(&self, mut targets: Vec<String>) -> Result<Vec<String>> {
        let mut results = Vec::new();

        targets.dedup();
        for target in &mut targets {
            target.retain(|c| !c.is_whitespace());
        }

        if let Some(index) = targets.iter().position(|x| *x == "root") {
            targets.swap_remove(index);
            results.push("root".into());
        }
        results.append(&mut glob_match(targets, self.nodes.keys()));

        Ok(results)
    }

    #[instrument(skip(self), level = "debug")]
    fn dependency_existence_check(&self) -> Result<()> {
        trace!("Perform dependency existence check on cluster");
        let mut results = Vec::new();
        for node in self.nodes.values() {
            for dependency in node.settings.dependencies.iter().flatten() {
                if !self.nodes.contains_key(dependency) {
                    results.push(Err(anyhow!(
                        "Node dependency {dependency:?} is not defined in cluster"
                    )));
                } else {
                    results.push(Ok(()));
                }
            }
        }

        results.into_iter().bcollect::<_>()
    }

    #[instrument(skip(self), level = "debug")]
    fn acyclic_check(&self) -> Result<()> {
        trace!("Perform acyclic check on cluster");
        let mut in_degree: HashMap<String, usize> = HashMap::new();
        let mut queue: VecDeque<String> = VecDeque::new();
        let mut visited: HashSet<String> = HashSet::new();

        // INVARIANT: The in-degree of a node is the sum all all incoming edegs of each
        // destination node.
        for (name, node) in &self.nodes {
            in_degree.entry(name.clone()).or_insert(0);
            for dependency in node.settings.dependencies.iter().flatten() {
                *in_degree.entry(dependency.clone()).or_insert(0) += 1;
            }
        }

        // INVARIANT: Queue only contains nodes with in-degree of 0.
        for (name, degree) in &in_degree {
            if *degree == 0 {
                queue.push_back(name.clone());
            }
        }

        while let Some(current) = queue.pop_front() {
            for dependency in self.nodes[&current].settings.dependencies.iter().flatten() {
                *in_degree.get_mut(dependency).unwrap() -= 1;
                if *in_degree.get(dependency).unwrap() == 0 {
                    queue.push_back(dependency.clone());
                }
            }
            visited.insert(current);
        }

        // INVARIANT: Queue is empty, but graph has not been fully visited.
        //   - There exists a cycle.
        //   - The unvisited nodes represent this cycle.
        if visited.len() != self.nodes.len() {
            let cycle: Vec<String> =
                self.nodes.keys().filter(|key| !visited.contains(*key)).cloned().collect();
            return Err(anyhow!("Cluster contains cycle(s): {cycle:?}"));
        }
        debug!("Topological sort of cluster nodes: {visited:?}");

        Ok(())
    }

    #[instrument(skip(self), level = "debug")]
    fn expand_work_dir_aliases(&mut self) -> Result<()> {
        trace!("Expand working directory aliases of nodes");
        for node in self.nodes.values_mut() {
            let expand = shellexpand::full(
                node.settings.deployment.work_dir_alias.0.to_string_lossy().as_ref(),
            )?
            .into_owned();
            node.settings.deployment.work_dir_alias = WorkDirAlias::new(expand);
        }
        Ok(())
    }
}

/// Iterator for node entry dependencies.
///
/// Obtain a full listing of nodes defined as dependencies of a given target node that was
/// initially pushed into stack.
#[derive(Debug)]
pub struct DependencyIter<'cluster> {
    graph: &'cluster HashMap<String, NodeEntry>,
    visited: HashSet<String>,
    stack: VecDeque<String>,
}

impl<'cluster> Iterator for DependencyIter<'cluster> {
    type Item = (&'cluster str, &'cluster NodeEntry);

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(node) = self.stack.pop_front() {
            let (name, node) = self.graph.get_key_value(&node)?;
            for dependency in node.settings.dependencies.iter().flatten() {
                if !self.visited.contains(dependency) {
                    self.stack.push_front(dependency.clone());
                    self.visited.insert(dependency.clone());
                }
            }
            return Some((name.as_str(), node));
        }
        None
    }
}

/// Root entry of cluster definition.
///
/// Any and all cluster's that OCD operates on must have a _root_. The root contains the cluster
/// definition, which must always be deployed in order for OCD to know what nodes it must manage
/// within the repository store.
///
/// Root is always bare-alias such that it can only be deployed at two locations relative to the
/// user's home directory:
///
/// 1. The user's home directory itself.
/// 2. The standard configuration directory for OCD, i.e., `$XDG_CONFIG_HOME/ocd`.
///
/// This restriction of deployment for root ensures that the cluster definition always exists at
/// the standard configuration directory. This ensures that the cluster definition can be reliably
/// read, parsed, and deserialized during runtime. This also ensures that OCD can easily clone a
/// target cluster and deploy it by simply using root itself.
///
/// Root also has access to the file exclusion feature. The user can specify a list of sparsity
/// rules to exclude certain files and directories from deployment.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
pub struct RootEntry {
    /// Deployment options.
    pub settings: RootEntrySettings,
}

impl RootEntry {
    /// Construct new root entry through builder.
    ///
    /// # Errors
    ///
    /// Will fail if configuration directory path cannot be determined.
    pub fn builder() -> Result<RootEntryBuilder> {
        RootEntryBuilder::new()
    }

    /// Use default settings for root entry.
    ///
    /// # Errors
    ///
    /// Will fail if configuration directory cannot be determined.
    pub fn try_default() -> Result<Self> {
        Ok(RootEntry {
            settings: RootEntrySettings {
                work_dir_alias: WorkDirAlias::new(config_dir()?),
                excluded: None,
            },
        })
    }
}

/// Builder for [`RootEntry`].
#[derive(Debug)]
pub struct RootEntryBuilder {
    settings: RootEntrySettings,
}

impl RootEntryBuilder {
    /// Construct new builder for [`RootEntry`].
    ///
    /// # Errors
    ///
    /// Will fail if configuration directory cannot be determined.
    pub fn new() -> Result<Self> {
        Ok(Self {
            settings: RootEntrySettings {
                work_dir_alias: WorkDirAlias::new(config_dir()?),
                excluded: None,
            },
        })
    }

    /// Deploy to standard configuration directory.
    ///
    /// # Errors
    ///
    /// - Will fail if configuration directory path cannot be determined.
    pub fn deploy_to_config_dir(mut self) -> Result<Self> {
        self.settings.work_dir_alias = WorkDirAlias::new(config_dir()?);
        Ok(self)
    }

    /// Deploy to home directory.
    ///
    /// # Errors
    ///
    /// - Will fail if home directory path cannot be determined.
    pub fn deploy_to_home_dir(mut self) -> Result<Self> {
        self.settings.work_dir_alias = WorkDirAlias::new(home_dir()?);
        Ok(self)
    }

    /// Set exclusion rules to exclude files from deployment for node entry.
    pub fn excluded(mut self, rules: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.settings.excluded = Some(rules.into_iter().map(Into::into).collect());
        self
    }

    /// Build new [`RootEntry`].
    pub fn build(self) -> RootEntry {
        RootEntry { settings: self.settings }
    }
}

/// Deployment options for root entry.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
pub struct RootEntrySettings {
    /// Working directory alias option.
    #[serde(deserialize_with = "deserialize_root_work_dir_alias")]
    pub work_dir_alias: WorkDirAlias,

    /// List of sparsity rules to exclude files from deployment.
    pub excluded: Option<Vec<String>>,
}

fn deserialize_root_work_dir_alias<'de, D>(deserializer: D) -> Result<WorkDirAlias, D::Error>
where
    D: Deserializer<'de>,
{
    let result: String = Deserialize::deserialize(deserializer)?;
    match result.as_str() {
        "config_dir" => Ok(WorkDirAlias::new(config_dir().map_err(serde::de::Error::custom)?)),
        "home_dir" => Ok(WorkDirAlias::new(home_dir().map_err(serde::de::Error::custom)?)),
        _ => Err(anyhow!("Invalid deployment option for root")).map_err(serde::de::Error::custom),
    }
}

/// Node entry of cluster.
///
/// A cluster typically contains a series of nodes. A given node entry can either be normal or
/// bare-alias. If the user does not specify a working directory alias, then their home directory
/// will be used as the default. All nodes contain a URL that points to a remote repository. This
/// URL is mainly used to tell OCD where to clone the node itself if it is missing in the
/// repository store.
///
/// Node entries have access to the file exclusion feature, and dependency deployment feature.
/// Thus, each node can have a listing of sparsity rules to exclude files and directories from
/// deployment, and a listing of other nodes as dependencies that must be deployed with the node
/// itself.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
pub struct NodeEntry {
    pub settings: NodeEntrySettings,
}

impl NodeEntry {
    /// Construct new node entry through builder.
    ///
    /// # Errors
    ///
    /// Will fail if default working directory alias cannot be determined.
    pub fn builder() -> Result<NodeEntryBuilder> {
        NodeEntryBuilder::new()
    }
}

/// Builder for [`NodeEntry`]
#[derive(Debug)]
pub struct NodeEntryBuilder {
    settings: NodeEntrySettings,
}

impl NodeEntryBuilder {
    /// Construct new empty builder for [`NodeEntry`].
    ///
    /// # Errors
    ///
    /// Will fail if default working directory alias cannot be determined.
    pub fn new() -> Result<Self> {
        Ok(Self {
            settings: NodeEntrySettings {
                deployment: NodeEntryDeployment {
                    kind: DeploymentKind::Normal,
                    work_dir_alias: WorkDirAlias::try_default()?,
                },
                url: String::default(),
                excluded: None,
                dependencies: None,
            },
        })
    }

    /// Set method of deployment for node entry.
    pub fn deployment(mut self, kind: DeploymentKind, work_dir_alias: WorkDirAlias) -> Self {
        self.settings.deployment = NodeEntryDeployment { kind, work_dir_alias };
        self
    }

    /// Set URL to clone node entry from.
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.settings.url = url.into();
        self
    }

    /// Set exclusion rules to exclude files from deployment for node entry.
    pub fn excluded(mut self, rules: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.settings.excluded = Some(rules.into_iter().map(Into::into).collect());
        self
    }

    /// Set dependencies to be deployed with node entry.
    pub fn dependencies(mut self, nodes: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.settings.dependencies = Some(nodes.into_iter().map(Into::into).collect());
        self
    }

    /// Build new [`NodeEntry`].
    pub fn build(self) -> NodeEntry {
        NodeEntry { settings: self.settings }
    }
}

/// Settings for node entry.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
pub struct NodeEntrySettings {
    /// Deployment method for node entry.
    #[serde(deserialize_with = "deserialize_node_deployment")]
    pub deployment: NodeEntryDeployment,

    /// URL to clone node entry from.
    pub url: String,

    /// List of sparisty rules to exclude files from deployment.
    pub excluded: Option<Vec<String>>,

    /// List of other nodes to be deployed as dependencies with this node entry.
    pub dependencies: Option<Vec<String>>,
}

/// Node deployment method.
///
/// Currently, there are only two kinds of node deployment:
///
/// 1. Normal deployment kind.
/// 2. Bare-alias deployment kind.
///
/// Normal deployment simply ensures that the node entry has been cloned into repository store.
/// Bare-alias deployment not only ensures that node entry has been cloned into repository store,
/// but is also properly deployed to target working directory alias.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
pub struct NodeEntryDeployment {
    /// Deployment kind.
    pub kind: DeploymentKind,

    /// Working directory alias to use.
    pub work_dir_alias: WorkDirAlias,
}

impl FromStr for NodeEntryDeployment {
    type Err = anyhow::Error;

    fn from_str(data: &str) -> Result<Self, Self::Err> {
        let (kind, work_dir_alias) = match data {
            "normal" => (DeploymentKind::Normal, WorkDirAlias::try_default()?),
            "bare_alias" => (DeploymentKind::BareAlias, WorkDirAlias::new(home_dir()?)),
            _ => return Err(anyhow!("Invalid deployment kind")),
        };

        Ok(NodeEntryDeployment { kind, work_dir_alias })
    }
}

struct NodeEntryDeploymentVisitor(PhantomData<fn() -> NodeEntryDeployment>);

impl<'de> Visitor<'de> for NodeEntryDeploymentVisitor {
    type Value = NodeEntryDeployment;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("string or map")
    }

    fn visit_str<E>(self, value: &str) -> Result<NodeEntryDeployment, E>
    where
        E: serde::de::Error,
    {
        FromStr::from_str(value).map_err(serde::de::Error::custom)
    }

    fn visit_map<M>(self, map: M) -> Result<NodeEntryDeployment, M::Error>
    where
        M: MapAccess<'de>,
    {
        Deserialize::deserialize(serde::de::value::MapAccessDeserializer::new(map))
    }
}

fn deserialize_node_deployment<'de, D>(deserializer: D) -> Result<NodeEntryDeployment, D::Error>
where
    D: Deserializer<'de>,
{
    deserializer.deserialize_any(NodeEntryDeploymentVisitor(PhantomData))
}

/// Variants of node deployment.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "snake_case")]
pub enum DeploymentKind {
    /// Node is normal, so make sure it got cloned.
    Normal,

    /// Node is bare-alias, make sure it got cloned, and is deployed to working directory alias.
    BareAlias,
}

impl DeploymentKind {
    pub fn is_bare_alias(&self) -> bool {
        match self {
            DeploymentKind::Normal => false,
            DeploymentKind::BareAlias => true,
        }
    }
}

/// Working directory alias path.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize)]
pub struct WorkDirAlias(pub(crate) PathBuf);

impl WorkDirAlias {
    /// Construct new working directory alias based on provided path.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self(path.into())
    }

    /// Try to use default path.
    ///
    /// Default path is user's home directory.
    ///
    /// # Errors
    ///
    /// - Will fail if user home directory cannot be determined.
    pub fn try_default() -> Result<Self> {
        Ok(Self(home_dir()?))
    }

    pub fn to_os_string(&self) -> OsString {
        OsString::from(self.0.to_string_lossy().into_owned())
    }
}

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

    use anyhow::Context;
    use pretty_assertions::assert_eq as pretty_assert_eq;
    use sealed_test::prelude::*;
    use simple_test_case::test_case;

    #[test_case(
        r#"
            [settings]
            work_dir_alias = "home_dir"
        "#,
        RootEntry {
            settings: RootEntrySettings {
                work_dir_alias: WorkDirAlias::new("some/path"),
                excluded: None,
            }
        };
        "home_dir"
    )]
    #[test_case(
        r#"
            [settings]
            work_dir_alias = "config_dir"
        "#,
        RootEntry {
            settings: RootEntrySettings {
                work_dir_alias: WorkDirAlias::new("some/path/.config/ocd"),
                excluded: None,
            }
        };
        "config_dir"
    )]
    #[sealed_test(env = [("HOME", "some/path"), ("XDG_CONFIG_HOME", "some/path/.config")])]
    fn root_entry_valid_work_dir_alias(config: &str, expect: RootEntry) -> Result<()> {
        let result: RootEntry = toml::de::from_str(config)?;
        pretty_assert_eq!(result, expect);
        Ok(())
    }

    #[test]
    fn root_entry_invalid_work_dir_alias() {
        let config = r#"
            [settings]
            work_dir_alias = "data_dir"
        "#;
        let result: Result<RootEntry> = toml::de::from_str(config).with_context(|| "should fail!");
        assert!(result.is_err());
    }

    #[test_case(
        r#"
            [settings]
            deployment = "normal"
            url = "https://some/url"
        "#,
        NodeEntry  {
            settings: NodeEntrySettings {
                deployment: NodeEntryDeployment {
                    kind: DeploymentKind::Normal,
                    work_dir_alias: WorkDirAlias::try_default()?,
                },
                url: "https://some/url".into(),
                excluded: None,
                dependencies: None,
            }
        };
        "str_normal"
    )]
    #[test_case(
        r#"
            [settings]
            deployment = "bare_alias"
            url = "https://some/url"
        "#,
        NodeEntry  {
            settings: NodeEntrySettings {
                deployment: NodeEntryDeployment {
                    kind: DeploymentKind::BareAlias,
                    work_dir_alias: WorkDirAlias::new("some/path"),
                },
                url: "https://some/url".into(),
                excluded: None,
                dependencies: None,
            }
        };
        "str_bare_alias"
    )]
    #[test_case(
        r#"
            [settings]
            deployment = { kind = "normal", work_dir_alias = "blah/blah" }
            url = "https://some/url"
        "#,
        NodeEntry  {
            settings: NodeEntrySettings {
                deployment: NodeEntryDeployment {
                    kind: DeploymentKind::Normal,
                    work_dir_alias: WorkDirAlias::new("blah/blah"),
                },
                url: "https://some/url".into(),
                excluded: None,
                dependencies: None,
            }
        };
        "map_normal"
    )]
    #[test_case(
        r#"
            [settings]
            deployment = { kind = "bare_alias", work_dir_alias = "blah/blah" }
            url = "https://some/url"
        "#,
        NodeEntry  {
            settings: NodeEntrySettings {
                deployment: NodeEntryDeployment {
                    kind: DeploymentKind::BareAlias,
                    work_dir_alias: WorkDirAlias::new("blah/blah"),
                },
                url: "https://some/url".into(),
                excluded: None,
                dependencies: None,
            }
        };
        "map_bare_alias"
    )]
    #[sealed_test(env = [("HOME", "some/path"), ("XDG_CONFIG_HOME", "some/path/.config")])]
    fn node_entry_valid_deployment(config: &str, expect: NodeEntry) -> Result<()> {
        let node: NodeEntry = toml::de::from_str(config)?;
        pretty_assert_eq!(node, expect);
        Ok(())
    }

    #[test_case(
        r#"
            [settings]
            deployment = "snafu"
            url = "https://some/url"
        "#;
        "invalid_str"
    )]
    #[test_case(
        r#"
            [settings]
            deployment = { kind = "snafu", work_dir_alias = "blah/blah" }
            url = "https://some/url"
        "#;
        "unknown_field"
    )]
    fn node_entry_invalid_deployment(config: &str) {
        let result: Result<NodeEntry> = toml::de::from_str(config).with_context(|| "should fail!");
        assert!(result.is_err());
    }
}