leo_package/
package.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 crate::*;
18
19use leo_errors::{CliError, PackageError, Result, UtilError};
20use leo_passes::DiGraph;
21use leo_span::Symbol;
22
23use anyhow::anyhow;
24use indexmap::{IndexMap, map::Entry};
25use std::path::{Path, PathBuf};
26
27/// Either the bytecode of an Aleo program (if it was a network dependency) or
28/// a path to its source (if it was local).
29#[derive(Clone, Debug)]
30pub enum ProgramData {
31    Bytecode(String),
32    SourcePath(PathBuf),
33}
34
35/// A Leo package.
36#[derive(Clone, Debug)]
37pub struct Package {
38    /// The directory on the filesystem where the package is located, canonicalized.
39    pub base_directory: PathBuf,
40
41    /// A topologically sorted list of all programs in this package, whether
42    /// dependencies or the main program.
43    ///
44    /// Any program's dependent program will appear before it, so that compiling
45    /// them in order should give access to all stubs necessary to compile each
46    /// program.
47    pub programs: Vec<Program>,
48
49    /// The manifest file of this package.
50    pub manifest: Manifest,
51
52    /// The .env file of this package.
53    pub env: Env,
54}
55
56impl Package {
57    pub fn outputs_directory(&self) -> PathBuf {
58        self.base_directory.join(OUTPUTS_DIRECTORY)
59    }
60
61    pub fn imports_directory(&self) -> PathBuf {
62        self.base_directory.join(IMPORTS_DIRECTORY)
63    }
64
65    pub fn build_directory(&self) -> PathBuf {
66        self.base_directory.join(BUILD_DIRECTORY)
67    }
68
69    pub fn source_directory(&self) -> PathBuf {
70        self.base_directory.join(SOURCE_DIRECTORY)
71    }
72
73    pub fn tests_directory(&self) -> PathBuf {
74        self.base_directory.join(TESTS_DIRECTORY)
75    }
76
77    /// Create a Leo package by the name `package_name` in a subdirectory of `path`.
78    pub fn initialize<P: AsRef<Path>>(
79        package_name: &str,
80        path: P,
81        network: NetworkName,
82        endpoint: &str,
83    ) -> Result<PathBuf> {
84        Self::initialize_impl(package_name, path.as_ref(), network, endpoint)
85    }
86
87    fn initialize_impl(package_name: &str, path: &Path, network: NetworkName, endpoint: &str) -> Result<PathBuf> {
88        let package_name =
89            if package_name.ends_with(".aleo") { package_name.to_string() } else { format!("{package_name}.aleo") };
90
91        if !crate::is_valid_aleo_name(&package_name) {
92            return Err(CliError::invalid_program_name(package_name).into());
93        }
94
95        let path = path.canonicalize().map_err(|e| PackageError::failed_path(path.display(), e))?;
96        let full_path = path.join(package_name.strip_suffix(".aleo").unwrap());
97
98        // Verify that there is no existing directory at the path.
99        if full_path.exists() {
100            return Err(
101                PackageError::failed_to_initialize_package(package_name, &path, "Directory already exists").into()
102            );
103        }
104
105        // Create the package directory.
106        std::fs::create_dir(&full_path)
107            .map_err(|e| PackageError::failed_to_initialize_package(&package_name, &full_path, e))?;
108
109        // Change the current working directory to the package directory.
110        std::env::set_current_dir(&full_path)
111            .map_err(|e| PackageError::failed_to_initialize_package(&package_name, &full_path, e))?;
112
113        // Create the gitignore file.
114        const GITIGNORE_TEMPLATE: &str = ".env\n*.avm\n*.prover\n*.verifier\noutputs/\n";
115
116        const GITIGNORE_FILENAME: &str = ".gitignore";
117
118        let gitignore_path = full_path.join(GITIGNORE_FILENAME);
119
120        std::fs::write(gitignore_path, GITIGNORE_TEMPLATE).map_err(PackageError::io_error_gitignore_file)?;
121
122        // Create the .env file.
123        let env = Env { network, private_key: TEST_PRIVATE_KEY.to_string(), endpoint: endpoint.to_string() };
124
125        let env_path = full_path.join(ENV_FILENAME);
126
127        env.write_to_file(env_path)?;
128
129        // Create the manifest.
130        let manifest = Manifest {
131            program: package_name.clone(),
132            version: "0.1.0".to_string(),
133            description: String::new(),
134            license: "MIT".to_string(),
135            dependencies: None,
136            dev_dependencies: None,
137        };
138
139        let manifest_path = full_path.join(MANIFEST_FILENAME);
140
141        manifest.write_to_file(manifest_path)?;
142
143        // Create the source directory.
144        let source_path = full_path.join(SOURCE_DIRECTORY);
145
146        std::fs::create_dir(&source_path)
147            .map_err(|e| PackageError::failed_to_create_source_directory(source_path.display(), e))?;
148
149        // Create the main.leo file.
150        let main_path = source_path.join(MAIN_FILENAME);
151
152        let name_no_aleo = package_name.strip_suffix(".aleo").unwrap();
153
154        std::fs::write(&main_path, main_template(name_no_aleo))
155            .map_err(|e| UtilError::util_file_io_error(format_args!("Failed to write `{}`", main_path.display()), e))?;
156
157        // Create the tests directory.
158        let tests_path = full_path.join(TESTS_DIRECTORY);
159
160        std::fs::create_dir(&tests_path)
161            .map_err(|e| PackageError::failed_to_create_source_directory(tests_path.display(), e))?;
162
163        let test_file_path = tests_path.join(format!("test_{name_no_aleo}.leo"));
164        std::fs::write(&test_file_path, test_template(name_no_aleo))
165            .map_err(|e| UtilError::util_file_io_error(format_args!("Failed to write `{}`", main_path.display()), e))?;
166
167        Ok(full_path)
168    }
169
170    /// Examine the Leo package at `path` to create a `Package`, but don't find dependencies.
171    ///
172    /// This may be useful if you just need other information like the manifest or env file.
173    pub fn from_directory_no_graph<P: AsRef<Path>, Q: AsRef<Path>>(path: P, home_path: Q) -> Result<Self> {
174        Self::from_directory_impl(
175            path.as_ref(),
176            home_path.as_ref(),
177            /* build_graph */ false,
178            /* with_tests */ false,
179        )
180    }
181
182    /// Examine the Leo package at `path` to create a `Package`, including all its dependencies,
183    /// obtaining dependencies from the file system or network and topologically sorting them.
184    pub fn from_directory<P: AsRef<Path>, Q: AsRef<Path>>(path: P, home_path: Q) -> Result<Self> {
185        Self::from_directory_impl(
186            path.as_ref(),
187            home_path.as_ref(),
188            /* build_graph */ true,
189            /* with_tests */ false,
190        )
191    }
192
193    /// Examine the Leo package at `path` to create a `Package`, including all its dependencies
194    /// and its tests, obtaining dependencies from the file system or network and topologically sorting them.
195    pub fn from_directory_with_tests<P: AsRef<Path>, Q: AsRef<Path>>(path: P, home_path: Q) -> Result<Self> {
196        Self::from_directory_impl(
197            path.as_ref(),
198            home_path.as_ref(),
199            /* build_graph */ true,
200            /* with_tests */ true,
201        )
202    }
203
204    pub fn test_files(&self) -> impl Iterator<Item = PathBuf> {
205        let path = self.tests_directory();
206        // This allocation isn't ideal but it's not performance critical and
207        // easily resolves lifetime issues.
208        let data: Vec<PathBuf> = Self::files_with_extension(&path, "leo").collect();
209        data.into_iter()
210    }
211
212    pub fn import_files(&self) -> impl Iterator<Item = PathBuf> {
213        let path = self.imports_directory();
214        // This allocation isn't ideal but it's not performance critical and
215        // easily resolves lifetime issues.
216        let data: Vec<PathBuf> = Self::files_with_extension(&path, "aleo").collect();
217        data.into_iter()
218    }
219
220    fn files_with_extension(path: &Path, extension: &'static str) -> impl Iterator<Item = PathBuf> {
221        path.read_dir()
222            .ok()
223            .into_iter()
224            .flatten()
225            .flat_map(|maybe_filename| maybe_filename.ok())
226            .filter(|entry| entry.file_type().ok().map(|filetype| filetype.is_file()).unwrap_or(false))
227            .flat_map(move |entry| {
228                let path = entry.path();
229                if path.extension().is_some_and(|e| e == extension) { Some(path) } else { None }
230            })
231    }
232
233    fn from_directory_impl(path: &Path, home_path: &Path, build_graph: bool, with_tests: bool) -> Result<Self> {
234        let map_err = |path: &Path, err| {
235            UtilError::util_file_io_error(format_args!("Trying to find path at {}", path.display()), err)
236        };
237
238        let path = path.canonicalize().map_err(|err| map_err(path, err))?;
239
240        let env = Env::read_from_file_or_environment(path.join(ENV_FILENAME))?;
241
242        let manifest = Manifest::read_from_file(path.join(MANIFEST_FILENAME))?;
243
244        let programs: Vec<Program> = if build_graph {
245            let home_path = home_path.canonicalize().map_err(|err| map_err(home_path, err))?;
246
247            let mut map: IndexMap<Symbol, (Dependency, Program)> = IndexMap::new();
248
249            let mut digraph = DiGraph::<Symbol>::new(Default::default());
250
251            let first_dependency = Dependency {
252                name: manifest.program.clone(),
253                location: Location::Local,
254                network: None,
255                path: Some(path.clone()),
256            };
257
258            let test_dependencies: Vec<Dependency> = if with_tests {
259                let tests_directory = path.join(TESTS_DIRECTORY);
260                let mut test_dependencies: Vec<Dependency> = Self::files_with_extension(&tests_directory, "leo")
261                    .map(|path| Dependency {
262                        // We just made sure it has a ".leo" extension.
263                        name: format!("{}.aleo", crate::filename_no_leo_extension(&path).unwrap()),
264                        location: Location::Test,
265                        network: None,
266                        path: Some(path.to_path_buf()),
267                    })
268                    .collect();
269                if let Some(deps) = manifest.dev_dependencies.as_ref() {
270                    test_dependencies.extend(deps.iter().cloned());
271                }
272                test_dependencies
273            } else {
274                Vec::new()
275            };
276
277            for dependency in test_dependencies.into_iter().chain(std::iter::once(first_dependency.clone())) {
278                Self::graph_build(
279                    &home_path,
280                    env.network,
281                    &env.endpoint,
282                    &first_dependency,
283                    dependency,
284                    &mut map,
285                    &mut digraph,
286                )?;
287            }
288
289            let ordered_dependency_symbols =
290                digraph.post_order().map_err(|_| UtilError::circular_dependency_error())?;
291
292            ordered_dependency_symbols.into_iter().map(|symbol| map.swap_remove(&symbol).unwrap().1).collect()
293        } else {
294            Vec::new()
295        };
296
297        Ok(Package { base_directory: path, programs, env, manifest })
298    }
299
300    fn graph_build(
301        home_path: &Path,
302        network: NetworkName,
303        endpoint: &str,
304        main_program: &Dependency,
305        new: Dependency,
306        map: &mut IndexMap<Symbol, (Dependency, Program)>,
307        graph: &mut DiGraph<Symbol>,
308    ) -> Result<()> {
309        let name_symbol = crate::symbol(&new.name)?;
310
311        let program = match map.entry(name_symbol) {
312            Entry::Occupied(occupied) => {
313                // We've already visited this dependency. Just make sure it's compatible with
314                // the one we already have.
315                let existing_dep = &occupied.get().0;
316                assert_eq!(new.name, existing_dep.name);
317                if new.location != existing_dep.location || new.path != existing_dep.path {
318                    return Err(PackageError::conflicting_dependency(format_args!("{name_symbol}.aleo")).into());
319                }
320                return Ok(());
321            }
322            Entry::Vacant(vacant) => {
323                let program = match (new.path.as_ref(), new.location) {
324                    (Some(path), Location::Local) => {
325                        // It's a local dependency.
326                        Program::from_path(name_symbol, path.clone())?
327                    }
328                    (Some(path), Location::Test) => {
329                        // It's a test dependency - the path points to the source file,
330                        // not a package.
331                        Program::from_path_test(path, main_program.clone())?
332                    }
333                    (_, Location::Network) => {
334                        // It's a network dependency.
335                        Program::fetch(name_symbol, home_path, network, endpoint)?
336                    }
337                    _ => return Err(anyhow!("Invalid dependency data for {} (path must be given).", new.name).into()),
338                };
339
340                vacant.insert((new, program.clone()));
341
342                program
343            }
344        };
345
346        graph.add_node(name_symbol);
347
348        for dependency in program.dependencies.iter() {
349            let dependency_symbol = crate::symbol(&dependency.name)?;
350            graph.add_edge(name_symbol, dependency_symbol);
351            Self::graph_build(home_path, network, endpoint, main_program, dependency.clone(), map, graph)?;
352        }
353
354        Ok(())
355    }
356}
357
358fn main_template(name: &str) -> String {
359    format!(
360        r#"// The '{name}' program.
361program {name}.aleo {{
362    transition main(public a: u32, b: u32) -> u32 {{
363        let c: u32 = a + b;
364        return c;
365    }}
366}}
367"#
368    )
369}
370
371fn test_template(name: &str) -> String {
372    format!(
373        r#"// The 'test_{name}' test program.
374import {name}.aleo;
375program test_{name}.aleo {{
376    @test
377    script test_it() {{
378        let result: u32 = {name}.aleo/main(1u32, 2u32);
379        assert_eq(result, 3u32);
380    }}
381
382    @test
383    @should_fail
384    transition do_nothing() {{
385        let result: u32 = {name}.aleo/main(2u32, 3u32);
386        assert_eq(result, 3u32);
387    }}
388}}
389"#
390    )
391}