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
use once_cell::sync::OnceCell;
use std::{
    borrow::Cow,
    fs::FileType,
    path::{Path, PathBuf},
    sync::Arc,
    time::SystemTime,
};

use crate::{description::PkgInfo, normalize::NormalizePath, Error, RResult, Resolver};

#[derive(Debug, Default, Clone, Copy)]
pub struct EntryStat {
    /// `None` for non-existing file
    file_type: Option<FileType>,

    /// `None` for existing file but without system time.
    modified: Option<SystemTime>,
}

impl EntryStat {
    fn new(file_type: Option<FileType>, modified: Option<SystemTime>) -> Self {
        Self {
            file_type,
            modified,
        }
    }

    /// Returns `None` for non-existing file
    pub fn file_type(&self) -> Option<FileType> {
        self.file_type
    }

    /// Returns `None` for existing file but without system time.
    pub fn modified(&self) -> Option<SystemTime> {
        self.modified
    }

    fn stat(path: &Path) -> Self {
        if !path.is_absolute() {
            Self::new(None, None)
        } else if let Ok(meta) = path.metadata() {
            // This field might not be available on all platforms,
            // and will return an Err on platforms where it is not available.
            let modified = meta.modified().ok();
            Self::new(Some(meta.file_type()), modified)
        } else {
            Self::new(None, None)
        }
    }
}

#[derive(Debug)]
pub struct Entry {
    parent: Option<Arc<Entry>>,
    path: Box<Path>,
    pkg_info: Option<Arc<PkgInfo>>,
    stat: OnceCell<EntryStat>,
    // None: `self.path` is not a symlink
    symlink: OnceCell<Option<Arc<Path>>>,
}

impl Entry {
    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn parent(&self) -> Option<&Arc<Entry>> {
        self.parent.as_ref()
    }

    pub fn pkg_info(&self) -> Option<&Arc<PkgInfo>> {
        self.pkg_info.as_ref()
    }

    pub fn is_file(&self) -> bool {
        self.cached_stat()
            .file_type()
            .map_or(false, |ft| ft.is_file())
    }

    pub fn is_dir(&self) -> bool {
        self.cached_stat()
            .file_type()
            .map_or(false, |ft| ft.is_dir())
    }

    pub fn exists(&self) -> bool {
        self.cached_stat().file_type().is_some()
    }

    pub fn cached_stat(&self) -> EntryStat {
        *self.stat.get_or_init(|| EntryStat::stat(&self.path))
    }

    /// Returns the canonicalized path of `self.path` if it is a symlink.
    /// Returns None if `self.path` is not a symlink.
    pub fn symlink(&self) -> &Option<Arc<Path>> {
        self.symlink.get_or_init(|| {
            if self.path.read_link().is_err() {
                return None;
            }
            match dunce::canonicalize(&self.path) {
                Ok(symlink_path) => Some(Arc::from(symlink_path)),
                Err(_) => None,
            }
        })
    }
}

impl Resolver {
    pub(super) fn load_entry(&self, path: &Path) -> RResult<Arc<Entry>> {
        let key = path.normalize();
        if let Some(cached) = self.cache.entries.get(key.as_ref()) {
            Ok(cached.clone())
        } else {
            let entry = Arc::new(self.load_entry_uncached(&key)?);
            self.cache
                .entries
                .entry(key.into())
                .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 mut entry = Entry {
            parent: parent.clone(),
            path: path.into(),
            pkg_info: None,
            stat: OnceCell::default(),
            symlink: OnceCell::default(),
        };

        // Attempt to cache package.json
        let pkg_name = &self.options.description_file;
        let is_pkg_suffix = path.ends_with(pkg_name);
        if entry.is_dir() || is_pkg_suffix {
            let pkg_path = if is_pkg_suffix {
                Cow::Borrowed(path)
            } else {
                Cow::Owned(path.join(pkg_name))
            };
            match self
                .cache
                .fs
                .read_description_file(&pkg_path, EntryStat::default())
            {
                Ok(info) => {
                    entry.pkg_info.replace(info);
                }
                Err(error @ (Error::UnexpectedJson(_) | Error::UnexpectedValue(_))) => {
                    // Return bad json
                    return Err(error);
                }
                Err(Error::Io(_)) => {
                    // package.json does not exists
                }
                _ => unreachable!(),
            }
        }

        if entry.pkg_info().is_none() {
            if let Some(parent) = &parent {
                entry.pkg_info = parent.pkg_info.clone();
            }
        }

        Ok(entry)
    }

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

    #[must_use]
    pub fn get_dependency_from_entry(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {
        todo!("get_dependency_from_entry")
    }
}

#[test]
#[ignore]
fn dependency_test() {
    let case_path = super::test_helper::p(vec!["full", "a"]);
    let request = "package2";
    let resolver = Resolver::new(Default::default());
    resolver.resolve(&case_path, request).unwrap();
    let (file, missing) = resolver.get_dependency_from_entry();
    assert_eq!(file.len(), 3);
    assert_eq!(missing.len(), 1);
}