go_engine/vfs/
compound.rs

1// Copyright 2022 The Goscript Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5use crate::vfs::VirtualFs;
6use go_parser::Map;
7use std::io;
8use std::path::{Path, PathBuf};
9
10const ABS_PREFIX: &str = "__abs__";
11
12pub struct CompoundFs {
13    sub_fs: Map<String, Box<dyn VirtualFs>>,
14}
15
16impl CompoundFs {
17    pub fn new(sub_fs: Map<String, Box<dyn VirtualFs>>) -> Self {
18        Self { sub_fs }
19    }
20
21    fn to_inner(&self, path: &Path) -> io::Result<(&Box<dyn VirtualFs>, String, PathBuf)> {
22        let mut path = path.to_path_buf();
23        let fs_name = path
24            .components()
25            .next()
26            .map(|x| x.as_os_str().to_str().unwrap().to_owned())
27            .ok_or(io::Error::from(io::ErrorKind::NotFound))?;
28        let fs = self
29            .sub_fs
30            .get(&fs_name)
31            .ok_or(io::Error::from(io::ErrorKind::NotFound))?;
32        path = path.strip_prefix(&fs_name).unwrap().to_path_buf();
33        if let Ok(p) = path.strip_prefix(ABS_PREFIX) {
34            path = Path::new("/").join(p);
35        }
36        Ok((fs, fs_name, path))
37    }
38
39    fn to_outer(fs_name: &str, path: &Path) -> PathBuf {
40        let full_path = if path.is_absolute() {
41            format!("{}/{}{}", fs_name, ABS_PREFIX, path.to_string_lossy())
42        } else {
43            format!("{}/{}", fs_name, path.to_string_lossy())
44        };
45        PathBuf::from(full_path)
46    }
47}
48
49impl VirtualFs for CompoundFs {
50    fn read_file(&self, path: &Path) -> io::Result<String> {
51        let (fs, _, path) = self.to_inner(path)?;
52        fs.read_file(&path)
53    }
54
55    fn read_dir(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
56        let (fs, fs_name, path) = self.to_inner(path)?;
57        fs.read_dir(&path).map(|x| {
58            x.into_iter()
59                .map(|p| Self::to_outer(&fs_name, &p))
60                .collect()
61        })
62    }
63
64    fn is_file(&self, path: &Path) -> bool {
65        if let Ok((fs, _, path)) = self.to_inner(path) {
66            fs.is_file(&path)
67        } else {
68            false
69        }
70    }
71
72    fn is_dir(&self, path: &Path) -> bool {
73        if let Ok((fs, _, path)) = self.to_inner(path) {
74            fs.is_dir(&path)
75        } else {
76            false
77        }
78    }
79
80    fn canonicalize_path(&self, path: &PathBuf) -> io::Result<PathBuf> {
81        let (fs, name, inner) = self.to_inner(path)?;
82        let p = fs.canonicalize_path(&inner)?;
83        Ok(CompoundFs::to_outer(&name, &p))
84    }
85
86    fn strip_prefix<'a>(&'a self, path: &'a Path) -> &'a Path {
87        let path_str = path.to_str().unwrap();
88        let (_, suffix) = path_str.split_once('/').unwrap_or(("", path_str));
89        Path::new(suffix)
90    }
91
92    fn is_local(&self, path: &str) -> bool {
93        let local = |p: &str| p == "." || p == ".." || p.starts_with("./") || p.starts_with("../");
94        if local(path) {
95            return true;
96        }
97        let (_, path) = path.split_once('/').unwrap_or(("", path));
98        local(path)
99    }
100}