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
use std::{
    path::{Path, PathBuf},
    sync::{Arc, RwLock},
    time::SystemTime,
};

use crate::{
    description::{PkgInfo, PkgJSON},
    Error, RResult, Resolver,
};
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
#[cfg(windows)]
use std::os::windows::ffi::OsStrExt;

#[derive(Debug, Clone)]
pub enum EntryKind {
    File,
    Dir,
    NonExist,
    Unknown,
}

impl EntryKind {
    pub fn is_file(&self) -> bool {
        matches!(self, EntryKind::File)
    }

    pub fn is_dir(&self) -> bool {
        matches!(self, EntryKind::Dir)
    }
}

#[derive(Debug, Clone)]
pub struct EntryStat {
    pub kind: EntryKind,
    pub mtime: Option<SystemTime>,
}

impl EntryStat {
    pub fn stat(path: &Path) -> std::io::Result<Self> {
        let stat = if let Ok(meta) = std::fs::metadata(path) {
            let kind = if meta.is_file() {
                EntryKind::File
            } else if meta.is_dir() {
                EntryKind::Dir
            } else {
                EntryKind::Unknown
            };
            let mtime = Some(meta.modified()?);
            EntryStat { kind, mtime }
        } else {
            EntryStat {
                kind: EntryKind::NonExist,
                mtime: None,
            }
        };
        Ok(stat)
    }
}

#[derive(Debug)]
pub struct Entry {
    pub parent: Option<Arc<Entry>>,
    path: PathBuf,
    pub pkg_info: Option<Arc<PkgInfo>>,
    stat: RwLock<Option<EntryStat>>,
    symlink: RwLock<Option<PathBuf>>,
}

impl Entry {
    pub fn symlink(&self) -> std::io::Result<PathBuf> {
        if let Some(symlink) = self.symlink.read().unwrap().as_ref() {
            return Ok(symlink.to_path_buf());
        }
        let real_path = std::fs::canonicalize(&self.path)?;
        let mut writer = self.symlink.write().unwrap();
        *writer = Some(real_path.clone());
        Ok(real_path)
    }

    pub fn is_file(&self) -> bool {
        if let Some(stat) = self.stat.read().unwrap().as_ref() {
            return stat.kind.is_file();
        }
        if let Ok(stat) = EntryStat::stat(&self.path) {
            let is_file = stat.kind.is_file();
            let mut writer = self.stat.write().unwrap();
            *writer = Some(stat);
            is_file
        } else {
            false
        }
    }

    pub fn is_dir(&self) -> bool {
        if let Some(stat) = self.stat.read().unwrap().as_ref() {
            return stat.kind.is_dir();
        }
        if let Ok(stat) = EntryStat::stat(&self.path) {
            let is_dir = stat.kind.is_dir();
            let mut writer = self.stat.write().unwrap();
            *writer = Some(stat);
            is_dir
        } else {
            false
        }
    }

    #[cfg(windows)]
    fn has_trailing_slash(p: &Path) -> bool {
        let last = p.as_os_str().encode_wide().last();
        last == Some(b'\\' as u16) || last == Some(b'/' as u16)
    }
    #[cfg(unix)]
    fn has_trailing_slash(p: &Path) -> bool {
        p.as_os_str().as_bytes().last() == Some(&b'/')
    }

    pub fn path_to_key(path: &Path) -> (PathBuf, bool) {
        (path.to_path_buf(), Self::has_trailing_slash(path))
    }
}

impl Resolver {
    pub(super) fn load_entry(&self, path: &Path) -> RResult<Arc<Entry>> {
        let key = Entry::path_to_key(path);
        if let Some(cached) = self.entries.get(&key) {
            Ok(cached.clone())
        } else {
            // TODO: how to mutex that?
            let entry = Arc::new(self.load_entry_uncached(path)?);
            self.entries.entry(key).or_insert(entry.clone());
            Ok(entry)
        }
    }

    fn load_entry_uncached(&self, path: &Path) -> RResult<Entry> {
        let parent = if let Some(parent) = path.parent() {
            let entry = self.load_entry(parent)?;
            Some(entry)
        } else {
            None
        };
        let path = path.to_path_buf();
        let pkg_file_name = &self.options.description_file;
        let maybe_pkg_path = path.join(pkg_file_name);
        let pkg_file_stat = EntryStat::stat(&maybe_pkg_path).map_err(Error::Io)?;
        let pkg_info = if pkg_file_stat.kind.is_file() {
            let content = self
                .cache
                .fs
                .read_file(&maybe_pkg_path, &pkg_file_stat)
                .map_err(Error::Io)?;
            let pkg_json = if let Some(cached) = self.cache.pkg_json.get(&content) {
                cached.clone()
            } else {
                Arc::new(PkgJSON::parse(&content, &maybe_pkg_path)?)
            };
            let dir_path = path.clone();
            self.cache.pkg_json.insert(content, pkg_json.clone());
            let pkg_info = Arc::new(PkgInfo {
                json: pkg_json,
                dir_path,
            });
            Some(pkg_info)
        } else if let Some(parent) = &parent {
            parent.pkg_info.clone()
        } else {
            None
        };

        let need_stat = if let Some(info) = &pkg_info {
            // Is path pointed xxx.package.json ?
            // if `true`, then use above stats
            // else return `!true` means stat is None.
            let is_pkg_file = info.dir_path.join(&pkg_file_name).eq(&path);
            !is_pkg_file
        } else {
            true
        };

        let stat = RwLock::new(if need_stat { None } else { Some(pkg_file_stat) });
        let symlink = RwLock::new(None);
        Ok(Entry {
            parent,
            path,
            pkg_info,
            stat,
            symlink,
        })
    }

    // TODO: should put entries as a parament.
    pub fn clear_entries(&self) {
        self.entries.clear();
    }
}