fresh-editor 0.1.74

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
Documentation
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use super::backend::{FsBackend, FsEntry, FsEntryType, FsMetadata};
use async_trait::async_trait;
use lru::LruCache;
use std::io;
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::fs;
use tokio::sync::RwLock;

/// Local filesystem backend with caching
pub struct LocalFsBackend {
    /// LRU cache for metadata to reduce syscalls
    metadata_cache: Arc<RwLock<LruCache<PathBuf, CachedMetadata>>>,
    /// How long to cache metadata before refreshing
    cache_duration: Duration,
}

#[derive(Clone)]
struct CachedMetadata {
    metadata: FsMetadata,
    cached_at: Instant,
}

impl LocalFsBackend {
    /// Create a new local filesystem backend with default cache settings
    pub fn new() -> Self {
        Self::with_cache_settings(1000, Duration::from_secs(5))
    }

    /// Create a backend with custom cache settings
    ///
    /// # Arguments
    ///
    /// * `cache_size` - Maximum number of metadata entries to cache
    /// * `cache_duration` - How long to cache metadata before refreshing
    pub fn with_cache_settings(cache_size: usize, cache_duration: Duration) -> Self {
        Self {
            metadata_cache: Arc::new(RwLock::new(LruCache::new(
                NonZeroUsize::new(cache_size).unwrap(),
            ))),
            cache_duration,
        }
    }

    /// Get metadata from cache if available and not stale
    async fn get_cached_metadata(&self, path: &Path) -> Option<FsMetadata> {
        let cache = self.metadata_cache.read().await;
        if let Some(cached) = cache.peek(path) {
            if cached.cached_at.elapsed() < self.cache_duration {
                return Some(cached.metadata.clone());
            }
        }
        None
    }

    /// Store metadata in cache
    async fn cache_metadata(&self, path: PathBuf, metadata: FsMetadata) {
        let mut cache = self.metadata_cache.write().await;
        cache.put(
            path,
            CachedMetadata {
                metadata,
                cached_at: Instant::now(),
            },
        );
    }

    /// Read metadata for a single path
    async fn read_metadata(&self, path: &Path) -> io::Result<FsMetadata> {
        // Check cache first
        if let Some(cached) = self.get_cached_metadata(path).await {
            return Ok(cached);
        }

        // Read from filesystem
        let std_metadata = fs::metadata(path).await?;
        let is_hidden = is_hidden_file(path);

        let metadata = FsMetadata::new()
            .with_size(std_metadata.len())
            .with_modified(
                std_metadata
                    .modified()
                    .ok()
                    .unwrap_or(std::time::UNIX_EPOCH),
            )
            .with_hidden(is_hidden)
            .with_readonly(std_metadata.permissions().readonly());

        // Cache it
        self.cache_metadata(path.to_path_buf(), metadata.clone())
            .await;

        Ok(metadata)
    }

    /// Determine entry type from metadata
    fn entry_type_from_metadata(metadata: &std::fs::Metadata) -> FsEntryType {
        if metadata.is_symlink() {
            FsEntryType::Symlink
        } else if metadata.is_dir() {
            FsEntryType::Directory
        } else {
            FsEntryType::File
        }
    }
}

impl Default for LocalFsBackend {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl FsBackend for LocalFsBackend {
    async fn read_dir(&self, path: &Path) -> io::Result<Vec<FsEntry>> {
        let mut entries = Vec::new();
        let mut read_dir = fs::read_dir(path).await?;

        while let Some(entry) = read_dir.next_entry().await? {
            let path = entry.path();
            let name = entry.file_name().to_string_lossy().into_owned();

            let entry_type = if let Ok(file_type) = entry.file_type().await {
                if file_type.is_symlink() {
                    FsEntryType::Symlink
                } else if file_type.is_dir() {
                    FsEntryType::Directory
                } else {
                    FsEntryType::File
                }
            } else {
                // If we can't determine type, assume file
                FsEntryType::File
            };

            entries.push(FsEntry::new(path, name, entry_type));
        }

        Ok(entries)
    }

    async fn get_metadata_batch(&self, paths: &[PathBuf]) -> Vec<io::Result<FsMetadata>> {
        // Spawn tasks to fetch metadata in parallel
        let tasks: Vec<_> = paths
            .iter()
            .map(|path| {
                let path = path.clone();
                let backend = self.clone();
                tokio::spawn(async move { backend.read_metadata(&path).await })
            })
            .collect();

        // Collect results
        let mut results = Vec::with_capacity(paths.len());
        for task in tasks {
            match task.await {
                Ok(Ok(metadata)) => results.push(Ok(metadata)),
                Ok(Err(e)) => results.push(Err(e)),
                Err(_) => {
                    results.push(Err(io::Error::new(io::ErrorKind::Other, "Task join error")))
                }
            }
        }

        results
    }

    async fn exists(&self, path: &Path) -> bool {
        fs::try_exists(path).await.unwrap_or(false)
    }

    async fn is_dir(&self, path: &Path) -> io::Result<bool> {
        let metadata = fs::metadata(path).await?;
        Ok(metadata.is_dir())
    }

    async fn get_entry(&self, path: &Path) -> io::Result<FsEntry> {
        let metadata = fs::metadata(path).await?;
        let name = path
            .file_name()
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Invalid path"))?
            .to_string_lossy()
            .into_owned();

        let entry_type = Self::entry_type_from_metadata(&metadata);
        let is_hidden = is_hidden_file(path);

        let fs_metadata = FsMetadata::new()
            .with_size(metadata.len())
            .with_modified(metadata.modified().ok().unwrap_or(std::time::UNIX_EPOCH))
            .with_hidden(is_hidden)
            .with_readonly(metadata.permissions().readonly());

        Ok(FsEntry::new(path.to_path_buf(), name, entry_type).with_metadata(fs_metadata))
    }

    async fn canonicalize(&self, path: &Path) -> io::Result<PathBuf> {
        fs::canonicalize(path).await
    }
}

// Clone implementation for LocalFsBackend to enable parallel operations
impl Clone for LocalFsBackend {
    fn clone(&self) -> Self {
        Self {
            metadata_cache: Arc::clone(&self.metadata_cache),
            cache_duration: self.cache_duration,
        }
    }
}

/// Check if a file is hidden (starts with . on Unix, or has hidden attribute on Windows)
fn is_hidden_file(path: &Path) -> bool {
    // Check for dot-prefix (works on all platforms)
    let is_dot_hidden = path
        .file_name()
        .and_then(|name| name.to_str())
        .map(|name| name.starts_with('.'))
        .unwrap_or(false);

    if is_dot_hidden {
        return true;
    }

    // On Windows, also check the hidden attribute
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;

        if let Ok(metadata) = std::fs::metadata(path) {
            return metadata.file_attributes() & FILE_ATTRIBUTE_HIDDEN != 0;
        }
    }

    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs as std_fs;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_read_dir() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create test files
        std_fs::write(temp_path.join("file1.txt"), "content1").unwrap();
        std_fs::write(temp_path.join("file2.txt"), "content2").unwrap();
        std_fs::create_dir(temp_path.join("subdir")).unwrap();

        let backend = LocalFsBackend::new();
        let entries = backend.read_dir(temp_path).await.unwrap();

        assert_eq!(entries.len(), 3);

        // Check that we have the expected entries
        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"file1.txt"));
        assert!(names.contains(&"file2.txt"));
        assert!(names.contains(&"subdir"));

        // Check types
        let subdir = entries.iter().find(|e| e.name == "subdir").unwrap();
        assert!(subdir.is_dir());

        let file1 = entries.iter().find(|e| e.name == "file1.txt").unwrap();
        assert!(file1.is_file());
    }

    #[tokio::test]
    async fn test_get_metadata_batch() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create test files
        std_fs::write(temp_path.join("file1.txt"), "content1").unwrap();
        std_fs::write(temp_path.join("file2.txt"), "content2").unwrap();

        let backend = LocalFsBackend::new();
        let paths = vec![temp_path.join("file1.txt"), temp_path.join("file2.txt")];

        let results = backend.get_metadata_batch(&paths).await;

        assert_eq!(results.len(), 2);
        assert!(results[0].is_ok());
        assert!(results[1].is_ok());

        let meta1 = results[0].as_ref().unwrap();
        assert_eq!(meta1.size, Some(8)); // "content1" is 8 bytes
    }

    #[tokio::test]
    async fn test_metadata_caching() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();
        let file_path = temp_path.join("test.txt");

        std_fs::write(&file_path, "content").unwrap();

        let backend = LocalFsBackend::with_cache_settings(10, Duration::from_secs(10));

        // First read - should populate cache
        let meta1 = backend.read_metadata(&file_path).await.unwrap();
        assert_eq!(meta1.size, Some(7));

        // Second read - should hit cache
        let meta2 = backend.read_metadata(&file_path).await.unwrap();
        assert_eq!(meta2.size, Some(7));

        // Verify cache was used (sizes should match)
        assert_eq!(meta1.size, meta2.size);
    }

    #[tokio::test]
    async fn test_exists() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();
        let file_path = temp_path.join("test.txt");

        let backend = LocalFsBackend::new();

        assert!(!backend.exists(&file_path).await);

        std_fs::write(&file_path, "content").unwrap();

        assert!(backend.exists(&file_path).await);
    }

    #[tokio::test]
    async fn test_is_dir() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();
        let file_path = temp_path.join("test.txt");
        let dir_path = temp_path.join("subdir");

        std_fs::write(&file_path, "content").unwrap();
        std_fs::create_dir(&dir_path).unwrap();

        let backend = LocalFsBackend::new();

        assert!(!backend.is_dir(&file_path).await.unwrap());
        assert!(backend.is_dir(&dir_path).await.unwrap());
    }

    #[tokio::test]
    async fn test_get_entry() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();
        let file_path = temp_path.join("test.txt");

        std_fs::write(&file_path, "content").unwrap();

        let backend = LocalFsBackend::new();
        let entry = backend.get_entry(&file_path).await.unwrap();

        assert_eq!(entry.name, "test.txt");
        assert!(entry.is_file());
        assert!(entry.metadata.is_some());

        let metadata = entry.metadata.unwrap();
        assert_eq!(metadata.size, Some(7));
    }

    #[tokio::test]
    async fn test_hidden_file_detection() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();
        let hidden_file = temp_path.join(".hidden");
        let normal_file = temp_path.join("visible.txt");

        std_fs::write(&hidden_file, "hidden").unwrap();
        std_fs::write(&normal_file, "visible").unwrap();

        let backend = LocalFsBackend::new();

        let hidden_entry = backend.get_entry(&hidden_file).await.unwrap();
        let normal_entry = backend.get_entry(&normal_file).await.unwrap();

        assert!(hidden_entry.metadata.as_ref().unwrap().is_hidden);
        assert!(!normal_entry.metadata.as_ref().unwrap().is_hidden);
    }

    #[tokio::test]
    async fn test_parallel_metadata_fetch() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        // Create 100 test files
        for i in 0..100 {
            std_fs::write(
                temp_path.join(format!("file{}.txt", i)),
                format!("content{}", i),
            )
            .unwrap();
        }

        let backend = LocalFsBackend::new();
        let paths: Vec<_> = (0..100)
            .map(|i| temp_path.join(format!("file{}.txt", i)))
            .collect();

        let start = Instant::now();
        let results = backend.get_metadata_batch(&paths).await;
        let duration = start.elapsed();

        assert_eq!(results.len(), 100);
        assert!(results.iter().all(|r| r.is_ok()));

        // Parallel should be reasonably fast (less than 1 second for 100 files)
        assert!(duration.as_secs() < 1);
    }

    #[test]
    fn test_is_hidden_file() {
        assert!(is_hidden_file(Path::new(".hidden")));
        assert!(is_hidden_file(Path::new("/path/to/.hidden")));
        assert!(!is_hidden_file(Path::new("visible.txt")));
        assert!(!is_hidden_file(Path::new("/path/to/visible.txt")));
    }
}