Skip to content

Commit dc106c5

Browse files
committed
Quote strings with invalid plain scalar sequences involving : and #
1 parent ef8ba76 commit dc106c5

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

Sources/PotentYAML/YAMLWriter.swift

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
import Cfyaml
1212
import Foundation
13+
import PotentCodables
14+
import Regex
1315

1416

1517
internal struct YAMLWriter {
@@ -36,6 +38,12 @@ internal struct YAMLWriter {
3638
var explicitDocumentMarkers: Bool = false
3739
}
3840

41+
static let disallowedPlainSequencesRegex: Regex = #"(:\s)|(\s#)"#
42+
43+
public static func hasDisallowedPlainSequences(in string: String) -> Bool {
44+
return disallowedPlainSequencesRegex.firstMatch(in: string) != nil
45+
}
46+
3947
let emitter: OpaquePointer
4048
let options: Options
4149

@@ -158,7 +166,7 @@ internal struct YAMLWriter {
158166
private func emit(string: String, style: YAML.StringStyle, anchor: String?, tag: String?) throws {
159167

160168
let stringStyle: YAML.StringStyle
161-
if options.schema.requiresQuotes(for: string) {
169+
if style == .any && (options.schema.requiresQuotes(for: string) || Self.hasDisallowedPlainSequences(in: string)) {
162170
stringStyle = (options.preferredStringStyle.isQuoted ? options.preferredStringStyle : .doubleQuoted)
163171
}
164172
else {

Tests/YAMLWriterTests.swift

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,58 @@ class YAMLWriterTests: XCTestCase {
6161

6262
}
6363

64+
func testWriteStringValidSpecialPlain() throws {
65+
66+
let options = YAMLWriter.Options(pretty: false)
67+
68+
XCTAssertEqual(
69+
try YAMLWriter.write(["simple :string"], options: options),
70+
"""
71+
simple :string
72+
73+
"""
74+
)
75+
76+
XCTAssertEqual(
77+
try YAMLWriter.write(["simple# string"], options: options),
78+
"""
79+
simple# string
80+
81+
"""
82+
)
83+
84+
}
85+
86+
func testWriteStringInvalidSpecialPlain() throws {
87+
88+
let options = YAMLWriter.Options(preferredStringStyle: .plain, pretty: false)
89+
90+
XCTAssertEqual(
91+
try YAMLWriter.write(["simple: string"], options: options),
92+
"""
93+
"simple: string"
94+
95+
"""
96+
)
97+
98+
XCTAssertEqual(
99+
try YAMLWriter.write(["simple:\nstring"], options: options),
100+
#"""
101+
"simple:\nstring"
102+
103+
"""#
104+
)
105+
106+
XCTAssertEqual(
107+
try YAMLWriter.write(["simple #string"], options: options),
108+
"""
109+
"simple #string"
110+
111+
"""
112+
)
113+
114+
}
115+
64116
func testWriteStringPreferPlain() throws {
65117

66118
let options = YAMLWriter.Options(preferredStringStyle: .plain, pretty: false)

0 commit comments

Comments
 (0)