darklua 0.19.0

Transform Lua scripts
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use std::{
    collections::HashMap,
    fs::{self, File},
    io::{self, BufWriter, ErrorKind as IOErrorKind, Write},
    iter,
    path::{Path, PathBuf},
    str::Utf8Error,
    sync::{Arc, Mutex},
};

use crate::utils::normalize_path;

#[derive(Debug, Clone)]
enum Source {
    FileSystem,
    Memory(Arc<Mutex<HashMap<PathBuf, Vec<u8>>>>),
}

impl Source {
    pub fn exists(&self, location: &Path) -> ResourceResult<bool> {
        match self {
            Self::FileSystem => Ok(location.exists()),
            Self::Memory(data) => Ok(data.lock().unwrap().contains_key(&normalize_path(location))),
        }
    }

    pub fn is_directory(&self, location: &Path) -> ResourceResult<bool> {
        let is_directory = match self {
            Source::FileSystem => self.exists(location)? && location.is_dir(),
            Source::Memory(data) => {
                let data = data.lock().unwrap();
                let location = normalize_path(location);

                data.iter()
                    .any(|(path, _content)| path != &location && path.starts_with(&location))
            }
        };
        Ok(is_directory)
    }

    pub fn is_file(&self, location: &Path) -> ResourceResult<bool> {
        let is_file = match self {
            Source::FileSystem => self.exists(location)? && location.is_file(),
            Source::Memory(data) => {
                let data = data.lock().unwrap();
                let location = normalize_path(location);

                data.contains_key(&location)
            }
        };
        Ok(is_file)
    }

    pub fn get(&self, location: &Path) -> ResourceResult<String> {
        self.get_bytes(location).and_then(|bytes| {
            String::from_utf8(bytes)
                .map_err(|err| ResourceError::expected_utf8(location, err.utf8_error()))
        })
    }

    fn get_bytes(&self, location: &Path) -> ResourceResult<Vec<u8>> {
        match self {
            Self::FileSystem => fs::read(location).map_err(|err| match err.kind() {
                IOErrorKind::NotFound => ResourceError::not_found(location),
                _ => ResourceError::io_error(location, err),
            }),
            Self::Memory(data) => {
                let data = data.lock().unwrap();
                let location = normalize_path(location);

                data.get(&location)
                    .cloned()
                    .ok_or_else(|| ResourceError::not_found(location))
            }
        }
    }

    pub fn write(&self, location: &Path, content: &str) -> ResourceResult<()> {
        self.write_bytes(location, content.as_bytes())
    }

    fn write_bytes(&self, location: &Path, content: &[u8]) -> ResourceResult<()> {
        match self {
            Self::FileSystem => {
                if let Some(parent) = location.parent() {
                    fs::create_dir_all(parent)
                        .map_err(|err| ResourceError::io_error(parent, err))?;
                };

                let file =
                    File::create(location).map_err(|err| ResourceError::io_error(location, err))?;

                let mut file = BufWriter::new(file);
                file.write_all(content)
                    .map_err(|err| ResourceError::io_error(location, err))
            }
            Self::Memory(data) => {
                let mut data = data.lock().unwrap();
                data.insert(normalize_path(location), content.to_vec());
                Ok(())
            }
        }
    }

    pub fn walk(&self, location: &Path) -> impl Iterator<Item = PathBuf> {
        match self {
            Self::FileSystem => Box::new(walk_file_system(location.to_path_buf()))
                as Box<dyn Iterator<Item = PathBuf>>,
            Self::Memory(data) => {
                let data = data.lock().unwrap();
                let location = normalize_path(location);
                let mut paths: Vec<_> = data.keys().map(normalize_path).collect();
                paths.retain(|path| path.starts_with(&location));

                Box::new(paths.into_iter())
            }
        }
    }

    fn walk_all(&self, location: &Path) -> impl Iterator<Item = ResourceContent> {
        match self {
            Self::FileSystem => Box::new(walk_all_file_system(location.to_path_buf()))
                as Box<dyn Iterator<Item = ResourceContent>>,
            Self::Memory(data) => {
                let data = data.lock().unwrap();
                let location = normalize_path(location);
                let mut paths: Vec<_> = data.keys().map(normalize_path).collect();
                paths.retain(|path| path.starts_with(&location));

                Box::new(paths.into_iter().map(ResourceContent::File))
            }
        }
    }

    fn is_empty_directory(&self, location: &Path) -> ResourceResult<bool> {
        if !self.is_directory(location)? {
            return Ok(false);
        }

        match self {
            Self::FileSystem => match location.read_dir() {
                Ok(read_dir) => {
                    for entry in read_dir {
                        match entry {
                            Ok(_) => return Ok(false),
                            Err(err) if err.kind() == io::ErrorKind::NotFound => {}
                            Err(err) => {
                                log::warn!(
                                    "unable to read directory entry `{}`: {}",
                                    location.display(),
                                    err
                                );
                                return Ok(false);
                            }
                        }
                    }

                    Ok(true)
                }
                Err(err) => {
                    log::warn!("unable to read directory `{}`: {}", location.display(), err);
                    Ok(false)
                }
            },
            Self::Memory(_data) => Ok(false),
        }
    }

    fn remove(&self, location: &Path) -> Result<(), ResourceError> {
        match self {
            Self::FileSystem => {
                if !self.exists(location)? {
                    Ok(())
                } else if self.is_file(location)? {
                    fs::remove_file(location).map_err(|err| ResourceError::io_error(location, err))
                } else if self.is_directory(location)? {
                    fs::remove_dir_all(location)
                        .map_err(|err| ResourceError::io_error(location, err))
                } else {
                    Ok(())
                }
            }
            Self::Memory(data) => {
                if self.is_file(location)? {
                    let mut data = data.lock().unwrap();
                    data.remove(&normalize_path(location));
                } else if self.is_directory(location)? {
                    let mut data = data.lock().unwrap();
                    let location = normalize_path(location);
                    data.retain(|path, _| !path.starts_with(&location));
                }

                Ok(())
            }
        }
    }
}

fn walk_all_file_system(location: PathBuf) -> impl Iterator<Item = ResourceContent> {
    let mut unknown_paths = vec![location];
    let mut entries = Vec::new();
    let mut dir_entries = Vec::new();

    iter::from_fn(move || loop {
        if let Some(location) = unknown_paths.pop() {
            match location.metadata() {
                Ok(metadata) => {
                    if metadata.is_file() {
                        entries.push(ResourceContent::File(location.to_path_buf()));
                    } else if metadata.is_dir() {
                        entries.push(ResourceContent::Directory(location.to_path_buf()));
                        dir_entries.push(location.to_path_buf());
                    } else if metadata.is_symlink() {
                        log::warn!("unexpected symlink `{}` not followed", location.display());
                    } else {
                        log::warn!(
                            concat!(
                                "path `{}` points to an unexpected location that is not a ",
                                "file, not a directory and not a symlink"
                            ),
                            location.display()
                        );
                    };
                }
                Err(err) => {
                    log::warn!(
                        "unable to read metadata from file `{}`: {}",
                        location.display(),
                        err
                    );
                }
            }
        } else if let Some(dir_location) = dir_entries.pop() {
            match dir_location.read_dir() {
                Ok(read_dir) => {
                    for entry in read_dir {
                        match entry {
                            Ok(entry) => {
                                unknown_paths.push(entry.path());
                            }
                            Err(err) => {
                                log::warn!(
                                    "unable to read directory entry `{}`: {}",
                                    dir_location.display(),
                                    err
                                );
                            }
                        }
                    }
                }
                Err(err) => {
                    log::warn!(
                        "unable to read directory `{}`: {}",
                        dir_location.display(),
                        err
                    );
                }
            }
        } else if let Some(path) = entries.pop() {
            break Some(path);
        } else {
            break None;
        }
    })
}

fn walk_file_system(location: PathBuf) -> impl Iterator<Item = PathBuf> {
    walk_all_file_system(location).filter_map(|content| match content {
        ResourceContent::File(path) => Some(path),
        ResourceContent::Directory(_) => None,
    })
}

/// A resource manager for handling file operations.
///
/// This struct provides an abstraction over file system operations, allowing
/// operations to be performed either on the actual file system or in memory.
/// It handles reading, writing, and managing files and directories.
#[derive(Debug, Clone)]
pub struct Resources {
    source: Source,
}

impl Resources {
    /// Creates a new resource manager that operates on the file system.
    pub fn from_file_system() -> Self {
        Self {
            source: Source::FileSystem,
        }
    }

    /// Creates a new resource manager that operates in memory.
    ///
    /// This is useful for testing or when you want to process files without
    /// writing to disk.
    pub fn from_memory() -> Self {
        Self {
            source: Source::Memory(Arc::new(Mutex::new(HashMap::new()))),
        }
    }

    /// Collects all files in the specified location. Deprecated in favor of [Self::walk].
    #[deprecated(since = "0.19.0", note = "use `Resources::walk(location)` instead")]
    pub fn collect_work(&self, location: impl AsRef<Path>) -> impl Iterator<Item = PathBuf> {
        self.source.walk(location.as_ref())
    }

    /// Checks if a path exists.
    pub fn exists(&self, location: impl AsRef<Path>) -> ResourceResult<bool> {
        self.source.exists(location.as_ref())
    }

    /// Checks if a path is a directory.
    pub fn is_directory(&self, location: impl AsRef<Path>) -> ResourceResult<bool> {
        self.source.is_directory(location.as_ref())
    }

    /// Checks if a path is a file.
    pub fn is_file(&self, location: impl AsRef<Path>) -> ResourceResult<bool> {
        self.source.is_file(location.as_ref())
    }

    /// Reads the contents of a file.
    pub fn get(&self, location: impl AsRef<Path>) -> ResourceResult<String> {
        self.source.get(location.as_ref())
    }

    /// Reads the contents of a file as bytes.
    pub fn get_bytes(&self, location: impl AsRef<Path>) -> ResourceResult<Vec<u8>> {
        self.source.get_bytes(location.as_ref())
    }

    /// Writes content to a file.
    pub fn write(&self, location: impl AsRef<Path>, content: &str) -> ResourceResult<()> {
        self.source.write(location.as_ref(), content)
    }

    /// Writes content to a file as bytes.
    pub fn write_bytes(&self, location: impl AsRef<Path>, content: &[u8]) -> ResourceResult<()> {
        self.source.write_bytes(location.as_ref(), content)
    }

    /// Removes a file or directory.
    pub fn remove(&self, location: impl AsRef<Path>) -> ResourceResult<()> {
        self.source.remove(location.as_ref())
    }

    /// Walks through all files in a directory.
    pub fn walk(&self, location: impl AsRef<Path>) -> impl Iterator<Item = PathBuf> {
        self.source.walk(location.as_ref())
    }

    /// Walks through all files and directories in a directory.
    pub(crate) fn walk_all(
        &self,
        location: impl AsRef<Path>,
    ) -> impl Iterator<Item = ResourceContent> {
        self.source.walk_all(location.as_ref())
    }

    pub(crate) fn is_empty_directory(&self, location: impl AsRef<Path>) -> ResourceResult<bool> {
        self.source.is_empty_directory(location.as_ref())
    }
}

pub(crate) enum ResourceContent {
    File(PathBuf),
    Directory(PathBuf),
}

/// An error that can occur during operations on [`Resource`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceError {
    /// The requested resource was not found.
    NotFound(PathBuf),
    /// The requested resource is expected to be valid UTF-8, but is not.
    ExpectedUtf8 {
        path: PathBuf,
        utf8_error: Utf8Error,
    },
    /// An I/O error occurred while accessing the resource.
    IO { path: PathBuf, error: String },
}

impl ResourceError {
    pub(crate) fn not_found(path: impl Into<PathBuf>) -> Self {
        Self::NotFound(path.into())
    }

    pub(crate) fn expected_utf8(path: impl Into<PathBuf>, utf8_error: Utf8Error) -> Self {
        Self::ExpectedUtf8 {
            path: path.into(),
            utf8_error,
        }
    }

    pub(crate) fn io_error(path: impl Into<PathBuf>, error: io::Error) -> Self {
        Self::IO {
            path: path.into(),
            error: error.to_string(),
        }
    }
}

/// A type alias for `Result<T, ResourceError>`.
type ResourceResult<T> = Result<T, ResourceError>;

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

    fn any_path() -> &'static Path {
        Path::new("test.lua")
    }

    const ANY_CONTENT: &str = "return true";

    mod memory {
        use std::iter::FromIterator;

        use super::*;

        fn new() -> Resources {
            Resources::from_memory()
        }

        #[test]
        fn not_created_file_does_not_exist() {
            assert_eq!(new().exists(any_path()), Ok(false));
        }

        #[test]
        fn created_file_exists() {
            let resources = new();
            resources.write(any_path(), ANY_CONTENT).unwrap();

            assert_eq!(resources.exists(any_path()), Ok(true));
        }

        #[test]
        fn created_file_is_removed_exists() {
            let resources = new();
            resources.write(any_path(), ANY_CONTENT).unwrap();

            resources.remove(any_path()).unwrap();

            assert_eq!(resources.exists(any_path()), Ok(false));
        }

        #[test]
        fn created_file_exists_is_a_file() {
            let resources = new();
            resources.write(any_path(), ANY_CONTENT).unwrap();

            assert_eq!(resources.is_file(any_path()), Ok(true));
        }

        #[test]
        fn created_file_exists_is_not_a_directory() {
            let resources = new();
            resources.write(any_path(), ANY_CONTENT).unwrap();

            assert_eq!(resources.is_directory(any_path()), Ok(false));
        }

        #[test]
        fn read_content_of_created_file() {
            let resources = new();
            resources.write(any_path(), ANY_CONTENT).unwrap();

            assert_eq!(resources.get(any_path()), Ok(ANY_CONTENT.to_string()));
        }

        #[test]
        fn collect_work_contains_created_files() {
            let resources = new();
            resources.write("src/test.lua", ANY_CONTENT).unwrap();

            assert_eq!(
                Vec::from_iter(resources.walk("src")),
                vec![PathBuf::from("src/test.lua")]
            );
        }
    }
}