leo_package/source/
main.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
17//! The `main.leo` file.
18
19use crate::source::directory::SOURCE_DIRECTORY_NAME;
20use leo_errors::{PackageError, Result};
21
22use serde::Deserialize;
23use std::{borrow::Cow, fs::File, io::Write, path::Path};
24
25pub static MAIN_FILENAME: &str = "main.leo";
26
27#[derive(Deserialize)]
28pub struct MainFile {
29    pub package_name: String,
30}
31
32impl MainFile {
33    pub fn new(package_name: &str) -> Self {
34        Self { package_name: package_name.to_string() }
35    }
36
37    pub fn filename() -> String {
38        format!("{SOURCE_DIRECTORY_NAME}{MAIN_FILENAME}")
39    }
40
41    pub fn exists_at(path: &Path) -> bool {
42        let mut path = Cow::from(path);
43        if path.is_dir() {
44            if !path.ends_with(SOURCE_DIRECTORY_NAME) {
45                path.to_mut().push(SOURCE_DIRECTORY_NAME);
46            }
47            path.to_mut().push(MAIN_FILENAME);
48        }
49        path.exists()
50    }
51
52    pub fn write_to(self, path: &Path) -> Result<()> {
53        let mut path = Cow::from(path);
54        if path.is_dir() {
55            if !path.ends_with(SOURCE_DIRECTORY_NAME) {
56                path.to_mut().push(SOURCE_DIRECTORY_NAME);
57            }
58            path.to_mut().push(MAIN_FILENAME);
59        }
60
61        let mut file = File::create(&path).map_err(PackageError::io_error_main_file)?;
62        Ok(file.write_all(self.template().as_bytes()).map_err(PackageError::io_error_main_file)?)
63    }
64
65    // TODO: Generalize to other networks.
66    fn template(&self) -> String {
67        format!(
68            r#"// The '{}' program.
69program {}.aleo {{
70    transition main(public a: u32, b: u32) -> u32 {{
71        let c: u32 = a + b;
72        return c;
73    }}
74}}
75"#,
76            self.package_name, self.package_name
77        )
78    }
79}