Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

scan: run through uv run, poetry run and other Python env runners (#34)

chessMan76f449fcfbb0
diff --git a/src/backend.rs b/src/backend.rs
index 64e9013..27d8f88 100644
--- a/src/backend.rs
+++ b/src/backend.rs
@@ -45,6 +45,19 @@ pub struct Recording {
pub mutates: bool,
}
+/// Launchers that can't be unwrapped the way uv run or poetry run are (see python::unwrap_env_runner).
+fn wrapper_hint(program: &str) -> Option<&'static str> {
+ Some(match crate::util::program_stem(program).as_str() {
+ "tsx" | "ts-node" | "npx" => {
+ "Node.js 22.6+ runs TypeScript itself, and fast-anything needs node to start the app:\n fast-anything scan -- node app.ts"
+ }
+ "bundle" => {
+ "bundle exec sets up gems for its own process only. Scan with ruby directly, and if the app needs Bundler, put require \"bundler/setup\" at the top of its script:\n fast-anything scan -- ruby app.rb"
+ }
+ _ => return None,
+ })
+}
+
impl Lang {
pub fn detect(program: &str) -> Result<Lang> {
if python::is_python(program) {
@@ -63,6 +76,8 @@ impl Lang {
Ok(Lang::CSharp)
} else if let Some(lang) = cfamily::detect(program) {
Ok(lang)
+ } else if let Some(hint) = wrapper_hint(program) {
+ bail!("{hint}")
} else {
bail!(
"fast-anything speaks Python, Node.js (JavaScript/TypeScript), Ruby, Java, Go, PHP, C, C++ and C#. Start the command with one of them:\n fast-anything scan -- python app.py\n fast-anything scan -- node app.js\n fast-anything scan -- ruby app.rb\n fast-anything scan -- java App.java\n fast-anything scan -- go run .\n fast-anything scan -- php app.php\n fast-anything scan -- clang -O2 main.c (or gcc, g++, clang++, icpx)\n fast-anything scan -- dotnet run -c Release"
@@ -373,6 +388,14 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
+ #[test]
+ fn launchers_get_a_hint() {
+ assert!(Lang::detect("npx").unwrap_err().to_string().contains("node app.ts"));
+ assert!(Lang::detect("tsx").unwrap_err().to_string().contains("node app.ts"));
+ assert!(Lang::detect("bundle").unwrap_err().to_string().contains("bundler/setup"));
+ assert!(Lang::detect("cobol").unwrap_err().to_string().starts_with("fast-anything speaks"));
+ }
+
#[test]
fn blocks_come_out_byte_for_byte() {
let guard = |t: &str| line_starting(t, &["if__name__==\"__main__\":", "if__name__=='__main__':"]);
diff --git a/src/pipeline.rs b/src/pipeline.rs
index a2ddb35..fb9368c 100644
--- a/src/pipeline.rs
+++ b/src/pipeline.rs
@@ -24,6 +24,13 @@ pub fn scan(root: &Path, command: Vec<String>) -> Result<ScanOut> {
"put the command that runs your app after --, e.g. fast-anything scan -- python app.py"
);
let mut ctx = Ctx::open(root)?;
+ let command = match crate::python::unwrap_env_runner(&command, |argv| env_runner_output(&ctx.root, argv))? {
+ Some(unwrapped) => {
+ ui::step(format!("{} runs {}", ui::bold(command[..2].join(" ")), ui::bold(&unwrapped[0])));
+ unwrapped
+ }
+ None => command,
+ };
let lang = crate::cfamily::refine(Lang::detect(&command[0])?, &command[1..]);
let exe = lang.resolve(&command[0], &ctx.root)?;
ui::step(format!("profiling {}", ui::bold(command.join(" "))));
@@ -39,6 +46,13 @@ pub fn scan(root: &Path, command: Vec<String>) -> Result<ScanOut> {
Ok(ScanOut { command, wall: profile.wall, hotspots })
}
+/// What an env runner (uv, poetry, ...) prints for a command run in the project.
+fn env_runner_output(root: &Path, argv: &[&str]) -> Result<String> {
+ let out = util::output(std::process::Command::new(argv[0]).args(&argv[1..]).current_dir(root), argv[0])?;
+ ensure!(out.status.success(), "{} failed:\n{}", argv.join(" "), util::tail(&util::combined(&out), 10));
+ Ok(String::from_utf8_lossy(&out.stdout).into_owned())
+}
+
fn pick<'a>(hotspots: &'a [Hotspot], id: Option<&str>) -> Result<&'a Hotspot> {
let Some(id) = id else {
return hotspots
diff --git a/src/python.rs b/src/python.rs
index 6984b01..cb8f204 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -20,6 +20,39 @@ pub fn is_python(program: &str) -> bool {
stem == "py" || stem.starts_with("python") || stem.starts_with("pypy")
}
+/// Tools that run a command inside a project's virtualenv: `uv run app.py`, `poetry run python app.py`.
+const ENV_RUNNERS: &[&str] = &["uv", "poetry", "pipenv", "pdm", "hatch", "rye"];
+
+/// `uv run [python] app.py ...` (and the other ENV_RUNNERS) as `<the env's python> app.py ...`, so
+/// every later run uses the same interpreter and packages. `query` runs the runner's own python
+/// and returns what it prints. None when the command doesn't start with a runner.
+pub fn unwrap_env_runner(command: &[String], query: impl Fn(&[&str]) -> Result<String>) -> Result<Option<Vec<String>>> {
+ let runner = crate::util::program_stem(command.first().map(String::as_str).unwrap_or_default());
+ if !ENV_RUNNERS.contains(&runner.as_str()) || command.get(1).map(String::as_str) != Some("run") {
+ return Ok(None);
+ }
+ let mut rest = &command[2..];
+ if rest.first().is_some_and(|a| is_python(a)) {
+ rest = &rest[1..];
+ }
+ let shown = command[..2].join(" ");
+ match rest.first().map(String::as_str) {
+ None => bail!("name the script after {shown}, e.g. fast-anything scan -- {shown} app.py"),
+ Some(a) if a.starts_with('-') && a != "-m" => bail!(
+ "fast-anything can't pass options to {shown}. Get its interpreter with {shown} python -c \"import sys; print(sys.executable)\" and scan with that: fast-anything scan -- <that python> app.py"
+ ),
+ Some(a) if a != "-m" && !a.ends_with(".py") => bail!(
+ "{a} isn't a .py script. Run the code it starts as {shown} python -m <module> or {shown} python <script>.py"
+ ),
+ _ => {}
+ }
+ let mut ask = command[..2].iter().map(String::as_str).collect::<Vec<_>>();
+ ask.extend(["python", "-c", "import sys; print(sys.executable)"]);
+ let exe = query(&ask)?.trim().to_string();
+ ensure!(!exe.is_empty(), "{shown} didn't say which python it uses");
+ Ok(Some(std::iter::once(exe).chain(rest.iter().cloned()).collect()))
+}
+
/// The absolute interpreter path behind python, python3, py, .venv/bin/python, ...
pub fn resolve(program: &str, root: &Path) -> Result<String> {
if !is_python(program) {
@@ -695,6 +728,24 @@ mod tests {
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
+ #[test]
+ fn env_runners_resolve_to_their_python() {
+ let cmd = |s: &str| s.split_whitespace().map(String::from).collect::<Vec<_>>();
+ let query = |argv: &[&str]| -> Result<String> {
+ assert_eq!(&argv[1..], ["run", "python", "-c", "import sys; print(sys.executable)"]);
+ Ok(format!("/proj/.venv-{}/bin/python\n", argv[0]))
+ };
+ let got = |s: &str| unwrap_env_runner(&cmd(s), query);
+ assert_eq!(got("uv run app.py data.txt").unwrap().unwrap(), cmd("/proj/.venv-uv/bin/python app.py data.txt"));
+ assert_eq!(got("poetry run python app.py").unwrap().unwrap(), cmd("/proj/.venv-poetry/bin/python app.py"));
+ assert_eq!(got("pdm run python3 -m pkg").unwrap().unwrap(), cmd("/proj/.venv-pdm/bin/python -m pkg"));
+ assert!(got("python app.py").unwrap().is_none());
+ assert!(got("uv pip list").unwrap().is_none());
+ assert!(got("uv run --with numpy app.py").unwrap_err().to_string().contains("can't pass options"));
+ assert!(got("uv run pytest").unwrap_err().to_string().contains("isn't a .py script"));
+ assert!(got("uv run").is_err());
+ }
+
#[test]
fn spots_python() {
assert!(is_python("python"));