]> git.lizzy.rs Git - rust.git/blob - xtask/src/pre_cache.rs
Revert "Rewrite `#[derive]` removal to be based on AST"
[rust.git] / xtask / src / pre_cache.rs
1 use std::{
2     fs::FileType,
3     path::{Path, PathBuf},
4 };
5
6 use anyhow::Result;
7 use xshell::rm_rf;
8
9 use crate::flags;
10
11 impl flags::PreCache {
12     /// Cleans the `./target` dir after the build such that only
13     /// dependencies are cached on CI.
14     pub(crate) fn run(self) -> Result<()> {
15         let slow_tests_cookie = Path::new("./target/.slow_tests_cookie");
16         if !slow_tests_cookie.exists() {
17             panic!("slow tests were skipped on CI!")
18         }
19         rm_rf(slow_tests_cookie)?;
20
21         for path in read_dir("./target/debug", FileType::is_file)? {
22             // Can't delete yourself on windows :-(
23             if !path.ends_with("xtask.exe") {
24                 rm_rf(&path)?
25             }
26         }
27
28         rm_rf("./target/.rustc_info.json")?;
29
30         let to_delete = read_dir("./crates", FileType::is_dir)?
31             .into_iter()
32             .map(|path| path.file_name().unwrap().to_string_lossy().replace('-', "_"))
33             .collect::<Vec<_>>();
34
35         for &dir in ["./target/debug/deps", "target/debug/.fingerprint"].iter() {
36             for path in read_dir(dir, |_file_type| true)? {
37                 if path.ends_with("xtask.exe") {
38                     continue;
39                 }
40                 let file_name = path.file_name().unwrap().to_string_lossy();
41                 let (stem, _) = match rsplit_once(&file_name, '-') {
42                     Some(it) => it,
43                     None => {
44                         rm_rf(path)?;
45                         continue;
46                     }
47                 };
48                 let stem = stem.replace('-', "_");
49                 if to_delete.contains(&stem) {
50                     rm_rf(path)?;
51                 }
52             }
53         }
54
55         Ok(())
56     }
57 }
58 fn read_dir(path: impl AsRef<Path>, cond: impl Fn(&FileType) -> bool) -> Result<Vec<PathBuf>> {
59     read_dir_impl(path.as_ref(), &cond)
60 }
61
62 fn read_dir_impl(path: &Path, cond: &dyn Fn(&FileType) -> bool) -> Result<Vec<PathBuf>> {
63     let mut res = Vec::new();
64     for entry in path.read_dir()? {
65         let entry = entry?;
66         let file_type = entry.file_type()?;
67         if cond(&file_type) {
68             res.push(entry.path())
69         }
70     }
71     Ok(res)
72 }
73
74 fn rsplit_once(haystack: &str, delim: char) -> Option<(&str, &str)> {
75     let mut split = haystack.rsplitn(2, delim);
76     let suffix = split.next()?;
77     let prefix = split.next()?;
78     Some((prefix, suffix))
79 }