Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ name = "cargo-fastfmt"
path = "src/main.rs"

[dependencies]
serde_json = "1.0.151"
tree-sitter = "0.25"
tree-sitter-rust = "0.24"

Expand Down
5 changes: 5 additions & 0 deletions DEV.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ The tuning benchmark is AnswerDotAI/loopmini: run stable `cargo fmt` on its `src

## Commands

Edition lookup uses offline `cargo metadata --no-deps`, caching the resolved
editions for all workspace packages. This respects workspace inheritance, member
overrides, and Cargo's default edition without reimplementing manifest parsing.
Standalone Rust files outside a Cargo package, including files under a virtual workspace root, retain the 2021 fallback.

```bash
maturin develop && pytest -q
ship-rs-build
Expand Down
32 changes: 28 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//! width cap, and small (code blocks: 1 expression, fn/impl: 1 item,
//! comma-separated bodies: 3 items). Joins run innermost-first to a fixpoint, so
//! nested one-liners collapse fully.
use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
Expand Down Expand Up @@ -158,8 +159,7 @@ fn fastfmt(src: &str, edition: &str, width: usize) -> Result<String, String> {
Ok(compact(&String::from_utf8_lossy(&out.stdout), width))
}

/// The value at `key` in the nearest `file` at or above `path`, e.g. the edition
/// from Cargo.toml or max_width from rustfmt.toml.
/// The value at `key` in the nearest config file at or above `path`.
fn toml_lookup(path: &Path, file: &str, key: &str) -> Option<String> {
for dir in path.canonicalize().unwrap_or_else(|_| path.to_path_buf()).ancestors() {
if let Ok(t) = std::fs::read_to_string(dir.join(file)) {
Expand All @@ -169,7 +169,30 @@ fn toml_lookup(path: &Path, file: &str, key: &str) -> Option<String> {
None
}

fn edition_for(path: &Path) -> String { toml_lookup(path, "Cargo.toml", "edition").unwrap_or_else(|| "2021".into()) }
/// Let Cargo resolve editions, including workspace inheritance and its 2015 default.
/// Cache every package from the response so a workspace only needs one lookup.
fn edition_for(path: &Path, editions: &mut HashMap<PathBuf, String>) -> Result<String, String> {
let path = path.canonicalize().map_err(|e| e.to_string())?;
let Some(dir) = path.ancestors().find(|p| p.join("Cargo.toml").is_file()) else { return Ok("2021".into()) };
let manifest = dir.join("Cargo.toml");
if let Some(edition) = editions.get(&manifest) { return Ok(edition.clone()); }
let out = Command::new("cargo")
.args(["metadata", "--no-deps", "--offline", "--format-version", "1", "--manifest-path"])
.arg(&manifest)
.output()
.map_err(|e| format!("failed to run cargo metadata: {e}"))?;
if !out.status.success() { return Err(String::from_utf8_lossy(&out.stderr).into_owned()); }
let metadata: serde_json::Value = serde_json::from_slice(&out.stdout).map_err(|e| format!("invalid cargo metadata: {e}"))?;
let packages = metadata["packages"].as_array().ok_or("cargo metadata has no packages")?;
for package in packages {
let manifest = package["manifest_path"].as_str().ok_or("cargo package has no manifest_path")?;
let edition = package["edition"].as_str().ok_or("cargo package has no edition")?;
let manifest = Path::new(manifest).canonicalize().map_err(|e| e.to_string())?;
editions.insert(manifest, edition.into());
}
// A virtual workspace manifest owns no package: this is a standalone file.
Ok(editions.get(&manifest).cloned().unwrap_or_else(|| "2021".into()))
}

/// `--width` beats the nearest rustfmt.toml's max_width, which beats the default.
fn width_for(path: &Path, flag: Option<usize>) -> usize {
Expand Down Expand Up @@ -263,6 +286,7 @@ fn main() {
for p in &paths { rs_files(p, &mut files) }
files.sort();
let mut dirty = vec![];
let mut editions = HashMap::new();
for f in &files {
let src = match std::fs::read_to_string(f) {
Ok(s) => s,
Expand All @@ -271,7 +295,7 @@ fn main() {
std::process::exit(2)
}
};
match fastfmt(&src, &edition_for(f), width_for(f, width_flag)) {
match edition_for(f, &mut editions).and_then(|edition| fastfmt(&src, &edition, width_for(f, width_flag))) {
Ok(new) if new != src => {
if check { dirty.push(f) } else if let Err(e) = std::fs::write(f, &new) {
eprintln!("{}: {e}", f.display());
Expand Down
32 changes: 31 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"End-to-end check of the installed binary: rustfmt runs, then compaction joins."
import subprocess
import subprocess, pytest

BROKEN ="""fn time() -> f64 {
42.0
Expand Down Expand Up @@ -68,3 +68,33 @@ def test_fastfmt_binary(tmp_path):
assert f.read_text() == BROKEN
r = subprocess.run(['cargo-fastfmt', '--check'], cwd=tmp_path, capture_output=True, text=True)
assert r.returncode == 1 and 'main.rs' in r.stdout


@pytest.mark.parametrize('edition,source', [
('edition.workspace = true', 'fn f(x: Option<u8>) { if let Some(x) = x && x > 0 { drop(x); } }'),
('edition = { workspace = true }', 'fn f(x: Option<u8>) { if let Some(x) = x && x > 0 { drop(x); } }'),
("edition = '2021' # member override", 'fn gen() {}'),
('', 'fn async() {}'), # Cargo defaults to 2015, not the workspace edition
])
def test_workspace_editions(tmp_path, edition, source):
(tmp_path/'Cargo.toml').write_text('[workspace]\nmembers = ["py"]\nresolver = "2"\n'
'[workspace.package]\nedition = "2024"\n')
member = tmp_path/'py'
(member/'src').mkdir(parents=True)
(member/'Cargo.toml').write_text('[package]\nname = "bindings"\nversion = "0.1.0"\n' + edition + '\n')
(member/'src/lib.rs').write_text(source + '\n')
subprocess.run(['cargo', 'fastfmt'], cwd=tmp_path, check=True)
subprocess.run(['cargo', 'fastfmt', '--check'], cwd=tmp_path, check=True)


def test_standalone_file_in_virtual_workspace(tmp_path):
(tmp_path/'Cargo.toml').write_text('[workspace]\nmembers = ["member"]\nresolver = "2"\n')
src = tmp_path/'member/src'
src.mkdir(parents=True)
(src.parent/'Cargo.toml').write_text('[package]\nname = "member"\nversion = "0.1.0"\nedition = "2021"\n')
(src/'lib.rs').write_text('fn member() {}\n')
script = tmp_path/'script.rs'
script.write_text('async fn main() {\n work().await;\n}\n')
subprocess.run(['cargo-fastfmt'], cwd=tmp_path, check=True)
assert script.read_text() == 'async fn main() { work().await; }\n'
subprocess.run(['cargo-fastfmt', '--check'], cwd=tmp_path, check=True)