btdt 0.4.4

"been there, done that" - a tool for flexible CI caching
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
//! A pipeline defines how multiple files a processed to be stored in the cache, e.g. by archiving
//! them in TAR format and potentially compressing them.

use crate::cache::Cache;
use crate::error::{IoPathError, IoPathResult, WithPath};
use crate::util::close::Close;
use ignore::overrides::Override;
use ignore::{Error, WalkBuilder};
use std::fs::File;
use std::io;
use std::io::{BufWriter, Write};
use std::path::Path;
use tar::{Builder, EntryType, Header};

/// A pipeline defines how multiple files a processed to be stored in the cache.
///
/// # Examples
///
/// ```rust
/// # use std::fs;
/// # use std::io;
/// use btdt::cache::local::LocalCache;
/// # use btdt::error::IoPathResult;
/// use btdt::pipeline::Pipeline;
/// use btdt::storage::in_memory::InMemoryStorage;
///
/// # fn main() -> IoPathResult<()> {
/// # const CACHEABLE_PATH: &str = "/tmp/btdt-cacheable";
/// # struct CacheableDir;
/// # impl CacheableDir {
/// #     pub fn new() -> Self {
/// #         fs::create_dir(CACHEABLE_PATH).expect(format!("Failed to create directory at {}", CACHEABLE_PATH).as_str());
/// #         Self
/// #     }
/// # }
/// # impl Drop for CacheableDir {
/// #    fn drop(&mut self) {
/// #        fs::remove_dir_all(CACHEABLE_PATH).expect(format!("Failed to remove directory at {}", CACHEABLE_PATH).as_str());
/// #    }
/// # }
/// # let _cacheable_dir = CacheableDir::new();
/// let mut pipeline = Pipeline::new(LocalCache::new(InMemoryStorage::new()));
/// pipeline.store(&["cache-key"], CACHEABLE_PATH)?;
/// pipeline.restore(&["cache-key"], CACHEABLE_PATH)?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct Pipeline<C: Cache> {
    cache: C,
}

impl<C: Cache> Pipeline<C> {
    /// Creates a new pipeline with the given cache.
    pub fn new(cache: C) -> Self {
        Pipeline { cache }
    }

    /// Restores the files stored in the cache.
    ///
    /// The first key found in the cache is used to restore the files. If no key is found, nothing
    /// is restored. Restored files are written into the directory specified by `destination`.
    ///
    /// Returns `Ok(Some(key))` if files were restored where `key` is the cache key used, `Ok(None)`
    /// otherwise.
    pub fn restore<'a>(
        &self,
        keys: &[&'a str],
        destination: impl AsRef<Path>,
    ) -> IoPathResult<Option<&'a str>> {
        if let Some(cache_hit) = self.cache.get(keys)? {
            tar::Archive::new(cache_hit.reader)
                .unpack(destination.as_ref())
                .with_path(destination.as_ref())?;
            Ok(Some(cache_hit.key))
        } else {
            Ok(None)
        }
    }

    /// Stores the files in the cache.
    ///
    /// The files in the directory specified by `source` are archived and stored in the cache under
    /// the given keys.
    ///
    /// Files named `.btdtignore` can be used to exclude files from the cache. The syntax follows
    /// the [`.gitignore` specification](https://git-scm.com/docs/gitignore).
    pub fn store(&mut self, keys: &[&str], source: impl AsRef<Path>) -> IoPathResult<()> {
        self.store_with_overrides(keys, source, Override::empty())
    }

    /// Stores the files in the cache.
    ///
    /// The files in the directory specified by `source` are archived and stored in the cache under
    /// the given keys.
    ///
    /// Files named `.btdtignore` can be used to exclude files from the cache. The syntax follows
    /// the [`.gitignore` specification](https://git-scm.com/docs/gitignore).
    pub fn store_with_overrides(
        &mut self,
        keys: &[&str],
        source: impl AsRef<Path>,
        overrides: Override,
    ) -> IoPathResult<()> {
        let mut writer = BufWriter::new(self.cache.set(keys)?);
        {
            let mut archive = tar::Builder::new(&mut writer);
            archive.follow_symlinks(false);
            Self::add_dir_to_archive(&mut archive, source.as_ref(), overrides)?;
            archive.finish().with_path(source.as_ref())?;
        }
        writer
            .into_inner()
            .map_err(|e| e.into())
            .and_then(Close::close)
            .with_path(source.as_ref())?;
        Ok(())
    }

    fn add_dir_to_archive(
        archive_builder: &mut Builder<impl Write>,
        root: &Path,
        overrides: Override,
    ) -> IoPathResult<()> {
        let walker = WalkBuilder::new(root)
            .follow_links(false)
            .standard_filters(false)
            .add_custom_ignore_filename(".btdtignore")
            .overrides(overrides)
            .build();

        for entry in walker {
            let entry = entry.map_err(|err| match err {
                Error::WithPath { path, err } => IoPathError::new(io::Error::other(err), path),
                err => IoPathError::new_no_path(io::Error::other(err)),
            })?;

            let source_path = entry.path();
            if source_path == root {
                continue;
            }
            let archived_path = source_path
                .strip_prefix(root)
                .expect("root not a prefix of parth");

            let file_type = entry.file_type().expect("file type should be available");
            if file_type.is_dir() {
                archive_builder
                    .append_dir(archived_path, source_path)
                    .with_path(source_path)?;
            } else if file_type.is_symlink() {
                let link_target = std::fs::read_link(source_path).with_path(source_path)?;
                let mut header = Header::new_old();
                header.set_entry_type(EntryType::Symlink);
                header.set_size(0);
                archive_builder
                    .append_link(&mut header, archived_path, link_target)
                    .with_path(source_path)?;
            } else if file_type.is_file() {
                let mut file = File::open(source_path).with_path(source_path)?;
                archive_builder
                    .append_file(archived_path, &mut file)
                    .with_path(entry.path())?;
            } else {
                return Err(io::Error::other("Unsupported file type")).with_path(entry.path());
            }
        }
        Ok(())
    }

    /// Consumes the pipeline and returns the cache.
    pub fn into_cache(self) -> C {
        self.cache
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache::local::LocalCache;
    use crate::storage::in_memory::InMemoryStorage;
    use crate::test_util::fs_spec::{DirSpec, FileSpec, Node};
    use ignore::overrides::OverrideBuilder;
    use std::fs;
    use std::fs::Permissions;
    use std::os::unix::fs::PermissionsExt;
    use tempfile::tempdir;

    fn file_with_name(name: &str) -> (String, Box<dyn Node>) {
        (
            name.to_string(),
            Box::new(FileSpec {
                permissions: Permissions::from_mode(0o644),
                content: vec![],
            }) as Box<dyn Node>,
        )
    }

    #[test]
    fn test_roundtrip() {
        let cache = LocalCache::new(InMemoryStorage::new());
        let mut pipeline = Pipeline::new(cache);

        let spec = DirSpec::create_unix_fixture();

        let tempdir = tempdir().unwrap();
        let source_path = tempdir.path().join("source-root");
        spec.create(source_path.as_ref()).unwrap();
        pipeline.store(&["cache-key"], &source_path).unwrap();

        let destination_path = tempdir.path().join("destination-root");
        pipeline.restore(&["cache-key"], &destination_path).unwrap();

        assert_eq!(spec.compare_with(&destination_path).unwrap(), vec![]);
    }

    #[test]
    fn test_respects_btdtignore_files() {
        let cache = LocalCache::new(InMemoryStorage::new());
        let mut pipeline = Pipeline::new(cache);

        let spec = DirSpec {
            permissions: Permissions::from_mode(0o755),
            children: [
                (
                    ".btdtignore".to_string(),
                    Box::new(FileSpec {
                        permissions: Permissions::from_mode(0o644),
                        content: b"
# comment
/ignore-root-only
ignore-everywhere
ignore-only-dir/
ignore-*-wildcard
subpath/**/ignore
!**/include
                "
                        .to_vec(),
                    }) as Box<dyn Node>,
                ),
                file_with_name("some-file"),
                file_with_name(".hidden-file"),
                file_with_name("include"),
                file_with_name("ignore-root-only"),
                file_with_name("ignore-everywhere"),
                file_with_name("ignore-foo-wildcard"),
                file_with_name("ignore-with-local-ignore-file"),
                (
                    "ignore-only-dir".to_string(),
                    Box::new(DirSpec {
                        permissions: Permissions::from_mode(0o755),
                        children: [file_with_name("foo"), file_with_name("include")]
                            .into_iter()
                            .collect(),
                    }) as Box<dyn Node>,
                ),
                (
                    "subpath".to_string(),
                    Box::new(DirSpec {
                        permissions: Permissions::from_mode(0o755),
                        children: [
                            file_with_name("ignore-root-only"),
                            file_with_name("ignore-everywhere"),
                            file_with_name("ignore-only-dir"),
                            file_with_name("ignore-with-local-ignore-file"),
                            (
                                ".btdtignore".to_string(),
                                Box::new(FileSpec {
                                    permissions: Permissions::from_mode(0o644),
                                    content: b"ignore-with-local-ignore-file".to_vec(),
                                }) as Box<dyn Node>,
                            ),
                            (
                                "subsubpath".to_string(),
                                Box::new(DirSpec {
                                    permissions: Permissions::from_mode(0o755),
                                    children: [file_with_name("foo"), file_with_name("ignore")]
                                        .into_iter()
                                        .collect(),
                                }) as Box<dyn Node>,
                            ),
                        ]
                        .into_iter()
                        .collect(),
                    }) as Box<dyn Node>,
                ),
            ]
            .into_iter()
            .collect(),
        };
        let expected = DirSpec {
            permissions: Permissions::from_mode(0o755),
            children: [
                (
                    ".btdtignore".to_string(),
                    Box::new(FileSpec {
                        permissions: Permissions::from_mode(0o644),
                        content: b"
# comment
/ignore-root-only
ignore-everywhere
ignore-only-dir/
ignore-*-wildcard
subpath/**/ignore
!**/include
                "
                        .to_vec(),
                    }) as Box<dyn Node>,
                ),
                file_with_name("some-file"),
                file_with_name(".hidden-file"),
                file_with_name("include"),
                file_with_name("ignore-with-local-ignore-file"),
                (
                    "subpath".to_string(),
                    Box::new(DirSpec {
                        permissions: Permissions::from_mode(0o755),
                        children: [
                            file_with_name("ignore-root-only"),
                            file_with_name("ignore-only-dir"),
                            (
                                ".btdtignore".to_string(),
                                Box::new(FileSpec {
                                    permissions: Permissions::from_mode(0o644),
                                    content: b"ignore-with-local-ignore-file".to_vec(),
                                }) as Box<dyn Node>,
                            ),
                            (
                                "subsubpath".to_string(),
                                Box::new(DirSpec {
                                    permissions: Permissions::from_mode(0o755),
                                    children: [file_with_name("foo")].into_iter().collect(),
                                }) as Box<dyn Node>,
                            ),
                        ]
                        .into_iter()
                        .collect(),
                    }) as Box<dyn Node>,
                ),
            ]
            .into_iter()
            .collect(),
        };

        let tempdir = tempdir().unwrap();
        let source_path = tempdir.path().join("source-root");
        spec.create(source_path.as_ref()).unwrap();
        pipeline.store(&["cache-key"], &source_path).unwrap();

        let destination_path = tempdir.path().join("destination-root");
        pipeline.restore(&["cache-key"], &destination_path).unwrap();

        assert_eq!(expected.compare_with(&destination_path).unwrap(), vec![]);
    }

    #[test]
    fn test_does_not_use_gitignore_files() {
        let cache = LocalCache::new(InMemoryStorage::new());
        let mut pipeline = Pipeline::new(cache);

        let spec = DirSpec {
            permissions: Permissions::from_mode(0o755),
            children: [
                (
                    ".gitignore".to_string(),
                    Box::new(FileSpec {
                        permissions: Permissions::from_mode(0o644),
                        content: b"do-not-ignore".to_vec(),
                    }) as Box<dyn Node>,
                ),
                (
                    "do-not-ignore".to_string(),
                    Box::new(FileSpec {
                        permissions: Permissions::from_mode(0o644),
                        content: vec![],
                    }) as Box<dyn Node>,
                ),
            ]
            .into_iter()
            .collect(),
        };

        let tempdir = tempdir().unwrap();
        let source_path = tempdir.path().join("source-root");
        spec.create(source_path.as_ref()).unwrap();
        pipeline.store(&["cache-key"], &source_path).unwrap();

        let destination_path = tempdir.path().join("destination-root");
        pipeline.restore(&["cache-key"], &destination_path).unwrap();

        assert_eq!(spec.compare_with(&destination_path).unwrap(), vec![]);
    }

    #[test]
    fn test_store_with_overrides() {
        let cache = LocalCache::new(InMemoryStorage::new());
        let mut pipeline = Pipeline::new(cache);

        let spec = DirSpec {
            permissions: Permissions::from_mode(0o755),
            children: [file_with_name("some-file"), file_with_name("ignore")]
                .into_iter()
                .collect(),
        };
        let expected = DirSpec {
            permissions: Permissions::from_mode(0o755),
            children: [file_with_name("some-file")].into_iter().collect(),
        };

        let tempdir = tempdir().unwrap();
        let source_path = tempdir.path().join("source-root");
        spec.create(source_path.as_ref()).unwrap();

        let overrides = OverrideBuilder::new(&source_path)
            .add("!ignore")
            .unwrap()
            .build()
            .unwrap();
        pipeline
            .store_with_overrides(&["cache-key"], &source_path, overrides)
            .unwrap();

        let destination_path = tempdir.path().join("destination-root");
        pipeline.restore(&["cache-key"], &destination_path).unwrap();

        assert_eq!(expected.compare_with(&destination_path).unwrap(), vec![]);
    }

    #[test]
    fn test_restore_returns_restored_cache_key() {
        let cache = LocalCache::new(InMemoryStorage::new());
        let mut pipeline = Pipeline::new(cache);

        let tempdir = tempdir().unwrap();
        let source_path = tempdir.path().join("source-root");
        fs::create_dir(&source_path).unwrap();
        pipeline.store(&["cache-key-0"], tempdir.path()).unwrap();
        pipeline.store(&["cache-key-1"], tempdir.path()).unwrap();

        let destination_path = tempdir.path().join("destination-root");

        assert!(
            pipeline
                .restore(&["non-existent"], &destination_path)
                .unwrap()
                .is_none()
        );
        assert_eq!(
            pipeline
                .restore(
                    &["non-existent", "cache-key-1", "cache-key-0"],
                    &destination_path
                )
                .unwrap(),
            Some("cache-key-1")
        );
    }
}