Skip to content

Commit

Permalink
[xcstrings2swift] Fix bug that generate invalid member identifier whe…
Browse files Browse the repository at this point in the history
…n key has punctuation
  • Loading branch information
nearfri committed Apr 12, 2024
1 parent acda195 commit 10945fb
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 1 deletion.
32 changes: 32 additions & 0 deletions Sources/LocStringResourceGen/LocalizationItem.swift
Expand Up @@ -13,6 +13,38 @@ extension LocalizationItem {
return id
}
}

public func fixingID() -> MemberDeclation {
if id.isEmpty { return self }

var newID = ""

let firstChar = id[id.startIndex]
if isIdentifierHead(firstChar) {
newID = String(firstChar)
} else {
newID = firstChar.isNumber ? "_\(firstChar)" : "_"
}

for char in id.dropFirst() {
newID.append(isIdentifierBody(char) ? char : "_")
}

switch self {
case .property:
return .property(newID)
case .method(_, let parameters):
return .method(newID, parameters)
}
}

private func isIdentifierHead(_ character: Character) -> Bool {
return character.isLetter || character == "_"
}

private func isIdentifierBody(_ character: Character) -> Bool {
return isIdentifierHead(character) || character.isNumber
}
}

public struct Parameter: Hashable {
Expand Down
Expand Up @@ -70,7 +70,7 @@ struct StringCatalogDTOMapper {
key: key,
defaultValue: defaultValue,
rawDefaultValue: stringUnitDTO.escapedValue,
memberDeclation: memberDeclation)
memberDeclation: memberDeclation.fixingID())
}

private func stringUnitDTO(from dto: LocalizationDTO) -> StringUnitDTO? {
Expand Down
48 changes: 48 additions & 0 deletions Tests/LocStringResourceGenTests/LocalizationItemTests.swift
@@ -1,6 +1,54 @@
import XCTest
@testable import LocStringResourceGen

final class LocalizationItemMemberDeclationTests: XCTestCase {
func test_fixingID_validPropertyID_returnsEqual() throws {
// Given
let sut = LocalizationItem.MemberDeclation.property("valid_key")

// When
let fixed = sut.fixingID()

// Then
XCTAssertEqual(fixed, sut)
}

func test_fixingID_validMethodID_returnsEqual() throws {
// Given
let sut = LocalizationItem.MemberDeclation.method(
"valid_id",
[.init(firstName: "p1", type: "Int")])

// When
let fixed = sut.fixingID()

// Then
XCTAssertEqual(fixed, sut)
}

func test_fixingID_invalidID_returnFixed() throws {
// Given
let sut = LocalizationItem.MemberDeclation.property("punctuation/key")

// When
let fixed = sut.fixingID()

// Then
XCTAssertEqual(fixed, .property("punctuation_key"))
}

func test_fixingID_idStartsWithNumber_returnFixed() throws {
// Given
let sut = LocalizationItem.MemberDeclation.property("1number_key")

// When
let fixed = sut.fixingID()

// Then
XCTAssertEqual(fixed, .property("_1number_key"))
}
}

final class LocalizationItemTests: XCTestCase {
func test_documentComments() throws {
func test(defaultValue: String,
Expand Down

0 comments on commit 10945fb

Please sign in to comment.