// Copyright 2018 Zach Miller
//
// Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT License (https://opensource.org/licenses/MIT), at your option.
//
// This file may not be copied, modified, or distributed except according to those terms.

use tempfile::{tempdir_in, NamedTempFile, TempDir};

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

// Retrieves the path that temporary test files should be created in.
pub(crate) fn get_test_path() -> PathBuf {
    match env::var("TEMPORARY_TEST_PATH") {
        Ok(p) => PathBuf::from(p),
        _ => panic!("TEMPORARY_TEST_PATH environment variable not set."),
    }
}

// Creates the temporary test path.
pub(crate) fn create_test_directory() -> TempDir {
    let path = get_test_path();
    fs::create_dir_all(&path).unwrap();
    tempdir_in(&path).unwrap()
}

// Create the temporary test path with folders for committed and uncommitted checkpoints.
pub(crate) fn create_test_directory_with_checkpoint_folders() -> TempDir {
    let dir = create_test_directory();
    let committed_path = dir.path().join("committed");
    let uncommitted_path = dir.path().join("uncommitted");
    fs::create_dir(committed_path).unwrap();
    fs::create_dir(uncommitted_path).unwrap();
    dir
}

// Creates a temporary named file in the specified directory.
pub(crate) fn create_named_test_file<P: AsRef<Path>>(dir: P) -> NamedTempFile {
    NamedTempFile::new_in(&dir).unwrap()
}
