piano 0.4.0

Automated instrumentation-based profiling for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::path::{Path, PathBuf};
use std::process::Command;

use ignore::WalkBuilder;
use toml_edit::DocumentMut;

use crate::error::Error;

/// Copy the user's project into a staging directory, respecting .gitignore
/// and skipping the `target/` directory.
pub fn prepare_staging(project_root: &Path, staging_dir: &Path) -> Result<(), Error> {
    let walker = WalkBuilder::new(project_root)
        .hidden(false)
        .filter_entry(|entry| {
            // Skip target/ only at the project root level (depth 1).
            entry.depth() != 1 || entry.file_name().to_string_lossy() != "target"
        })
        .build();

    for entry in walker {
        let entry = entry.map_err(|e| std::io::Error::other(e.to_string()))?;
        let source = entry.path();
        let relative = source
            .strip_prefix(project_root)
            .map_err(|e| std::io::Error::other(e.to_string()))?;

        let dest = staging_dir.join(relative);

        if entry.file_type().is_some_and(|ft| ft.is_dir()) {
            std::fs::create_dir_all(&dest)?;
        } else if entry.file_type().is_some_and(|ft| ft.is_file()) {
            if let Some(parent) = dest.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::copy(source, &dest)?;
        }
    }

    Ok(())
}

/// How to reference piano-runtime in the staged Cargo.toml.
pub(crate) enum RuntimeSource<'a> {
    /// Published crate version (e.g. "0.1.0").
    Version(&'a str),
    /// Local path (for development before publishing).
    Path(&'a Path),
}

/// Add `piano-runtime` as a dependency in the staged project's Cargo.toml.
/// Uses `toml_edit` for structured manipulation (never string replacement).
pub fn inject_runtime_dependency(staging_dir: &Path, runtime_version: &str) -> Result<(), Error> {
    inject_runtime(staging_dir, RuntimeSource::Version(runtime_version))
}

/// Add `piano-runtime` as a path dependency in the staged project's Cargo.toml.
pub fn inject_runtime_path_dependency(
    staging_dir: &Path,
    runtime_path: &Path,
) -> Result<(), Error> {
    inject_runtime(staging_dir, RuntimeSource::Path(runtime_path))
}

fn inject_runtime(staging_dir: &Path, source: RuntimeSource<'_>) -> Result<(), Error> {
    let cargo_toml_path = staging_dir.join("Cargo.toml");
    let content = std::fs::read_to_string(&cargo_toml_path)?;

    let mut doc: DocumentMut = content
        .parse::<DocumentMut>()
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;

    // Ensure [dependencies] table exists.
    if !doc.contains_table("dependencies") {
        doc["dependencies"] = toml_edit::Item::Table(toml_edit::Table::new());
    }

    match source {
        RuntimeSource::Version(v) => {
            doc["dependencies"]["piano-runtime"] = toml_edit::value(v);
        }
        RuntimeSource::Path(p) => {
            let mut table = toml_edit::InlineTable::new();
            table.insert("path", p.to_string_lossy().as_ref().into());
            doc["dependencies"]["piano-runtime"] =
                toml_edit::Item::Value(toml_edit::Value::InlineTable(table));
        }
    }

    std::fs::write(&cargo_toml_path, doc.to_string())?;

    Ok(())
}

/// Extract human-readable compiler errors from cargo's JSON output.
fn extract_rendered_errors(json_output: &str) -> Vec<String> {
    json_output
        .lines()
        .filter_map(|line| {
            let msg: serde_json::Value = serde_json::from_str(line).ok()?;
            if msg.get("reason")?.as_str()? != "compiler-message" {
                return None;
            }
            msg.get("message")?
                .get("rendered")?
                .as_str()
                .map(String::from)
        })
        .collect()
}

/// Find the workspace root for a project directory.
///
/// Walks up from `project_dir` looking for the nearest parent `Cargo.toml`
/// containing a `[workspace]` table. Does not validate that this project
/// is an actual member of the workspace -- Cargo will catch mismatches at
/// build time. Returns `None` if no workspace root is found.
pub fn find_workspace_root(project_dir: &Path) -> Option<PathBuf> {
    let project_dir = project_dir.canonicalize().ok()?;
    let mut dir = project_dir.parent()?;
    loop {
        let cargo_toml = dir.join("Cargo.toml");
        if cargo_toml.exists() {
            let content = std::fs::read_to_string(&cargo_toml).ok()?;
            let doc: DocumentMut = content.parse().ok()?;
            if doc.get("workspace").is_some() {
                return Some(dir.to_path_buf());
            }
        }
        dir = dir.parent()?;
    }
}

/// Find the binary entry point for a Cargo project.
///
/// Reads `Cargo.toml` and resolves the entry point using Cargo's rules:
///
/// 1. `[[bin]]` entries with an explicit `path` field -- returns the first match.
/// 2. `[[bin]]` entries with a `name` but no `path` -- infers the source as
///    `src/bin/<name>.rs` or `src/bin/<name>/main.rs` (Cargo's convention).
/// 3. Falls back to `src/main.rs` if no `[[bin]]` section or no matches.
///
/// When multiple `[[bin]]` entries exist, the first match (in declaration order)
/// is used. Returns an error if no entry point can be found.
pub fn find_bin_entry_point(project_dir: &Path) -> Result<PathBuf, Error> {
    let cargo_toml_path = project_dir.join("Cargo.toml");
    let content = std::fs::read_to_string(&cargo_toml_path)?;
    let doc: DocumentMut = content
        .parse::<DocumentMut>()
        .map_err(|e| Error::BuildFailed(format!("failed to parse Cargo.toml: {e}")))?;

    if let Some(bins) = doc.get("bin").and_then(|b| b.as_array_of_tables()) {
        // First pass: check for an explicit path.
        for bin in bins {
            if let Some(path) = bin.get("path").and_then(|p| p.as_str()) {
                return Ok(PathBuf::from(path));
            }
        }

        // Second pass: infer from name (src/bin/<name>.rs or src/bin/<name>/main.rs).
        for bin in bins {
            if let Some(name) = bin.get("name").and_then(|n| n.as_str()) {
                let single_file = PathBuf::from("src").join("bin").join(format!("{name}.rs"));
                if project_dir.join(&single_file).exists() {
                    return Ok(single_file);
                }

                let dir_main = PathBuf::from("src").join("bin").join(name).join("main.rs");
                if project_dir.join(&dir_main).exists() {
                    return Ok(dir_main);
                }
            }
        }
    }

    // Cargo default: src/main.rs
    let default = PathBuf::from("src").join("main.rs");
    if project_dir.join(&default).exists() {
        return Ok(default);
    }

    Err(Error::BuildFailed(format!(
        "could not find binary entry point: no [[bin]] path in Cargo.toml and {} does not exist",
        project_dir.join(&default).display()
    )))
}

/// Build the instrumented binary using `cargo build --message-format=json`.
/// Returns the path to the compiled executable.
///
/// When `package` is `Some`, passes `-p <name>` to cargo to build a specific
/// workspace member (used when staging an entire workspace).
pub fn build_instrumented(
    staging_dir: &Path,
    target_dir: &Path,
    package: Option<&str>,
) -> Result<PathBuf, Error> {
    // Remove RUSTUP_TOOLCHAIN so the target project's rust-toolchain.toml
    // is respected. Without this, nested cargo invocations inherit the
    // parent's toolchain, ignoring the project's pinned version.
    let mut cmd = Command::new("cargo");
    cmd.arg("build")
        .arg("--message-format=json")
        .env("CARGO_TARGET_DIR", target_dir)
        .env_remove("RUSTUP_TOOLCHAIN")
        .current_dir(staging_dir);
    if let Some(pkg) = package {
        cmd.arg("-p").arg(pkg);
    }
    let output = cmd.output()?;

    if !output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let rendered = extract_rendered_errors(&stdout);
        if rendered.is_empty() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::BuildFailed(stderr.into_owned()));
        }
        return Err(Error::BuildFailed(rendered.join("")));
    }

    // Parse JSON lines to find the last compiler-artifact with an executable.
    // Cargo emits dependencies first; the project's own binary comes last.
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut binary_path = None;
    for line in stdout.lines() {
        let Ok(msg) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        if msg.get("reason").and_then(|r| r.as_str()) == Some("compiler-artifact")
            && let Some(exe) = msg.get("executable").and_then(|e| e.as_str())
        {
            binary_path = Some(PathBuf::from(exe));
        }
    }

    binary_path
        .ok_or_else(|| Error::BuildFailed("no executable found in cargo build output".into()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    /// Helper: create a file within a directory, creating parents as needed.
    fn create_file(base: &Path, relative: &str, content: &str) {
        let path = base.join(relative);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, content).unwrap();
    }

    #[test]
    fn staging_copies_project_structure() {
        let project = TempDir::new().unwrap();
        let staging = TempDir::new().unwrap();

        create_file(project.path(), "Cargo.toml", "[package]\nname = \"demo\"");
        create_file(project.path(), "src/main.rs", "fn main() {}");
        create_file(project.path(), "src/lib.rs", "pub fn lib() {}");
        create_file(project.path(), "src/util/helper.rs", "pub fn help() {}");

        // Also create a target/ dir that should be skipped
        create_file(project.path(), "target/debug/demo", "binary-content");

        prepare_staging(project.path(), staging.path()).unwrap();

        assert!(staging.path().join("Cargo.toml").exists());
        assert!(staging.path().join("src/main.rs").exists());
        assert!(staging.path().join("src/lib.rs").exists());
        assert!(staging.path().join("src/util/helper.rs").exists());
        assert!(!staging.path().join("target").exists());

        // Verify content was copied correctly
        let content = std::fs::read_to_string(staging.path().join("Cargo.toml")).unwrap();
        assert_eq!(content, "[package]\nname = \"demo\"");
    }

    #[test]
    fn inject_dependency_adds_piano_runtime() {
        let staging = TempDir::new().unwrap();
        let toml_content = r#"[package]
name = "demo"
version = "0.1.0"

[dependencies]
serde = "1"
"#;
        create_file(staging.path(), "Cargo.toml", toml_content);

        inject_runtime_dependency(staging.path(), "0.1.0").unwrap();

        let result = std::fs::read_to_string(staging.path().join("Cargo.toml")).unwrap();
        let doc: DocumentMut = result.parse().unwrap();

        // piano-runtime was added
        assert_eq!(doc["dependencies"]["piano-runtime"].as_str(), Some("0.1.0"),);
        // serde is preserved
        assert_eq!(doc["dependencies"]["serde"].as_str(), Some("1"),);
    }

    #[test]
    fn extract_compiler_errors_from_json() {
        let json_lines = concat!(
            r#"{"reason":"compiler-message","message":{"rendered":"error[E0308]: mismatched types\n --> src/main.rs:2:5\n"}}"#,
            "\n",
            r#"{"reason":"compiler-message","message":{"rendered":"error: aborting due to previous error\n"}}"#,
            "\n",
            r#"{"reason":"build-finished","success":false}"#,
        );
        let errors = extract_rendered_errors(json_lines);
        assert_eq!(errors.len(), 2);
        assert!(errors[0].contains("mismatched types"));
    }

    #[test]
    fn inject_dependency_creates_section_if_missing() {
        let staging = TempDir::new().unwrap();
        let toml_content = r#"[package]
name = "demo"
version = "0.1.0"
"#;
        create_file(staging.path(), "Cargo.toml", toml_content);

        inject_runtime_dependency(staging.path(), "0.2.0").unwrap();

        let result = std::fs::read_to_string(staging.path().join("Cargo.toml")).unwrap();
        let doc: DocumentMut = result.parse().unwrap();

        assert_eq!(doc["dependencies"]["piano-runtime"].as_str(), Some("0.2.0"),);
    }

    #[test]
    fn find_workspace_root_detects_parent_workspace() {
        let tmp = TempDir::new().unwrap();
        let ws = tmp.path().join("ws");

        // Create workspace root with [workspace] table.
        create_file(&ws, "Cargo.toml", "[workspace]\nmembers = [\"crates/*\"]\n");
        // Create a member project.
        create_file(
            &ws,
            "crates/member/Cargo.toml",
            "[package]\nname = \"member\"\nversion = \"0.1.0\"\n",
        );
        create_file(&ws, "crates/member/src/main.rs", "fn main() {}");

        let member_dir = ws.join("crates").join("member");
        let result = find_workspace_root(&member_dir);
        assert!(result.is_some(), "should find workspace root");
        assert_eq!(result.unwrap(), ws.canonicalize().unwrap());
    }

    #[test]
    fn find_workspace_root_returns_none_for_standalone() {
        let tmp = TempDir::new().unwrap();
        create_file(
            tmp.path(),
            "Cargo.toml",
            "[package]\nname = \"standalone\"\nversion = \"0.1.0\"\n",
        );
        create_file(tmp.path(), "src/main.rs", "fn main() {}");

        let result = find_workspace_root(tmp.path());
        assert!(
            result.is_none(),
            "standalone project should not find workspace root"
        );
    }

    #[test]
    fn find_bin_entry_point_with_explicit_path() {
        let tmp = TempDir::new().unwrap();
        let toml = r#"[package]
name = "demo"
version = "0.1.0"

[[bin]]
name = "demo"
path = "src/custom/app.rs"
"#;
        create_file(tmp.path(), "Cargo.toml", toml);
        create_file(tmp.path(), "src/custom/app.rs", "fn main() {}");

        let result = find_bin_entry_point(tmp.path()).unwrap();
        assert_eq!(result, PathBuf::from("src/custom/app.rs"));
    }

    #[test]
    fn find_bin_entry_point_infers_from_name_single_file() {
        let tmp = TempDir::new().unwrap();
        let toml = r#"[package]
name = "demo"
version = "0.1.0"

[[bin]]
name = "mytool"
"#;
        create_file(tmp.path(), "Cargo.toml", toml);
        create_file(tmp.path(), "src/bin/mytool.rs", "fn main() {}");

        let result = find_bin_entry_point(tmp.path()).unwrap();
        assert_eq!(result, PathBuf::from("src/bin/mytool.rs"));
    }

    #[test]
    fn find_bin_entry_point_infers_from_name_dir_main() {
        let tmp = TempDir::new().unwrap();
        let toml = r#"[package]
name = "demo"
version = "0.1.0"

[[bin]]
name = "mytool"
"#;
        create_file(tmp.path(), "Cargo.toml", toml);
        // No src/bin/mytool.rs, but src/bin/mytool/main.rs exists.
        create_file(tmp.path(), "src/bin/mytool/main.rs", "fn main() {}");

        let result = find_bin_entry_point(tmp.path()).unwrap();
        assert_eq!(result, PathBuf::from("src/bin/mytool/main.rs"));
    }

    #[test]
    fn find_bin_entry_point_defaults_to_src_main() {
        let tmp = TempDir::new().unwrap();
        let toml = r#"[package]
name = "demo"
version = "0.1.0"
"#;
        create_file(tmp.path(), "Cargo.toml", toml);
        create_file(tmp.path(), "src/main.rs", "fn main() {}");

        let result = find_bin_entry_point(tmp.path()).unwrap();
        assert_eq!(result, PathBuf::from("src/main.rs"));
    }

    #[test]
    fn find_bin_entry_point_errors_when_no_entry_found() {
        let tmp = TempDir::new().unwrap();
        let toml = r#"[package]
name = "demo"
version = "0.1.0"
"#;
        create_file(tmp.path(), "Cargo.toml", toml);
        // No src/main.rs, no [[bin]] entries.

        let result = find_bin_entry_point(tmp.path());
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("could not find binary entry point"),
            "unexpected error: {err_msg}"
        );
    }
}