revive_solc_json_interface/standard_json/input/
source.rs1use std::path::Path;
4use std::path::PathBuf;
5use std::sync::OnceLock;
6
7use serde::Deserialize;
8use serde::Serialize;
9
10pub const STDIN_PATH: &str = "-";
12
13pub const STDIN_SOURCE_NAME: &str = "<stdin>";
15
16static STDIN_CONTENT: OnceLock<Result<String, String>> = OnceLock::new();
18
19#[derive(Clone, Debug, Serialize, Deserialize)]
21#[serde(rename_all = "camelCase")]
22pub struct Source {
23 #[serde(skip_serializing_if = "Option::is_none")]
25 pub content: Option<String>,
26 #[serde(skip_serializing_if = "Option::is_none")]
28 pub urls: Option<Vec<String>>,
29 #[serde(skip_serializing_if = "Option::is_none")]
31 pub keccak256: Option<String>,
32}
33
34impl Source {
35 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 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 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 pub fn take_content(&mut self) -> Option<String> {
105 self.content.take()
106 }
107
108 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}