Skip to main content

revive_solc_json_interface/standard_json/input/
source.rs

1//! The `solc --standard-json` input source.
2
3use std::path::Path;
4use std::path::PathBuf;
5use std::sync::OnceLock;
6
7use serde::Deserialize;
8use serde::Serialize;
9
10/// The input path that selects the standard input.
11pub const STDIN_PATH: &str = "-";
12
13/// The source unit name `solc` gives to the standard input.
14pub const STDIN_SOURCE_NAME: &str = "<stdin>";
15
16/// The standard input content, read at most once since it can only be consumed once.
17static STDIN_CONTENT: OnceLock<Result<String, String>> = OnceLock::new();
18
19/// The `solc --standard-json` input source.
20#[derive(Clone, Debug, Serialize, Deserialize)]
21#[serde(rename_all = "camelCase")]
22pub struct Source {
23    /// The source code file content.
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub content: Option<String>,
26    /// The source file URLs.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub urls: Option<Vec<String>>,
29    /// The expected source code hash.
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub keccak256: Option<String>,
32}
33
34impl Source {
35    /// Returns the source unit name of the input `path`.
36    pub fn name(path: &Path) -> String {
37        let name = path.to_string_lossy();
38        if name == STDIN_PATH {
39            STDIN_SOURCE_NAME.to_owned()
40        } else {
41            name.to_string()
42        }
43    }
44
45    /// Reads the source from the file system, or from the standard input if `path` is [`STDIN_PATH`].
46    ///
47    /// The standard input is consumed on the first read and the same content is returned afterwards.
48    pub fn try_read(path: &Path) -> anyhow::Result<Self> {
49        let content = if path.to_string_lossy() == STDIN_PATH {
50            STDIN_CONTENT
51                .get_or_init(|| {
52                    std::io::read_to_string(std::io::stdin()).map_err(|error| error.to_string())
53                })
54                .clone()
55                .map_err(|error| anyhow::anyhow!("{STDIN_SOURCE_NAME} reading: {error}"))
56        } else {
57            std::fs::read_to_string(path)
58                .map_err(|error| anyhow::anyhow!("File {path:?} reading: {error}"))
59        }?;
60
61        Ok(Self {
62            content: Some(content),
63            urls: None,
64            keccak256: None,
65        })
66    }
67
68    /// Tries to resolve the source code.
69    ///
70    /// At the moment only one URL pointing to the file system is supported.
71    pub fn try_resolve(&mut self) -> anyhow::Result<()> {
72        match (self.content.as_ref(), self.urls.as_ref()) {
73            (Some(_), None) => Ok(()),
74            (None, Some(urls)) => {
75                let mut errors = Vec::with_capacity(urls.len());
76                for url in urls.iter() {
77                    let url_path = PathBuf::from(url);
78                    match Source::try_read(url_path.as_path()) {
79                        Ok(resolved) => {
80                            *self = resolved;
81                            break;
82                        }
83                        Err(error) => errors.push(error),
84                    }
85                }
86                if !errors.is_empty() {
87                    anyhow::bail!(
88                        "{}",
89                        errors
90                            .into_iter()
91                            .map(|error| error.to_string())
92                            .collect::<Vec<String>>()
93                            .join("\n")
94                    );
95                }
96                Ok(())
97            }
98            (Some(_), Some(_)) => anyhow::bail!("Both `content` and `urls` cannot be set."),
99            (None, None) => anyhow::bail!("Either `content` or `urls` must be set."),
100        }
101    }
102
103    /// Takes ownership of the source code and returns it.
104    pub fn take_content(&mut self) -> Option<String> {
105        self.content.take()
106    }
107
108    /// Returns the source code reference, if the source has been previously read or resolved.
109    pub fn content(&self) -> Option<&str> {
110        self.content.as_deref()
111    }
112}
113
114impl From<String> for Source {
115    fn from(content: String) -> Self {
116        Self {
117            content: Some(content),
118            urls: None,
119            keccak256: None,
120        }
121    }
122}
123
124impl From<&Path> for Source {
125    fn from(path: &Path) -> Self {
126        Self {
127            content: None,
128            urls: Some(vec![path.to_string_lossy().to_string()]),
129            keccak256: None,
130        }
131    }
132}