blob: a355544bbaaaf9a04f272f1432af8114836af6cb [file] [log] [blame]
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080015//! Implements TempDir which aids in creating an cleaning up temporary directories for testing.
16
Janis Danisevskisbf15d732020-12-08 10:35:26 -080017use std::fs::{create_dir, remove_dir_all};
18use std::io::ErrorKind;
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080019use std::path::{Path, PathBuf};
20use std::{env::temp_dir, ops::Deref};
Janis Danisevskisbf15d732020-12-08 10:35:26 -080021
Janis Danisevskisa578d392021-09-20 15:44:06 -070022pub mod run_as;
23
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080024/// Represents the lifecycle of a temporary directory for testing.
Janis Danisevskisbf15d732020-12-08 10:35:26 -080025#[derive(Debug)]
26pub struct TempDir {
27 path: std::path::PathBuf,
28 do_drop: bool,
29}
30
31impl TempDir {
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080032 /// Creates a temporary directory with a name of the form <prefix>_NNNNN where NNNNN is a zero
33 /// padded random number with 5 figures. The prefix must not contain file system separators.
34 /// The location of the directory cannot be chosen.
35 /// The directory with all of its content is removed from the file system when the resulting
36 /// object gets dropped.
Janis Danisevskisbf15d732020-12-08 10:35:26 -080037 pub fn new(prefix: &str) -> std::io::Result<Self> {
38 let tmp = loop {
39 let mut tmp = temp_dir();
40 let number: u16 = rand::random();
41 tmp.push(format!("{}_{:05}", prefix, number));
42 match create_dir(&tmp) {
43 Err(e) => match e.kind() {
44 ErrorKind::AlreadyExists => continue,
45 _ => return Err(e),
46 },
47 Ok(()) => break tmp,
48 }
49 };
50 Ok(Self { path: tmp, do_drop: true })
51 }
52
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080053 /// Returns the absolute path of the temporary directory.
Janis Danisevskisbf15d732020-12-08 10:35:26 -080054 pub fn path(&self) -> &Path {
55 &self.path
56 }
57
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080058 /// Returns a path builder for convenient extension of the path.
59 ///
60 /// ## Example:
61 ///
62 /// ```
63 /// let tdir = TempDir::new("my_test")?;
64 /// let temp_foo_bar = tdir.build().push("foo").push("bar");
65 /// ```
66 /// `temp_foo_bar` derefs to a Path that represents "<tdir.path()>/foo/bar"
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080067 pub fn build(&self) -> PathBuilder {
68 PathBuilder(self.path.clone())
69 }
70
Janis Danisevskisbf15d732020-12-08 10:35:26 -080071 /// When a test is failing you can set this to false in order to inspect
72 /// the directory structure after the test failed.
73 #[allow(dead_code)]
74 pub fn do_not_drop(&mut self) {
75 println!("Disabled automatic cleanup for: {:?}", self.path);
76 log::info!("Disabled automatic cleanup for: {:?}", self.path);
77 self.do_drop = false;
78 }
79}
80
81impl Drop for TempDir {
82 fn drop(&mut self) {
83 if self.do_drop {
84 remove_dir_all(&self.path).expect("Cannot delete temporary dir.");
85 }
86 }
87}
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080088
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080089/// Allows for convenient building of paths from a TempDir. See TempDir.build() for more details.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080090pub struct PathBuilder(PathBuf);
91
92impl PathBuilder {
Janis Danisevskis2a8330a2021-01-20 15:34:26 -080093 /// Adds another segment to the end of the path. Consumes, modifies and returns self.
Janis Danisevskisa51ccbc2020-11-25 21:04:24 -080094 pub fn push(mut self, segment: &str) -> Self {
95 self.0.push(segment);
96 self
97 }
98}
99
100impl Deref for PathBuilder {
101 type Target = Path;
102
103 fn deref(&self) -> &Self::Target {
104 &self.0
105 }
106}