@@ -61,19 +61,40 @@ public final class SwiftFormatter {
61
61
try format ( syntax: sourceFile, assumingFileURL: url, to: & outputStream)
62
62
}
63
63
64
+ /// Formats the given Swift source code and writes the result to an output stream.
65
+ ///
66
+ /// - Parameters:
67
+ /// - source: The Swift source code to be formatted.
68
+ /// - url: A file URL denoting the filename/path that should be assumed for this syntax tree,
69
+ /// which is associated with any diagnostics emitted during formatting. If this is nil, a
70
+ /// dummy value will be used.
71
+ /// - outputStream: A value conforming to `TextOutputStream` to which the formatted output will
72
+ /// be written.
73
+ /// - Throws: If an unrecoverable error occurs when formatting the code.
74
+ public func format< Output: TextOutputStream > (
75
+ source: String , assumingFileURL url: URL ? , to outputStream: inout Output
76
+ ) throws {
77
+ let sourceFile = try SyntaxParser . parse ( source: source)
78
+ try format ( syntax: sourceFile, assumingFileURL: url, to: & outputStream)
79
+ }
80
+
64
81
/// Formats the given Swift syntax tree and writes the result to an output stream.
65
82
///
66
83
/// - Parameters:
67
84
/// - syntax: The Swift syntax tree to be converted to source code and formatted.
68
- /// - url: A file URL denoting the filename/path that should be assumed for this syntax tree.
85
+ /// - url: A file URL denoting the filename/path that should be assumed for this syntax tree,
86
+ /// which is associated with any diagnostics emitted during formatting. If this is nil, a
87
+ /// dummy value will be used.
69
88
/// - outputStream: A value conforming to `TextOutputStream` to which the formatted output will
70
89
/// be written.
71
90
/// - Throws: If an unrecoverable error occurs when formatting the code.
72
91
public func format< Output: TextOutputStream > (
73
- syntax: SourceFileSyntax , assumingFileURL url: URL , to outputStream: inout Output
92
+ syntax: SourceFileSyntax , assumingFileURL url: URL ? , to outputStream: inout Output
74
93
) throws {
94
+ let assumedURL = url ?? URL ( fileURLWithPath: " source " )
95
+
75
96
let context = Context (
76
- configuration: configuration, diagnosticEngine: diagnosticEngine, fileURL: url ,
97
+ configuration: configuration, diagnosticEngine: diagnosticEngine, fileURL: assumedURL ,
77
98
sourceFileSyntax: syntax)
78
99
let pipeline = FormatPipeline ( context: context)
79
100
let transformedSyntax = pipeline. visit ( syntax)
@@ -89,6 +110,4 @@ public final class SwiftFormatter {
89
110
printTokenStream: debugOptions. contains ( . dumpTokenStream) )
90
111
outputStream. write ( printer. prettyPrint ( ) )
91
112
}
92
-
93
- // TODO: Add an overload of `format` that takes the source text directly.
94
113
}
0 commit comments