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

use crate::{Error, LogixVfs};

#[derive(Debug)]
pub struct RelFs {
    root: PathBuf,
    cur_dir: PathBuf,
}

impl RelFs {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            cur_dir: PathBuf::new(),
        }
    }

    pub fn chdir(&mut self, path: impl AsRef<Path>) -> Result<&Path, Error> {
        self.cur_dir = self.resolve_path(true, path)?;
        Ok(&self.cur_dir)
    }

    fn resolve_path(&self, relative: bool, path: impl AsRef<Path>) -> Result<PathBuf, Error> {
        use std::path::Component;

        let path = path.as_ref();
        let mut ret = if relative {
            self.cur_dir.clone()
        } else {
            self.root.join(&self.cur_dir)
        };

        let mut level = self.cur_dir.components().count();

        for cur in path.components() {
            match cur {
                Component::Normal(name) => {
                    level += 1;
                    ret.push(name);
                }
                Component::RootDir => {
                    while level > 0 {
                        level -= 1;
                        ret.pop();
                    }
                }
                Component::CurDir => {}
                Component::ParentDir => {
                    if level == 0 {
                        return Err(Error::PathOutsideBounds {
                            path: path.to_path_buf(),
                        });
                    }
                    level -= 1;
                    ret.pop();
                }
                Component::Prefix(prefix) => {
                    // NOTE(2024.02): Should never happen on platforms other than Windows
                    return Err(Error::Other(format!(
                        "Unknown prefix {:?}",
                        prefix.as_os_str()
                    )));
                }
            }
        }

        Ok(ret)
    }
}

pub struct ReadDir {
    path: PathBuf,
    prefix: PathBuf,
    it: std::fs::ReadDir,
}

impl Iterator for ReadDir {
    type Item = Result<PathBuf, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        Some(match self.it.next()? {
            Ok(entry) => {
                let full_path = entry.path();
                full_path
                    .strip_prefix(&self.prefix)
                    .map_err(|e| {
                        // NOTE(2024.02): This should not happen, at least I don't know how to trigger it
                        Error::Other(format!(
                            "Failed to strip prefix {:?} off {full_path:?}: {e}",
                            self.prefix
                        ))
                    })
                    .map(|p| p.to_path_buf())
            }
            Err(e) => Err(Error::from_io(self.path.clone(), e)),
        })
    }
}

impl LogixVfs for RelFs {
    type RoFile = File;
    type ReadDir = ReadDir;

    fn canonicalize_path(&self, path: &Path) -> Result<PathBuf, Error> {
        self.resolve_path(true, path)
    }

    fn open_file(&self, path: &Path) -> Result<Self::RoFile, Error> {
        let full_path = self.resolve_path(false, path)?;
        File::open(full_path).map_err(|e| Error::from_io(path.to_path_buf(), e))
    }

    fn read_dir(&self, path: &Path) -> Result<Self::ReadDir, Error> {
        let full_path = self.resolve_path(false, path)?;
        let it = full_path
            .read_dir()
            .map_err(|e| Error::from_io(path.to_path_buf(), e))?;
        Ok(ReadDir {
            path: path.to_path_buf(),
            prefix: full_path,
            it,
        })
    }
}

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

    type TestCase<'a> = &'a [(Option<(&'a str, &'a str)>, &'a [&'a str], &'a str, &'a str)];

    static PATHS_TO_TEST: TestCase = &[
        (
            None,
            &[
                ".config/awesome-app/config.toml",
                ".config/./awesome-app/./config.toml",
            ],
            "/home/zeldor/.config/awesome-app/config.toml",
            ".config/awesome-app/config.toml",
        ),
        (
            None,
            &[".config/./awesome-app/../config.toml"],
            "/home/zeldor/.config/config.toml",
            ".config/config.toml",
        ),
        (
            Some((".config", ".config")),
            &["awesome-app"],
            "/home/zeldor/.config/awesome-app",
            ".config/awesome-app",
        ),
        (
            None,
            &["../awesome-app"],
            "/home/zeldor/awesome-app",
            "awesome-app",
        ),
        (
            Some(("awesome-app", ".config/awesome-app")),
            &[
                "config.toml",
                "./config.toml",
                "/.config/awesome-app/config.toml",
            ],
            "/home/zeldor/.config/awesome-app/config.toml",
            ".config/awesome-app/config.toml",
        ),
        (
            None,
            &["../config.toml"],
            "/home/zeldor/.config/config.toml",
            ".config/config.toml",
        ),
        (None, &["/.bashrc"], "/home/zeldor/.bashrc", ".bashrc"),
    ];

    #[test]
    fn basics() {
        let mut fs = RelFs::new("/home/zeldor");

        for &(chdir, paths, if_full, if_relative) in PATHS_TO_TEST {
            if let Some((chdir, rel_after)) = chdir {
                assert_eq!(fs.chdir(chdir), Ok(Path::new(rel_after)), "{chdir:?}");
            }
            for path in paths {
                assert_eq!(
                    fs.resolve_path(false, path),
                    Ok(PathBuf::from(if_full)),
                    "{path:?}"
                );
                assert_eq!(
                    fs.resolve_path(true, path),
                    Ok(PathBuf::from(if_relative)),
                    "{path:?}"
                );
            }
        }
    }

    #[test]
    fn errors() {
        let mut fs = RelFs::new("src");

        assert_eq!(
            fs.canonicalize_path("../test".as_ref()),
            Err(Error::PathOutsideBounds {
                path: "../test".into()
            })
        );

        assert_eq!(
            fs.canonicalize_path("test/../test/../../test".as_ref()),
            Err(Error::PathOutsideBounds {
                path: "test/../test/../../test".into()
            })
        );

        assert_eq!(fs.open_file("lib.rs".as_ref()).err(), None);
        assert_eq!(
            fs.open_file("not-lib.rs".as_ref()).err(),
            Some(Error::NotFound {
                path: "not-lib.rs".into()
            })
        );
        assert_eq!(
            fs.open_file("../outside.txt".as_ref()).err(),
            Some(Error::PathOutsideBounds {
                path: "../outside.txt".into()
            })
        );

        assert_eq!(
            fs.chdir("../outside").err(),
            Some(Error::PathOutsideBounds {
                path: "../outside".into()
            })
        );

        assert_eq!(
            fs.read_dir("../outside".as_ref()).err(),
            Some(Error::PathOutsideBounds {
                path: "../outside".into()
            })
        );

        assert_eq!(
            fs.read_dir("lib.rs".as_ref()).err(),
            Some(Error::NotADirectory {
                path: "lib.rs".into()
            })
        );
        assert_eq!(
            fs.read_dir("not-lib.rs".as_ref()).err(),
            Some(Error::NotFound {
                path: "not-lib.rs".into()
            })
        );
    }
}