Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Have the ability to keep and add commas to the end of a single element in a multi line list #874

Open
dickoff opened this issue Nov 7, 2024 · 1 comment

Comments

@dickoff
Copy link

dickoff commented Nov 7, 2024

Precondition: Have multiElementCollectionTrailingCommas set to true in the swift format configuration.

Trailing commas in multi line arrays are great as they allow the git history for a line to be easily maintained when a new element is added later. For example:

let x =
[
    1,
    2,
    3
]

gets formatted to

let x =
[
    1,
    2,
    3,
]

This way, when someone comes along and adds "4," to this list later they will not have needed to add a "," after 3, leaving the git blame for that line alone. Unfortunately the rule for multiElementCollectionTrailingCommas does not keep or insert commas in single element lists. So in the above example if someone wrote

let x =
[
    1,
]

it will be formatted to:

let x =
[
    1
]

This means that when adding a second element to this list you must add a comma after the first element. It would be great if there was a way to configure swift-format to keep these trailing commas for single element multi line lists. Whether this is tied to multiElementCollectionTrailingCommas or some other configuration is certainly up to debate, I don't know the general guidance for whether or not configurations like this should change behavior.

There's this excerpt from PrettyPrint.swift describing this as a limitation.

      // We need to specifically disable trailing commas on elements of single item collections.
      // The syntax library can't distinguish a collection's initializer (where the elements are
      // types) from a literal (where the elements are the contents of a collection instance).
      // We never want to add a trailing comma in an initializer so we disable trailing commas on
      // single element collections.
      let shouldHaveTrailingComma =
        startLineNumber != openCloseBreakCompensatingLineNumber && !isSingleElement
        && configuration.multiElementCollectionTrailingCommas
      if shouldHaveTrailingComma && !hasTrailingComma {
        diagnose(.addTrailingComma, category: .trailingComma)
      } else if !shouldHaveTrailingComma && hasTrailingComma {
        diagnose(.removeTrailingComma, category: .trailingComma)
      }
@ahoppen
Copy link
Member

ahoppen commented Nov 8, 2024

Synced to Apple’s issue tracker as rdar://139474339

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants