engine/snapshot/files.rs
1// Copyright 2020-2021 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5 fs, io,
6 path::{Path, PathBuf},
7};
8
9/// Get the preferred Stronghold home directory
10///
11/// Defaults to a sub-directory named `.stronghold` under the user's home directory (see
12/// [`dirs_next::home_dir`](../dirs_next/fn.home_dir.html), but can be overridden by the `STRONGHOLD` environment
13/// variable.
14pub fn home_dir() -> io::Result<PathBuf> {
15 let home = match std::env::var("STRONGHOLD") {
16 Ok(h) => h.into(),
17 Err(_) => dirs_next::home_dir().expect("Failed to get home directory"),
18 };
19 let home_dir = home.join(".stronghold");
20
21 verify_or_create(&home_dir)?;
22
23 Ok(home_dir)
24}
25
26/// Get the preferred snapshot directory
27///
28/// Defaults to the `snapshots` subdirectory under the preferred Stronghold home directory as
29/// returned by [`home_dir`](fn.home_dir.html).
30pub fn snapshot_dir() -> io::Result<PathBuf> {
31 let home_dir = home_dir()?;
32 let snapshot_dir = home_dir.join("snapshots");
33
34 verify_or_create(&snapshot_dir)?;
35
36 Ok(snapshot_dir)
37}
38
39fn verify_or_create(dir: &Path) -> io::Result<()> {
40 if dir.is_dir() {
41 return Ok(());
42 }
43 fs::create_dir_all(dir)
44}
45
46/// Construct the path to a snapshot file with the specifed name (defaults to `main`) under
47/// the directory specified by the (`snapshot_dir`)[fn.snapshot_dir.html] function.
48pub fn get_path(name: Option<&str>) -> io::Result<PathBuf> {
49 snapshot_dir().map(|p| p.join(format!("{}.stronghold", name.unwrap_or("main"))))
50}