foundry_compilers/report/
compiler.rs1use foundry_compilers_artifacts::{CompilerOutput, SolcInput};
9use semver::Version;
10use std::{env, path::PathBuf, str::FromStr};
11
12#[derive(Clone, Debug, Default)]
27pub struct SolcCompilerIoReporter {
28 target: Option<Target>,
30}
31
32impl SolcCompilerIoReporter {
33 pub fn new(value: &str) -> Self {
36 Self { target: Some(value.parse().unwrap_or_default()) }
37 }
38
39 pub const DEFAULT_ENV: &'static str = "foundry_compilers_LOG";
44
45 pub fn from_default_env() -> Self {
48 Self::from_env(Self::DEFAULT_ENV)
49 }
50
51 pub fn from_env(env: impl AsRef<std::ffi::OsStr>) -> Self {
54 env::var(env).map(|var| Self::new(&var)).unwrap_or_default()
55 }
56
57 pub fn log_compiler_input(&self, input: &SolcInput, version: &Version) {
59 if let Some(target) = &self.target {
60 target.write_input(input, version)
61 }
62 }
63
64 pub fn log_compiler_output(&self, output: &CompilerOutput, version: &Version) {
66 if let Some(target) = &self.target {
67 target.write_output(output, version)
68 }
69 }
70}
71
72impl<S: AsRef<str>> From<S> for SolcCompilerIoReporter {
73 fn from(s: S) -> Self {
74 Self::new(s.as_ref())
75 }
76}
77
78#[derive(Clone, Debug, PartialEq, Eq)]
80struct Target {
81 dest_input: PathBuf,
83 dest_output: PathBuf,
85}
86
87impl Target {
88 fn write_input(&self, input: &SolcInput, version: &Version) {
89 trace!("logging compiler input to {}", self.dest_input.display());
90 match serde_json::to_string_pretty(input) {
91 Ok(json) => {
92 if let Err(err) = std::fs::write(get_file_name(&self.dest_input, version), json) {
93 error!("Failed to write compiler input: {}", err)
94 }
95 }
96 Err(err) => {
97 error!("Failed to serialize compiler input: {}", err)
98 }
99 }
100 }
101
102 fn write_output(&self, output: &CompilerOutput, version: &Version) {
103 trace!("logging compiler output to {}", self.dest_output.display());
104 match serde_json::to_string_pretty(output) {
105 Ok(json) => {
106 if let Err(err) = std::fs::write(get_file_name(&self.dest_output, version), json) {
107 error!("Failed to write compiler output: {}", err)
108 }
109 }
110 Err(err) => {
111 error!("Failed to serialize compiler output: {}", err)
112 }
113 }
114 }
115}
116
117impl Default for Target {
118 fn default() -> Self {
119 Self {
120 dest_input: "compiler-input.json".into(),
121 dest_output: "compiler-output.json".into(),
122 }
123 }
124}
125
126impl FromStr for Target {
127 type Err = Box<dyn std::error::Error + Send + Sync>;
128 fn from_str(s: &str) -> Result<Self, Self::Err> {
129 let mut dest_input = None;
130 let mut dest_output = None;
131 for part in s.split(',') {
132 let (name, val) =
133 part.split_once('=').ok_or_else(|| BadName { name: part.to_string() })?;
134 match name {
135 "i" | "in" | "input" | "compilerinput" => {
136 dest_input = Some(PathBuf::from(val));
137 }
138 "o" | "out" | "output" | "compileroutput" => {
139 dest_output = Some(PathBuf::from(val));
140 }
141 _ => return Err(BadName { name: part.to_string() }.into()),
142 };
143 }
144
145 Ok(Self {
146 dest_input: dest_input.unwrap_or_else(|| "compiler-input.json".into()),
147 dest_output: dest_output.unwrap_or_else(|| "compiler-output.json".into()),
148 })
149 }
150}
151
152#[derive(Clone, Debug, thiserror::Error)]
154#[error("{}", self.name)]
155pub struct BadName {
156 name: String,
157}
158
159fn get_file_name(path: impl Into<PathBuf>, v: &Version) -> PathBuf {
161 let mut path = path.into();
162 if let Some(stem) = path.file_stem().and_then(|s| s.to_str().map(|s| s.to_string())) {
163 path.set_file_name(format!("{stem}.{}.{}.{}.json", v.major, v.minor, v.patch));
164 }
165 path
166}
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171 use std::fs;
172 use tempfile::tempdir;
173
174 #[test]
175 fn can_set_file_name() {
176 let s = "/a/b/c/in.json";
177 let p = get_file_name(s, &Version::new(0, 8, 10));
178 assert_eq!(PathBuf::from("/a/b/c/in.0.8.10.json"), p);
179
180 let s = "abc.json";
181 let p = get_file_name(s, &Version::new(0, 8, 10));
182 assert_eq!(PathBuf::from("abc.0.8.10.json"), p);
183 }
184
185 #[test]
186 fn can_parse_target() {
187 let target: Target = "in=in.json,out=out.json".parse().unwrap();
188 assert_eq!(target, Target { dest_input: "in.json".into(), dest_output: "out.json".into() });
189
190 let target: Target = "in=in.json".parse().unwrap();
191 assert_eq!(target, Target { dest_input: "in.json".into(), ..Default::default() });
192
193 let target: Target = "out=out.json".parse().unwrap();
194 assert_eq!(target, Target { dest_output: "out.json".into(), ..Default::default() });
195 }
196
197 #[test]
198 fn can_init_reporter_from_env() {
199 let rep = SolcCompilerIoReporter::from_default_env();
200 assert!(rep.target.is_none());
201 std::env::set_var("foundry_compilers_LOG", "in=in.json,out=out.json");
202 let rep = SolcCompilerIoReporter::from_default_env();
203 assert!(rep.target.is_some());
204 assert_eq!(
205 rep.target.unwrap(),
206 Target { dest_input: "in.json".into(), dest_output: "out.json".into() }
207 );
208 std::env::remove_var("foundry_compilers_LOG");
209 }
210
211 #[test]
212 fn check_no_write_when_no_target() {
213 let reporter = SolcCompilerIoReporter::default();
214 let version = Version::parse("0.8.10").unwrap();
215 let input = SolcInput::default();
216 let output = CompilerOutput::default();
217
218 reporter.log_compiler_input(&input, &version);
219 reporter.log_compiler_output(&output, &version);
220 }
221
222 #[test]
223 fn serialize_and_write_to_file() {
224 let dir = tempdir().unwrap();
225 let input_path = dir.path().join("input.json");
226 let output_path = dir.path().join("output.json");
227 let version = Version::parse("0.8.10").unwrap();
228 let target = Target { dest_input: input_path.clone(), dest_output: output_path.clone() };
229
230 let input = SolcInput::default();
231 let output = CompilerOutput::default();
232
233 target.write_input(&input, &version);
234 target.write_output(&output, &version);
235
236 let input_content = fs::read_to_string(get_file_name(&input_path, &version)).unwrap();
237 let output_content = fs::read_to_string(get_file_name(&output_path, &version)).unwrap();
238
239 assert!(!input_content.is_empty());
240 assert!(!output_content.is_empty());
241
242 dir.close().unwrap();
243 }
244}