@@ -15,7 +15,6 @@ import Foundation
15
15
import SwiftFormat
16
16
import SwiftFormatConfiguration
17
17
import SwiftSyntax
18
- import TSCBasic
19
18
20
19
extension SwiftFormatCommand {
21
20
/// Formats one or more files containing Swift code.
@@ -89,31 +88,29 @@ private func formatMain(
89
88
// fixed anyway.
90
89
let formatter = SwiftFormatter ( configuration: configuration, diagnosticEngine: nil )
91
90
formatter. debugOptions = debugOptions
92
- let assumingFileURL = URL ( fileURLWithPath: assumingFilename ?? " <stdin> " )
91
+
92
+ let path = assumingFilename ?? " <stdin> "
93
+ let assumingFileURL = URL ( fileURLWithPath: path)
93
94
94
95
guard let source = readSource ( from: sourceFile) else {
95
96
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) . " ) )
98
98
return
99
99
}
100
100
101
+ var stdoutStream = FileHandle . standardOutput
101
102
do {
102
103
if inPlace {
103
- let cwd = FileManager . default. currentDirectoryPath
104
- var buffer = BufferedOutputByteStream ( )
104
+ var buffer = " "
105
105
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)
111
109
} else {
112
110
try formatter. format ( source: source, assumingFileURL: assumingFileURL, to: & stdoutStream)
113
- stdoutStream. flush ( )
111
+ stdoutStream. synchronizeFile ( )
114
112
}
115
113
} catch SwiftFormatError . fileNotReadable {
116
- let path = assumingFileURL. path
117
114
diagnosticEngine. diagnose (
118
115
Diagnostic . Message (
119
116
. error, " Unable to format \( path) : file is not readable or does not exist. " ) )
@@ -125,17 +122,15 @@ private func formatMain(
125
122
return
126
123
}
127
124
stdoutStream. write ( source)
128
- stdoutStream. flush ( )
125
+ stdoutStream. synchronizeFile ( )
129
126
return
130
127
}
131
- let path = assumingFileURL. path
132
128
let location = SourceLocationConverter ( file: path, source: source) . location ( for: position)
133
129
diagnosticEngine. diagnose (
134
130
Diagnostic . Message ( . error, " file contains invalid or unrecognized Swift syntax. " ) ,
135
131
location: location)
136
132
return
137
133
} catch {
138
- let path = assumingFileURL. path
139
134
diagnosticEngine. diagnose ( Diagnostic . Message ( . error, " Unable to format \( path) : \( error) " ) )
140
135
return
141
136
}
0 commit comments