leo_package/source/
directory.rs

1// Copyright (C) 2019-2024 Aleo Systems 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 crate::parse_file_paths;
18
19use leo_errors::{PackageError, Result};
20
21use crate::source::MAIN_FILENAME;
22use std::{
23    borrow::Cow,
24    fs,
25    path::{Path, PathBuf},
26};
27
28pub static SOURCE_DIRECTORY_NAME: &str = "src/";
29
30pub struct SourceDirectory;
31
32impl SourceDirectory {
33    /// Creates a directory at the provided path with the default directory name.
34    pub fn create(path: &Path) -> Result<()> {
35        let mut path = Cow::from(path);
36        if path.is_dir() && !path.ends_with(SOURCE_DIRECTORY_NAME) {
37            path.to_mut().push(SOURCE_DIRECTORY_NAME);
38        }
39
40        fs::create_dir_all(&path).map_err(PackageError::failed_to_create_source_directory)?;
41        Ok(())
42    }
43
44    /// Returns a list of files in the source directory.
45    pub fn files(path: &Path) -> Result<Vec<PathBuf>> {
46        let mut path = Cow::from(path);
47        if path.is_dir() && !path.ends_with(SOURCE_DIRECTORY_NAME) {
48            path.to_mut().push(SOURCE_DIRECTORY_NAME);
49        }
50
51        let directory = fs::read_dir(&path).map_err(|err| PackageError::failed_to_read_file(path.display(), err))?;
52        let mut file_paths = Vec::new();
53
54        parse_file_paths(directory, &mut file_paths)?;
55
56        Ok(file_paths)
57    }
58
59    /// Check that the files in the source directory are valid.
60    pub fn check_files(paths: &[PathBuf]) -> Result<()> {
61        match paths.len() {
62            0 => Err(PackageError::empty_source_directory().into()),
63            1 if paths[0].as_path().ends_with(MAIN_FILENAME) => Ok(()),
64            _ => Err(PackageError::source_directory_can_contain_only_one_file().into()),
65        }
66    }
67}