python – Regex to extract value from enum and function as a string

Regex to extract value from enum and function which is a static property inside

Basically, my task is to remove unused localization strings. I have a Localizable.strings file where I store strings like this: "someString" = "someLocalizedString"; My algorithm is something like this: I loop over all my files, gather all the used properties from the Localized.swift file (in code they look like: Localized.someString) and then compare them to the extracted property name of a string from the Localized.swift file. Something like this.

Based on the .strings file I generate a Swift file using SwiftGen (Localized.swift). The file has properties, enums and methods. Here are some examples:

  public static let yourComment = Localized.tr("Localizable", "Your comment")

  public enum Avg {
    public static let heartRate = Localized.tr("Localizable", "Avg. Heart Rate")
    public static let pace = Localized.tr("Localizable", "Avg. pace")
  }

  public static func usersCount(_ p1: Int) -> String {
    return Localized.tr("Localizable", "UsersCount", p1)
  }

And here is my python code for this:

for root, _, files in os.walk(search_dir):
    for file in files:
        if file.lower().endswith('.swift') and file != exclude_file:
            with open(os.path.join(root, file), 'r') as f:
                for line in f:
                    matches_string = re.findall(r'Localized\.([a-zA-Z0-9_]+)', line)
                    project_string_list += matches_string
with open(localized_file_path, 'r') as f:
        lines = f.readlines()
        for line in lines:
            matches_property = re.findall(r'public static let\s+([a-zA-Z0-9_]+)\s+=\s+Localized\.tr\("Localizable",\s+"([^"]+)"\)', line)
            for match in matches_property:
                if match[0] in project_string_list:
                    localized_string_list.append(match[1])
            
print(localized_string_list)

with open(strings_file_path, 'r') as f:
    lines = f.readlines()
    
    for line in lines:
        matches_localizable_string = re.findall(r'^\s*"([^"]+)"\s*=\s*".*?"\s*;\s*$', line)
        for match in matches_localizable_string:
            if match in localized_string_list:
                localizable_string_list.append(line)

with open(strings_file_path, 'w') as f:
    f.writelines(localizable_string_list)

The main question is, how do I extract the property name and string as I did with matches_localizable_string from the enum and from the function? The extracted result should be the property name and the second string from the tr() function.
Thank you in advance.

Read more here: Source link