Skip to content

Commit

Permalink
Quote strings with invalid plain scalar sequences involving : and #
Browse files Browse the repository at this point in the history
  • Loading branch information
kdubb committed Jun 18, 2024
1 parent ef8ba76 commit dc106c5
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
10 changes: 9 additions & 1 deletion Sources/PotentYAML/YAMLWriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

import Cfyaml
import Foundation
import PotentCodables
import Regex


internal struct YAMLWriter {
Expand All @@ -36,6 +38,12 @@ internal struct YAMLWriter {
var explicitDocumentMarkers: Bool = false
}

static let disallowedPlainSequencesRegex: Regex = #"(:\s)|(\s#)"#

public static func hasDisallowedPlainSequences(in string: String) -> Bool {
return disallowedPlainSequencesRegex.firstMatch(in: string) != nil
}

let emitter: OpaquePointer
let options: Options

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

let stringStyle: YAML.StringStyle
if options.schema.requiresQuotes(for: string) {
if style == .any && (options.schema.requiresQuotes(for: string) || Self.hasDisallowedPlainSequences(in: string)) {
stringStyle = (options.preferredStringStyle.isQuoted ? options.preferredStringStyle : .doubleQuoted)
}
else {
Expand Down
52 changes: 52 additions & 0 deletions Tests/YAMLWriterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,58 @@ class YAMLWriterTests: XCTestCase {

}

func testWriteStringValidSpecialPlain() throws {

let options = YAMLWriter.Options(pretty: false)

XCTAssertEqual(
try YAMLWriter.write(["simple :string"], options: options),
"""
simple :string
"""
)

XCTAssertEqual(
try YAMLWriter.write(["simple# string"], options: options),
"""
simple# string
"""
)

}

func testWriteStringInvalidSpecialPlain() throws {

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

XCTAssertEqual(
try YAMLWriter.write(["simple: string"], options: options),
"""
"simple: string"
"""
)

XCTAssertEqual(
try YAMLWriter.write(["simple:\nstring"], options: options),
#"""
"simple:\nstring"
"""#
)

XCTAssertEqual(
try YAMLWriter.write(["simple #string"], options: options),
"""
"simple #string"
"""
)

}

func testWriteStringPreferPlain() throws {

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

0 comments on commit dc106c5

Please sign in to comment.