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
use std::{collections::HashMap, fs, path::PathBuf};

use anyhow::{anyhow, Context, Result};
use serde::Deserialize;

#[derive(Debug, Clone, Deserialize)]
pub struct Config {
    root: String,
    workspaces: HashMap<String, Workspace>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Workspace {
    projects: HashMap<String, Project>,     // make optional
    workspaces: HashMap<String, Workspace>, // make optional
}

#[derive(Debug, Clone, Deserialize)]
pub struct Project;

impl Config {
    pub fn from_config_file() -> Result<Self> {
        let home_dir = home::home_dir().expect("Could not determine home directory");
        let config_file = home_dir.clone().join(".config/workspaces/workspaces.yaml");
        let config_file = fs::read_to_string(config_file)
            .context("Tried reading ~/.config/workspaces/workspaces.yaml")?;

        Self::from_str(config_file.as_str())
    }

    pub(crate) fn from_str(contents: &str) -> Result<Self> {
        let home_dir = home::home_dir().expect("Could not determine home directory");

        serde_yaml::from_str(contents)
            .context("Tried loading config from ~/.config/workspaces/workspaces.yaml")
            .and_then(|c: Self| {
                if !c.root.starts_with("~") {
                    return Ok(c)
                }
                let mut c = c;
                c.root = home_dir
                    .into_os_string()
                    .into_string()
                    .map_err(|err| anyhow!("Error: {:?}", err))
                    .context("Something unexpected happened")?;
                Ok(c)
            })
    }

    pub fn collect_workspace_paths(&self) -> Vec<PathBuf> {
        let parent = PathBuf::from(self.root.clone());

        self.workspaces
            .iter()
            .map(|(name, ws)| {
                let path = parent.clone().join(name);
                let mut nested = ws.collect_workspace_paths(path.clone());
                nested.push(path);
                nested
            })
            .collect::<Vec<Vec<PathBuf>>>()
            .concat()
    }

    pub fn collect_project_paths(&self) -> Vec<PathBuf> {
        let parent = PathBuf::from(self.root.clone());

        self.workspaces
            .iter()
            .map(|(name, ws)| {
                let path = parent.clone().join(name);
                ws.collect_project_paths(path.clone())
            })
            .collect::<Vec<Vec<PathBuf>>>()
            .concat()
    }
}

impl Workspace {
    pub fn collect_workspace_paths(&self, parent: PathBuf) -> Vec<PathBuf> {
        self.workspaces
            .iter()
            .map(|(name, ws)| {
                let path = parent.clone().join(name);
                let mut nested = ws.collect_workspace_paths(path.clone());
                nested.push(path);
                nested
            })
            .collect::<Vec<Vec<PathBuf>>>()
            .concat()
    }

    pub fn collect_project_paths(&self, parent: PathBuf) -> Vec<PathBuf> {
        let projects = self
            .projects
            .iter()
            .map(|(name, _)| parent.clone().join(name))
            .collect::<Vec<PathBuf>>();

        let nested_projects = self
            .workspaces
            .iter()
            .map(|(name, ws)| {
                let path = parent.clone().join(name);
                ws.collect_project_paths(path.clone())
            })
            .collect::<Vec<Vec<PathBuf>>>()
            .concat();

        vec![projects, nested_projects].concat()
    }
}

#[cfg(test)]
mod should {

    use std::path::PathBuf;

    use rstest::*;

    #[rstest]
    fn list_workspaces() {
        let contents = r#"---
root: /some/root
workspaces:
  w0:
    projects:
      p0:
    workspaces:
      w1:
        projects:
          p1:
        workspaces:
          w2:
            projects:
              p2:
            workspaces:
              w3:
                projects:
                workspaces:
"#;

        let config = super::Config::from_str(contents);

        assert!(config.is_ok());

        let config = config.unwrap();

        let mut workspaces = config.collect_workspace_paths();

        assert_eq!(
            workspaces.sort(),
            vec![
                PathBuf::from("/some/root/w0"),
                PathBuf::from("/some/root/w0/w1"),
                PathBuf::from("/some/root/w0/w1/w2"),
                PathBuf::from("/some/root/w0/w1/w2/w3"),
            ].sort()
        );
    }

    #[rstest]
    fn list_projects() {
        let contents = r#"---
root: /some/root
workspaces:
  w0:
    projects:
      p0:
    workspaces:
      w1:
        projects:
          p1:
        workspaces:
          w2:
            projects:
              p2:
            workspaces:
              w3:
                projects:
                workspaces:
"#;

        let config = super::Config::from_str(contents);

        assert!(config.is_ok());

        let config = config.unwrap();

        let mut projects = config.collect_project_paths();

        assert_eq!(
            projects.sort(),
            vec![
                PathBuf::from("/some/root/w0/p0"),
                PathBuf::from("/some/root/w0/w1/p1"),
                PathBuf::from("/some/root/w0/w1/w2/p2"),
            ].sort()
        );
    }
}