@@ -15,7 +15,6 @@ import Foundation
1515import SwiftFormat
1616import SwiftFormatConfiguration
1717import SwiftSyntax
18- import TSCBasic
1918
2019extension SwiftFormatCommand {
2120 /// Formats one or more files containing Swift code.
@@ -89,31 +88,29 @@ private func formatMain(
8988 // fixed anyway.
9089 let formatter = SwiftFormatter ( configuration: configuration, diagnosticEngine: nil )
9190 formatter. debugOptions = debugOptions
92- let assumingFileURL = URL ( fileURLWithPath: assumingFilename ?? " <stdin> " )
91+
92+ let path = assumingFilename ?? " <stdin> "
93+ let assumingFileURL = URL ( fileURLWithPath: path)
9394
9495 guard let source = readSource ( from: sourceFile) else {
9596 diagnosticEngine. diagnose (
96- Diagnostic . Message (
97- . error, " Unable to read source for formatting from \( assumingFileURL. path) . " ) )
97+ Diagnostic . Message ( . error, " Unable to read source for formatting from \( path) . " ) )
9898 return
9999 }
100100
101+ var stdoutStream = FileHandle . standardOutput
101102 do {
102103 if inPlace {
103- let cwd = FileManager . default. currentDirectoryPath
104- var buffer = BufferedOutputByteStream ( )
104+ var buffer = " "
105105 try formatter. format ( source: source, assumingFileURL: assumingFileURL, to: & buffer)
106- buffer. flush ( )
107- try localFileSystem. writeFileContents (
108- AbsolutePath ( assumingFileURL. path, relativeTo: AbsolutePath ( cwd) ) ,
109- bytes: buffer. bytes
110- )
106+
107+ let bufferData = buffer. data ( using: . utf8) ! // Conversion to UTF-8 cannot fail
108+ try bufferData. write ( to: assumingFileURL, options: . atomic)
111109 } else {
112110 try formatter. format ( source: source, assumingFileURL: assumingFileURL, to: & stdoutStream)
113- stdoutStream. flush ( )
111+ stdoutStream. synchronizeFile ( )
114112 }
115113 } catch SwiftFormatError . fileNotReadable {
116- let path = assumingFileURL. path
117114 diagnosticEngine. diagnose (
118115 Diagnostic . Message (
119116 . error, " Unable to format \( path) : file is not readable or does not exist. " ) )
@@ -125,17 +122,15 @@ private func formatMain(
125122 return
126123 }
127124 stdoutStream. write ( source)
128- stdoutStream. flush ( )
125+ stdoutStream. synchronizeFile ( )
129126 return
130127 }
131- let path = assumingFileURL. path
132128 let location = SourceLocationConverter ( file: path, source: source) . location ( for: position)
133129 diagnosticEngine. diagnose (
134130 Diagnostic . Message ( . error, " file contains invalid or unrecognized Swift syntax. " ) ,
135131 location: location)
136132 return
137133 } catch {
138- let path = assumingFileURL. path
139134 diagnosticEngine. diagnose ( Diagnostic . Message ( . error, " Unable to format \( path) : \( error) " ) )
140135 return
141136 }
0 commit comments