Skip to content

Commit 972f494

Browse files
committed
Pref for comma on the last field
1 parent e7adf64 commit 972f494

File tree

3 files changed

+13
-6
lines changed

3 files changed

+13
-6
lines changed

src/config.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub struct Config {
1919
pub newline_style: ::NewlineStyle,
2020
pub fn_brace_style: ::BraceStyle,
2121
pub fn_return_indent: ::ReturnIndent,
22+
pub struct_trailing_comma: bool,
2223
}
2324

2425
impl Config {

src/default.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ tab_spaces = 4
55
newline_style = "Unix"
66
fn_brace_style = "SameLineWhere"
77
fn_return_indent = "WithArgs"
8+
struct_trailing_comma = true

src/items.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -431,8 +431,8 @@ impl<'a> FmtVisitor<'a> {
431431
self.last_pos = span.lo + BytePos(struct_snippet.find('{').unwrap() as u32 + 1);
432432

433433
self.block_indent += config!(tab_spaces);
434-
for f in &struct_def.fields {
435-
self.visit_field(f, span.lo, &struct_snippet);
434+
for (i, f) in struct_def.fields.iter().enumerate() {
435+
self.visit_field(f, i == struct_def.fields.len() - 1, span.lo, &struct_snippet);
436436
}
437437
self.block_indent -= config!(tab_spaces);
438438

@@ -457,6 +457,7 @@ impl<'a> FmtVisitor<'a> {
457457
// Field of a struct
458458
fn visit_field(&mut self,
459459
field: &ast::StructField,
460+
last_field: bool,
460461
// These two args are for missing spans hacks.
461462
struct_start: BytePos,
462463
struct_snippet: &str)
@@ -480,21 +481,25 @@ impl<'a> FmtVisitor<'a> {
480481
};
481482
let typ = pprust::ty_to_string(&field.node.ty);
482483

483-
let field_str = match name {
484+
let mut field_str = match name {
484485
Some(name) => {
485486
let budget = config!(ideal_width) - self.block_indent;
487+
// 3 is being conservative and assuming that there will be a trailing comma.
486488
if self.block_indent + vis.len() + name.len() + typ.len() + 3 > budget {
487-
format!("{}{}:\n{}{},",
489+
format!("{}{}:\n{}{}",
488490
vis,
489491
name,
490492
&make_indent(self.block_indent + config!(tab_spaces)),
491493
typ)
492494
} else {
493-
format!("{}{}: {},", vis, name, typ)
495+
format!("{}{}: {}", vis, name, typ)
494496
}
495497
}
496-
None => format!("{}{},", vis, typ),
498+
None => format!("{}{}", vis, typ),
497499
};
500+
if !last_field || config!(struct_trailing_comma) {
501+
field_str.push(',');
502+
}
498503
self.changes.push_str_span(field.span, &field_str);
499504

500505
// This hack makes sure we only add comments etc. after the comma, and

0 commit comments

Comments
 (0)