SwiftFormat icon indicating copy to clipboard operation
SwiftFormat copied to clipboard

Support for both formatting files and reporting result as command return value

Open danieleformichelli opened this issue 3 years ago • 7 comments

Hello 👋

We would like to run swiftformat as pre-push hook and in case there is some files that need to be formatted:

  • format them
  • block the push operation

As far as I understand we can either:

  • run swiftformat without the --lint argument, which formats the files but always returns 0 as result
  • run swiftformat with the --lint argument, which doesn't formats the files and returns 1 as result if some file needs to be formatted

So there is no easy way to achieve it. Am I missing something? what do you think of adding a parameter to have the behavior described above?

Thanks a lot for your work! 🙏

danieleformichelli avatar Dec 21 '21 16:12 danieleformichelli

Can you run it with --lint and then again without in the same script?

nicklockwood avatar Dec 21 '21 21:12 nicklockwood

Yes, but it would double the time (which is already non negligible), isn't it?

danieleformichelli avatar Dec 21 '21 22:12 danieleformichelli

The results are cached, so formatting after linting should be faster. Also, you would only need to run the formatter on files that failed lint, so perhaps you could structure the script to skip formatting for files that passed lint?

nicklockwood avatar Dec 22 '21 05:12 nicklockwood

It's faster but in our project it's still over 3 seconds, which we would be glad to avoid :)

If you don't think it makes sense to add such parameter, the easier path would probably be to just run swiftformat without --lint, and check that the 1/1234 files require formatting line starts with 0 :)

danieleformichelli avatar Dec 22 '21 09:12 danieleformichelli

So to be clear, you want a parameter to return an error code after formatting if any changes were made, correct?

nicklockwood avatar Dec 22 '21 10:12 nicklockwood

Correct, I actually think it could be default behavior of the swiftformat command, as it could return

  • 0 if nothing needs to be formatted
  • -1 (or whatever else) if something has been formatted
  • X in case of other errors

danieleformichelli avatar Dec 22 '21 10:12 danieleformichelli

This is implemented in https://github.com/nicklockwood/SwiftFormat/pull/1676

calda avatar Apr 21 '24 16:04 calda