-
Notifications
You must be signed in to change notification settings - Fork 2.3k
feat(lint): geiger #11377
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat(lint): geiger #11377
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
33a7600
feat(lint): geiger
0xrusowsky 4ab28b7
keep cmd as alias
0xrusowsky ebb9f2b
fix: print warning
0xrusowsky c604abc
fix: expected test output
0xrusowsky 3a9da12
simplify claude's shit lol
0xrusowsky ddfac60
style: clippy
0xrusowsky File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,162 +1,57 @@ | ||
| use clap::{Parser, ValueHint}; | ||
| use eyre::{Result, WrapErr}; | ||
| use foundry_cli::utils::LoadConfig; | ||
| use foundry_compilers::{Graph, resolver::parse::SolData}; | ||
| use foundry_config::{Config, impl_figment_convert_basic}; | ||
| use itertools::Itertools; | ||
| use solar_parse::{ast, ast::visit::Visit, interface::Session}; | ||
| use std::{ | ||
| ops::ControlFlow, | ||
| path::{Path, PathBuf}, | ||
| }; | ||
| use eyre::Result; | ||
| use foundry_cli::opts::BuildOpts; | ||
| use foundry_config::impl_figment_convert; | ||
| use std::path::PathBuf; | ||
|
|
||
| /// CLI arguments for `forge geiger`. | ||
| /// | ||
| /// This command is an alias for `forge lint --only-lint unsafe-cheatcode` | ||
| /// and detects usage of unsafe cheat codes in a project and its dependencies. | ||
| #[derive(Clone, Debug, Parser)] | ||
| pub struct GeigerArgs { | ||
| /// Paths to files or directories to detect. | ||
| #[arg( | ||
| conflicts_with = "root", | ||
| value_hint = ValueHint::FilePath, | ||
| value_name = "PATH", | ||
| num_args(1..), | ||
| num_args(0..) | ||
| )] | ||
| paths: Vec<PathBuf>, | ||
|
|
||
| /// The project's root path. | ||
| /// | ||
| /// By default root of the Git repository, if in one, | ||
| /// or the current working directory. | ||
| #[arg(long, value_hint = ValueHint::DirPath, value_name = "PATH")] | ||
| root: Option<PathBuf>, | ||
|
|
||
| /// Globs to ignore. | ||
| #[arg( | ||
| long, | ||
| value_hint = ValueHint::FilePath, | ||
| value_name = "PATH", | ||
| num_args(1..), | ||
| )] | ||
| ignore: Vec<PathBuf>, | ||
|
|
||
| #[arg(long, hide = true)] | ||
| check: bool, | ||
|
|
||
| #[arg(long, hide = true)] | ||
| full: bool, | ||
|
|
||
| #[command(flatten)] | ||
| build: BuildOpts, | ||
| } | ||
|
|
||
| impl_figment_convert_basic!(GeigerArgs); | ||
| impl_figment_convert!(GeigerArgs, build); | ||
|
|
||
| impl GeigerArgs { | ||
| pub fn sources(&self, config: &Config) -> Result<Vec<PathBuf>> { | ||
| let cwd = std::env::current_dir()?; | ||
|
|
||
| let mut sources: Vec<PathBuf> = { | ||
| if self.paths.is_empty() { | ||
| let paths = config.project_paths(); | ||
| Graph::<SolData>::resolve(&paths)? | ||
| .files() | ||
| .keys() | ||
| .filter(|f| !paths.has_library_ancestor(f)) | ||
| .cloned() | ||
| .collect() | ||
| } else { | ||
| self.paths | ||
| .iter() | ||
| .flat_map(|path| foundry_common::fs::files_with_ext(path, "sol")) | ||
| .unique() | ||
| .collect() | ||
| } | ||
| }; | ||
|
|
||
| sources.retain_mut(|path| { | ||
| let abs_path = if path.is_absolute() { path.clone() } else { cwd.join(&path) }; | ||
| *path = abs_path.strip_prefix(&cwd).unwrap_or(&abs_path).to_path_buf(); | ||
| !self.ignore.iter().any(|ignore| { | ||
| if ignore.is_absolute() { | ||
| abs_path.starts_with(ignore) | ||
| } else { | ||
| abs_path.starts_with(cwd.join(ignore)) | ||
| } | ||
| }) | ||
| }); | ||
|
|
||
| Ok(sources) | ||
| } | ||
|
|
||
| pub fn run(self) -> Result<usize> { | ||
| pub fn run(self) -> Result<()> { | ||
| // Deprecated flags warnings | ||
| if self.check { | ||
| sh_warn!("`--check` is deprecated as it's now the default behavior\n")?; | ||
| } | ||
| if self.full { | ||
| sh_warn!("`--full` is deprecated as reports are not generated anymore\n")?; | ||
| } | ||
|
|
||
| let config = self.load_config()?; | ||
| let sources = self.sources(&config).wrap_err("Failed to resolve files")?; | ||
|
|
||
| if config.ffi { | ||
| sh_warn!("FFI enabled\n")?; | ||
| } | ||
|
|
||
| let mut sess = Session::builder().with_stderr_emitter().build(); | ||
| sess.dcx = sess.dcx.set_flags(|flags| flags.track_diagnostics = false); | ||
| let unsafe_cheatcodes = &[ | ||
| "ffi".to_string(), | ||
| "readFile".to_string(), | ||
| "readLine".to_string(), | ||
| "writeFile".to_string(), | ||
| "writeLine".to_string(), | ||
| "removeFile".to_string(), | ||
| "closeFile".to_string(), | ||
| "setEnv".to_string(), | ||
| "deriveKey".to_string(), | ||
| ]; | ||
| Ok(sess | ||
| .enter(|| sources.iter().map(|file| lint_file(&sess, unsafe_cheatcodes, file)).sum())) | ||
| } | ||
| } | ||
|
|
||
| fn lint_file(sess: &Session, unsafe_cheatcodes: &[String], path: &Path) -> usize { | ||
| try_lint_file(sess, unsafe_cheatcodes, path).unwrap_or(0) | ||
| } | ||
|
|
||
| fn try_lint_file( | ||
| sess: &Session, | ||
| unsafe_cheatcodes: &[String], | ||
| path: &Path, | ||
| ) -> solar_parse::interface::Result<usize> { | ||
| let arena = solar_parse::ast::Arena::new(); | ||
| let mut parser = solar_parse::Parser::from_file(sess, &arena, path)?; | ||
| let ast = parser.parse_file().map_err(|e| e.emit())?; | ||
| let mut visitor = Visitor::new(sess, unsafe_cheatcodes); | ||
| let _ = visitor.visit_source_unit(&ast); | ||
| Ok(visitor.count) | ||
| } | ||
| sh_println!("Running forge geiger (alias for: forge lint --only-lint unsafe-cheatcode)\n")?; | ||
|
|
||
| struct Visitor<'a> { | ||
| sess: &'a Session, | ||
| count: usize, | ||
| unsafe_cheatcodes: &'a [String], | ||
| } | ||
|
|
||
| impl<'a> Visitor<'a> { | ||
| fn new(sess: &'a Session, unsafe_cheatcodes: &'a [String]) -> Self { | ||
| Self { sess, count: 0, unsafe_cheatcodes } | ||
| } | ||
| } | ||
|
|
||
| impl<'ast> Visit<'ast> for Visitor<'_> { | ||
| type BreakValue = solar_parse::interface::data_structures::Never; | ||
| // Convert geiger command to lint command with specific lint filter | ||
| let lint_args = crate::cmd::lint::LintArgs { | ||
| paths: self.paths, | ||
| severity: None, | ||
| lint: Some(vec!["unsafe-cheatcode".to_string()]), | ||
| json: false, | ||
| build: self.build, | ||
| }; | ||
|
|
||
| fn visit_expr(&mut self, expr: &'ast ast::Expr<'ast>) -> ControlFlow<Self::BreakValue> { | ||
| if let ast::ExprKind::Call(lhs, _args) = &expr.kind | ||
| && let ast::ExprKind::Member(_lhs, member) = &lhs.kind | ||
| && self.unsafe_cheatcodes.iter().any(|c| c.as_str() == member.as_str()) | ||
| { | ||
| let msg = format!("usage of unsafe cheatcode `vm.{member}`"); | ||
| self.sess.dcx.err(msg).span(member.span).emit(); | ||
| self.count += 1; | ||
| } | ||
| self.walk_expr(expr) | ||
| // Run the lint command with the geiger-specific configuration | ||
| lint_args.run() | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.