mind_tree/
forest.rs

1//! A forest is a set of trees, including:
2//!
3//! - A main tree.
4//! - Project trees (cwd-based).
5
6use crate::node::Tree;
7use serde::{Deserialize, Serialize};
8use std::{
9  collections::HashMap,
10  path::{Path, PathBuf},
11};
12
13#[derive(Debug, Serialize, Deserialize)]
14pub struct Forest {
15  /// The main tree.
16  tree: Tree,
17
18  /// CWD-based trees.
19  ///
20  /// The keys are absolute paths.
21  projects: HashMap<PathBuf, Tree>,
22}
23
24impl Forest {
25  /// Create a new empty [`Forest`].
26  ///
27  /// This function creates an empty main tree with the provided `name` and `icon`, and no CWD-based project is
28  /// initialized.
29  pub fn new(tree: Tree) -> Self {
30    Self {
31      tree,
32      projects: HashMap::new(),
33    }
34  }
35
36  /// Get the main [`Tree`].
37  pub fn main_tree(&self) -> &Tree {
38    &self.tree
39  }
40
41  /// Return all the trees with their corresponding CWD.
42  pub fn cwd_trees(&self) -> impl Iterator<Item = (&Path, &Tree)> {
43    self
44      .projects
45      .iter()
46      .map(|(cwd, tree)| (cwd.as_path(), tree))
47  }
48
49  /// Get a CWD-based [`Tree`].
50  pub fn cwd_tree(&self, cwd: impl AsRef<Path>) -> Option<&Tree> {
51    self.projects.get(cwd.as_ref())
52  }
53
54  /// Add a [`Tree`] for the given CWD.
55  pub fn add_cwd_tree(&mut self, cwd: impl Into<PathBuf>, tree: Tree) {
56    let _ = self.projects.insert(cwd.into(), tree);
57  }
58}