nicklockwood / SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
MIT License
7.87k stars 637 forks source link

Support configuring `wrapAttributes` rule to apply differently to computed properties vs stored properties #1588

Closed calda closed 10 months ago

calda commented 10 months ago

This PR updates the wrapAttributes rules to support being applied differently to computed properties vs stored properties.

Take this example SwiftUI view:

struct MyView: View {
    @State var textContent: String

    var body: some View {
        childView
    }

    @ViewBuilder
    var childView: some View {
        Text(verbatim: textContent)
    }
}

We want the @ViewBuilder attribute to be on its own line, but the @State attribute to be on the same line as the property declaration. Previously this wasn't possible. Now this is supported using --computedvarattrs prev-line --storedvarattrs same-line.


Separately, when looking at adopting --varattributes prev-line, I noticed a type of case where I think we should preserve the existing formatting instead of wrapping. Take this example, with a max line width of 100 chars:

@available(*, unavailable, message: "This property is deprecated. It has a really long message.")
var foo: WrappedType

If we unwrap this so the attribute and the var are on the same line, since this exceeds the 100 char line width limit the wrap rule will then re-wrap the code into the following formatting:

@available(
   *,
   unavailable,
   message: "This property is deprecated. It has a really long message."
) var foo: WrappedType

I updated how wrapAttributes handles the same-line option, so it will preserve the existing formatting if unwrapping the attribute would cause the newly combined line to exceed the max line width.

Let me know if you think this should be an option rather than the default behavior.

codecov[bot] commented 10 months ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Comparison is base (1fd536f) 95.06% compared to head (895f57e) 95.09%.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## develop #1588 +/- ## =========================================== + Coverage 95.06% 95.09% +0.02% =========================================== Files 20 20 Lines 21967 22059 +92 =========================================== + Hits 20882 20976 +94 + Misses 1085 1083 -2 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

balavor commented 10 months ago

Awesome improvement. Probably the main reason why we don't use wrapAttributes.

nicklockwood commented 10 months ago

Looks great, thank you!