cairo_lang_project/
lib.rs

1//! Cairo project specification. For example, crates and flags used for compilation.
2#[cfg(test)]
3mod test;
4
5use std::path::{Path, PathBuf};
6
7use cairo_lang_filesystem::db::{CrateIdentifier, CrateSettings};
8use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
9use serde::{Deserialize, Serialize};
10
11#[derive(thiserror::Error, Debug)]
12pub enum DeserializationError {
13    #[error(transparent)]
14    TomlError(#[from] toml::de::Error),
15    #[error(transparent)]
16    IoError(#[from] std::io::Error),
17    #[error("PathError")]
18    PathError,
19}
20pub const PROJECT_FILE_NAME: &str = "cairo_project.toml";
21
22/// Cairo project config, including its file content and metadata about the file.
23/// This file is expected to be at a root of a crate and specify the crate name and location and
24/// of its dependency crates.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct ProjectConfig {
27    pub base_path: PathBuf,
28    pub content: ProjectConfigContent,
29}
30
31/// Contents of a Cairo project config file.
32#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
33pub struct ProjectConfigContent {
34    pub crate_roots: OrderedHashMap<CrateIdentifier, PathBuf>,
35    /// Additional configurations for the crates.
36    #[serde(default)]
37    #[serde(rename = "config")]
38    pub crates_config: AllCratesConfig,
39}
40
41/// Additional configurations for all crates.
42#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
43pub struct AllCratesConfig {
44    /// The configuration for non overridden crates.
45    #[serde(default)]
46    pub global: CrateSettings,
47    /// Configuration override per crate.
48    #[serde(default)]
49    #[serde(rename = "override")]
50    pub override_map: OrderedHashMap<CrateIdentifier, CrateSettings>,
51}
52
53impl AllCratesConfig {
54    /// Returns the configuration for the given crate.
55    pub fn get(&self, crate_identifier: &CrateIdentifier) -> &CrateSettings {
56        self.override_map.get(crate_identifier).unwrap_or(&self.global)
57    }
58}
59
60impl ProjectConfig {
61    pub fn from_directory(directory: &Path) -> Result<Self, DeserializationError> {
62        Self::from_file(&directory.join(PROJECT_FILE_NAME))
63    }
64    pub fn from_file(filename: &Path) -> Result<Self, DeserializationError> {
65        let base_path = filename
66            .parent()
67            .and_then(|p| p.to_str())
68            .ok_or(DeserializationError::PathError)?
69            .into();
70        let content = toml::from_str(&std::fs::read_to_string(filename)?)?;
71        Ok(ProjectConfig { base_path, content })
72    }
73
74    /// Returns the crate root's absolute path, according to the base path of this project.
75    pub fn absolute_crate_root(&self, root: &Path) -> PathBuf {
76        if root.is_relative() { self.base_path.join(root) } else { root.to_owned() }
77    }
78}