leo_package/build/
directory.rs

1// Copyright (C) 2019-2025 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17use leo_errors::{PackageError, Result};
18
19use std::{
20    borrow::Cow,
21    fs,
22    path::{Path, PathBuf},
23};
24
25pub static BUILD_DIRECTORY_NAME: &str = "build/";
26
27pub struct BuildDirectory;
28
29impl BuildDirectory {
30    /// Returns the path to the build directory if it exists.
31    pub fn open(path: &Path) -> Result<PathBuf> {
32        let mut path = Cow::from(path);
33        if path.is_dir() && !path.ends_with(BUILD_DIRECTORY_NAME) {
34            path.to_mut().push(BUILD_DIRECTORY_NAME);
35        }
36
37        if path.exists() {
38            Ok(path.to_path_buf())
39        } else {
40            Err(PackageError::directory_not_found(BUILD_DIRECTORY_NAME, path.display()).into())
41        }
42    }
43
44    /// Creates a directory at the provided path with the default directory name.
45    pub fn create(path: &Path) -> Result<PathBuf> {
46        let mut path = Cow::from(path);
47        if path.is_dir() && !path.ends_with(BUILD_DIRECTORY_NAME) {
48            path.to_mut().push(BUILD_DIRECTORY_NAME);
49        }
50
51        fs::create_dir_all(&path).map_err(|err| PackageError::failed_to_create_directory(BUILD_DIRECTORY_NAME, err))?;
52        Ok(path.to_path_buf())
53    }
54
55    /// Removes the directory at the provided path.
56    pub fn remove(path: &Path) -> Result<String> {
57        let mut path = Cow::from(path);
58        if path.is_dir() && !path.ends_with(BUILD_DIRECTORY_NAME) {
59            path.to_mut().push(BUILD_DIRECTORY_NAME);
60        }
61
62        if path.exists() {
63            fs::remove_dir_all(&path).map_err(|e| PackageError::failed_to_remove_directory(path.display(), e))?;
64        }
65
66        Ok(format!("(in \"{}\")", path.display()))
67    }
68}