Skip to content

Commit a64778e

Browse files
ytmimixxchan
authored andcommitted
Add format_cargo_toml to the code path called by rustfmt
Now users can provide the path to their `Cargo.toml` files for rustfmt to format.
1 parent 22bcae2 commit a64778e

File tree

2 files changed

+54
-11
lines changed

2 files changed

+54
-11
lines changed

src/formatting.rs

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
// High level formatting functions.
22

33
use std::collections::HashMap;
4+
use std::ffi::OsStr;
45
use std::io::{self, Write};
6+
use std::path::PathBuf;
57
use std::time::{Duration, Instant};
68

79
use rustc_ast::ast;
@@ -11,6 +13,7 @@ use self::newline_style::apply_newline_style;
1113
use crate::comment::{CharClasses, FullCodeCharKind};
1214
use crate::config::{Config, FileName, Verbosity};
1315
use crate::formatting::generated::is_generated_file;
16+
use crate::ignore_path::IgnorePathSet;
1417
use crate::modules::Module;
1518
use crate::parse::parser::{DirectoryOwnership, Parser, ParserError};
1619
use crate::parse::session::ParseSess;
@@ -36,6 +39,15 @@ impl<'b, T: Write + 'b> Session<'b, T> {
3639
return Err(ErrorKind::VersionMismatch);
3740
}
3841

42+
let cargo_toml = Some(OsStr::new("Cargo.toml"));
43+
match input {
44+
Input::File(path) if path.file_name() == cargo_toml => {
45+
let config = &self.config.clone();
46+
return format_cargo_toml(path, config, self);
47+
}
48+
_ => {}
49+
}
50+
3951
rustc_span::create_session_if_not_set_then(self.config.edition().into(), |_| {
4052
if self.config.disable_all_formatting() {
4153
// When the input is from stdin, echo back the input.
@@ -175,6 +187,29 @@ fn format_project<T: FormatHandler>(
175187
Ok(context.report)
176188
}
177189

190+
fn format_cargo_toml<T: FormatHandler>(
191+
path: PathBuf,
192+
config: &Config,
193+
handler: &mut T,
194+
) -> Result<FormatReport, ErrorKind> {
195+
let mut report = FormatReport::new();
196+
197+
let ignore_path_set = IgnorePathSet::from_ignore_list(&config.ignore())?;
198+
let file_name = FileName::Real(path.clone());
199+
if ignore_path_set.is_match(&file_name) {
200+
return Ok(report);
201+
}
202+
203+
let input = std::fs::read_to_string(&path)?;
204+
let mut result = cargo_toml::format_cargo_toml_inner(&input, config)?;
205+
206+
apply_newline_style(config.newline_style(), &mut result, &input);
207+
208+
handler.handle_formatted_file(None, file_name, result, &mut report)?;
209+
210+
Ok(report)
211+
}
212+
178213
// Used for formatting files.
179214
#[derive(new)]
180215
struct FormatContext<'a, T: FormatHandler> {
@@ -242,7 +277,7 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
242277
.add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
243278

244279
self.handler.handle_formatted_file(
245-
&self.parse_session,
280+
Some(&self.parse_session),
246281
path,
247282
visitor.buffer.to_owned(),
248283
&mut self.report,
@@ -254,7 +289,7 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
254289
trait FormatHandler {
255290
fn handle_formatted_file(
256291
&mut self,
257-
parse_session: &ParseSess,
292+
parse_session: Option<&ParseSess>,
258293
path: FileName,
259294
result: String,
260295
report: &mut FormatReport,
@@ -265,14 +300,14 @@ impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
265300
// Called for each formatted file.
266301
fn handle_formatted_file(
267302
&mut self,
268-
parse_session: &ParseSess,
303+
parse_session: Option<&ParseSess>,
269304
path: FileName,
270305
result: String,
271306
report: &mut FormatReport,
272307
) -> Result<(), ErrorKind> {
273308
if let Some(ref mut out) = self.out {
274309
match source_file::write_file(
275-
Some(parse_session),
310+
parse_session,
276311
&path,
277312
&result,
278313
out,

src/formatting/cargo_toml.rs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
use itertools::Itertools;
22
use std::cmp::Ordering;
3-
use toml_edit::{visit_mut::*, Decor, Document, Formatted, Item, KeyMut, Table, TableLike, Value};
3+
use toml_edit::{
4+
visit_mut::*, Decor, Document, Formatted, Item, KeyMut, Table, TableLike, TomlError, Value,
5+
};
46

5-
use crate::Config;
7+
use crate::{Config, ErrorKind};
68

7-
#[allow(dead_code)]
8-
fn format_cargo_toml(content: &str, config: &Config) -> String {
9-
let mut doc = content.parse::<toml_edit::Document>().unwrap();
9+
pub(crate) fn format_cargo_toml_inner(content: &str, config: &Config) -> Result<String, ErrorKind> {
10+
let mut doc = content.parse::<toml_edit::Document>()?;
1011
let rules: Vec<Box<dyn VisitMut>> = vec![
1112
Box::new(SortSection {
1213
current_position: 0,
@@ -27,7 +28,14 @@ fn format_cargo_toml(content: &str, config: &Config) -> String {
2728
for mut rule in rules.into_iter() {
2829
rule.visit_document_mut(&mut doc);
2930
}
30-
return doc.to_string();
31+
32+
Ok(doc.to_string())
33+
}
34+
35+
impl From<TomlError> for ErrorKind {
36+
fn from(_: TomlError) -> Self {
37+
ErrorKind::ParseError
38+
}
3139
}
3240

3341
/// Sort key names alphabetically within each section, with the exception of the
@@ -363,7 +371,7 @@ mod tests {
363371
d = "git-rustfmt"
364372
c = "src/git-rustfmt/main.rs""#;
365373

366-
let formatted = format_cargo_toml(s, &Default::default());
374+
let formatted = format_cargo_toml_inner(s, &Default::default()).unwrap();
367375

368376
#[rustfmt::skip]
369377
let expected = r#"[package]

0 commit comments

Comments
 (0)