leo_lang/cli/helpers/context.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 aleo_std;
18use leo_errors::{CliError, Result};
19use leo_package::Manifest;
20
21use aleo_std::aleo_dir;
22use std::{env::current_dir, path::PathBuf};
23
24/// Project context, manifest, current directory etc
25/// All the info that is relevant in most of the commands
26// TODO: Make `path` and `home` not pub, to prevent misuse through direct access.
27#[derive(Clone)]
28pub struct Context {
29 /// Path at which the command is called, None when default
30 pub path: Option<PathBuf>,
31 /// Path to use for the Aleo registry, None when default
32 pub home: Option<PathBuf>,
33 /// Recursive flag.
34 // TODO: Shift from callee to caller by including display method
35 pub recursive: bool,
36}
37
38impl Context {
39 pub fn new(path: Option<PathBuf>, home: Option<PathBuf>, recursive: bool) -> Result<Context> {
40 Ok(Context { path, home, recursive })
41 }
42
43 /// Returns the path of the parent directory to the Leo package.
44 pub fn parent_dir(&self) -> Result<PathBuf> {
45 match &self.path {
46 Some(path) => {
47 let mut path = path.clone();
48 path.pop();
49 Ok(path)
50 }
51 None => Ok(current_dir().map_err(CliError::cli_io_error)?),
52 }
53 }
54
55 /// Returns the path to the Leo package.
56 pub fn dir(&self) -> Result<PathBuf> {
57 match &self.path {
58 Some(path) => Ok(path.clone()),
59 None => Ok(current_dir().map_err(CliError::cli_io_error)?),
60 }
61 }
62
63 /// Returns the path to the Aleo registry directory.
64 pub fn home(&self) -> Result<PathBuf> {
65 match &self.home {
66 Some(path) => Ok(path.clone()),
67 None => Ok(aleo_dir()),
68 }
69 }
70
71 /// Opens the manifest file `program.json`.
72 pub fn open_manifest(&self) -> Result<Manifest> {
73 let path = self.dir()?;
74 let manifest_path = path.join(leo_package::MANIFEST_FILENAME);
75 let manifest = Manifest::read_from_file(manifest_path)?;
76 Ok(manifest)
77 }
78}