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
use std::{fs::Permissions, os::unix::fs::PermissionsExt, path::Path};

use async_trait::async_trait;
use tokio::io::AsyncWriteExt;

use super::{FileSystem, FileSystemError, FileSystemResult};

#[derive(Default, Debug, Clone)]
pub struct LocalFileSystem;

#[async_trait]
impl FileSystem for LocalFileSystem {
    async fn create_dir<P>(&self, path: P) -> FileSystemResult<()>
    where
        P: AsRef<Path> + Send,
    {
        tokio::fs::create_dir(path).await.map_err(Into::into)
    }

    async fn create_dir_all<P>(&self, path: P) -> FileSystemResult<()>
    where
        P: AsRef<Path> + Send,
    {
        tokio::fs::create_dir_all(path).await.map_err(Into::into)
    }

    async fn read<P>(&self, path: P) -> FileSystemResult<Vec<u8>>
    where
        P: AsRef<Path> + Send,
    {
        tokio::fs::read(path).await.map_err(Into::into)
    }

    async fn read_to_string<P>(&self, path: P) -> FileSystemResult<String>
    where
        P: AsRef<Path> + Send,
    {
        tokio::fs::read_to_string(path).await.map_err(Into::into)
    }

    async fn write<P, C>(&self, path: P, contents: C) -> FileSystemResult<()>
    where
        P: AsRef<Path> + Send,
        C: AsRef<[u8]> + Send,
    {
        tokio::fs::write(path, contents).await.map_err(Into::into)
    }

    async fn append<P, C>(&self, path: P, contents: C) -> FileSystemResult<()>
    where
        P: AsRef<Path> + Send,
        C: AsRef<[u8]> + Send,
    {
        let contents = contents.as_ref();
        let mut file = tokio::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)
            .await
            .map_err(Into::<FileSystemError>::into)?;

        file.write_all(contents)
            .await
            .map_err(Into::<FileSystemError>::into)?;

        file.flush().await.and(Ok(())).map_err(Into::into)
    }

    async fn copy<P1, P2>(&self, from: P1, to: P2) -> FileSystemResult<()>
    where
        P1: AsRef<Path> + Send,
        P2: AsRef<Path> + Send,
    {
        tokio::fs::copy(from, to)
            .await
            .and(Ok(()))
            .map_err(Into::into)
    }

    async fn set_mode<P>(&self, path: P, mode: u32) -> FileSystemResult<()>
    where
        P: AsRef<Path> + Send,
    {
        tokio::fs::set_permissions(path, Permissions::from_mode(mode))
            .await
            .map_err(Into::into)
    }

    async fn exists<P>(&self, path: P) -> bool
    where
        P: AsRef<Path> + Send,
    {
        path.as_ref().exists()
    }
}

#[cfg(test)]
mod tests {
    use uuid::Uuid;

    use super::*;

    const FILE_BITS: u32 = 0o100000;
    const DIR_BITS: u32 = 0o40000;

    fn setup() -> String {
        let test_dir = format!("/tmp/unit_test_{}", Uuid::new_v4());
        std::fs::create_dir(&test_dir).unwrap();
        test_dir
    }

    fn teardown(test_dir: String) {
        std::fs::remove_dir_all(test_dir).unwrap();
    }

    #[tokio::test]
    async fn create_dir_should_create_a_new_directory_at_path() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let new_dir = format!("{test_dir}/mynewdir");
        fs.create_dir(&new_dir).await.unwrap();

        let new_dir_path = Path::new(&new_dir);
        assert!(new_dir_path.exists() && new_dir_path.is_dir());
        teardown(test_dir);
    }

    #[tokio::test]
    async fn create_dir_should_bubble_up_error_if_some_happens() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let new_dir = format!("{test_dir}/mynewdir");
        // intentionally create new dir before calling function to force error
        std::fs::create_dir(&new_dir).unwrap();
        let err = fs.create_dir(&new_dir).await.unwrap_err();

        assert_eq!(err.to_string(), "File exists (os error 17)");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn create_dir_all_should_create_a_new_directory_and_all_of_it_ancestors_at_path() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let new_dir = format!("{test_dir}/the/path/to/mynewdir");
        fs.create_dir_all(&new_dir).await.unwrap();

        let new_dir_path = Path::new(&new_dir);
        assert!(new_dir_path.exists() && new_dir_path.is_dir());
        teardown(test_dir);
    }

    #[tokio::test]
    async fn create_dir_all_should_bubble_up_error_if_some_happens() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let new_dir = format!("{test_dir}/the/path/to/mynewdir");
        // intentionally create new file as ancestor before calling function to force error
        std::fs::write(format!("{test_dir}/the"), b"test").unwrap();
        let err = fs.create_dir_all(&new_dir).await.unwrap_err();

        assert_eq!(err.to_string(), "Not a directory (os error 20)");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn read_should_return_the_contents_of_the_file_at_path() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        std::fs::write(&file_path, b"Test").unwrap();
        let contents = fs.read(file_path).await.unwrap();

        assert_eq!(contents, b"Test");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn read_should_bubble_up_error_if_some_happens() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        // intentionally forget to create file to force error
        let err = fs.read(file_path).await.unwrap_err();

        assert_eq!(err.to_string(), "No such file or directory (os error 2)");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn read_to_string_should_return_the_contents_of_the_file_at_path_as_string() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        std::fs::write(&file_path, b"Test").unwrap();
        let contents = fs.read_to_string(file_path).await.unwrap();

        assert_eq!(contents, "Test");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn read_to_string_should_bubble_up_error_if_some_happens() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        // intentionally forget to create file to force error
        let err = fs.read_to_string(file_path).await.unwrap_err();

        assert_eq!(err.to_string(), "No such file or directory (os error 2)");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn write_should_create_a_new_file_at_path_with_contents() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        fs.write(&file_path, "Test").await.unwrap();

        assert_eq!(std::fs::read_to_string(file_path).unwrap(), "Test");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn write_should_overwrite_an_existing_file_with_contents() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        std::fs::write(&file_path, "Test").unwrap();
        assert_eq!(std::fs::read_to_string(&file_path).unwrap(), "Test");
        fs.write(&file_path, "Test updated").await.unwrap();

        assert_eq!(std::fs::read_to_string(file_path).unwrap(), "Test updated");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn write_should_bubble_up_error_if_some_happens() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        // intentionally create directory instead of file to force error
        std::fs::create_dir(&file_path).unwrap();
        let err = fs.write(&file_path, "Test").await.unwrap_err();

        assert_eq!(err.to_string(), "Is a directory (os error 21)");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn append_should_create_a_new_file_at_path_with_contents() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        fs.append(&file_path, "Test").await.unwrap();

        assert_eq!(std::fs::read_to_string(file_path).unwrap(), "Test");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn append_should_updates_an_existing_file_by_appending_contents() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        std::fs::write(&file_path, "Test").unwrap();
        assert_eq!(std::fs::read_to_string(&file_path).unwrap(), "Test");
        fs.append(&file_path, " updated").await.unwrap();

        assert_eq!(std::fs::read_to_string(file_path).unwrap(), "Test updated");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn append_should_bubble_up_error_if_some_happens() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let file_path = format!("{test_dir}/myfile");
        // intentionally create directory instead of file to force error
        std::fs::create_dir(&file_path).unwrap();
        let err = fs.append(&file_path, "Test").await.unwrap_err();

        assert_eq!(err.to_string(), "Is a directory (os error 21)");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn copy_should_create_a_duplicate_of_source() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let from_path = format!("{test_dir}/myfile");
        std::fs::write(&from_path, "Test").unwrap();
        let to_path = format!("{test_dir}/mycopy");
        fs.copy(&from_path, &to_path).await.unwrap();

        assert_eq!(std::fs::read_to_string(to_path).unwrap(), "Test");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn copy_should_ovewrite_destination_if_alread_exists() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let from_path = format!("{test_dir}/myfile");
        std::fs::write(&from_path, "Test").unwrap();
        let to_path = format!("{test_dir}/mycopy");
        std::fs::write(&from_path, "Some content").unwrap();
        fs.copy(&from_path, &to_path).await.unwrap();

        assert_eq!(std::fs::read_to_string(to_path).unwrap(), "Some content");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn copy_should_bubble_up_error_if_some_happens() {
        let test_dir = setup();
        let fs = LocalFileSystem;

        let from_path = format!("{test_dir}/nonexistentfile");
        let to_path = format!("{test_dir}/mycopy");
        let err = fs.copy(&from_path, &to_path).await.unwrap_err();

        assert_eq!(err.to_string(), "No such file or directory (os error 2)");
        teardown(test_dir);
    }

    #[tokio::test]
    async fn set_mode_should_update_the_file_mode_at_path() {
        let test_dir = setup();
        let fs = LocalFileSystem;
        let path = format!("{test_dir}/myfile");
        std::fs::write(&path, "Test").unwrap();
        assert!(std::fs::metadata(&path).unwrap().permissions().mode() != (FILE_BITS + 0o400));

        fs.set_mode(&path, 0o400).await.unwrap();

        assert_eq!(
            std::fs::metadata(&path).unwrap().permissions().mode(),
            FILE_BITS + 0o400
        );
        teardown(test_dir);
    }

    #[tokio::test]
    async fn set_mode_should_update_the_directory_mode_at_path() {
        let test_dir = setup();
        let fs = LocalFileSystem;
        let path = format!("{test_dir}/mydir");
        std::fs::create_dir(&path).unwrap();
        assert!(std::fs::metadata(&path).unwrap().permissions().mode() != (DIR_BITS + 0o700));

        fs.set_mode(&path, 0o700).await.unwrap();

        assert_eq!(
            std::fs::metadata(&path).unwrap().permissions().mode(),
            DIR_BITS + 0o700
        );
        teardown(test_dir);
    }

    #[tokio::test]
    async fn set_mode_should_bubble_up_error_if_some_happens() {
        let test_dir = setup();
        let fs = LocalFileSystem;
        let path = format!("{test_dir}/somemissingfile");
        // intentionnally don't create file

        let err = fs.set_mode(&path, 0o400).await.unwrap_err();

        assert_eq!(err.to_string(), "No such file or directory (os error 2)");
        teardown(test_dir);
    }
}