-
Notifications
You must be signed in to change notification settings - Fork 99
[PM-26292] tool: Add script to delete unused Localizable.strings entries #2464
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
KatherineInCode
wants to merge
6
commits into
main
Choose a base branch
from
pm-26292/delete-unused-strings
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5545c4b
Initial generation
KatherineInCode 0192873
Use lowercased strings for simplicity
KatherineInCode 8d501bd
Normalize keys
KatherineInCode 7e3386e
Include multiline
KatherineInCode 87d355a
Refactor
KatherineInCode 88c53c4
Delete unused strings
KatherineInCode File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
311 changes: 0 additions & 311 deletions
311
BitwardenResources/Localizations/en.lproj/Localizable.strings
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
129 changes: 129 additions & 0 deletions
129
Scripts/fix-localizable-strings/delete_unused_strings.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| """ | ||
| delete_unused_strings | ||
|
|
||
| Finds and removes string entries from a Localizable.strings file whose keys are | ||
| never referenced in Swift source code. Keys are assumed to be accessed via | ||
| ``Localizations.X``, where ``X`` is the SwiftGen-generated identifier for the | ||
| key (first character lowercased). Any comment block immediately preceding a | ||
| removed entry (with no blank lines between them) is also removed. | ||
| """ | ||
|
|
||
| import os | ||
| import re | ||
|
|
||
| from strings_file_utils import filter_entries | ||
|
|
||
| # Matches any `Localizations.identifier` reference in Swift source, including | ||
| # cases where the identifier is on the next line (e.g. `Localizations\n .foo`). | ||
| _LOCALIZATIONS_RE = re.compile(r'Localizations\s*\.([a-zA-Z_][a-zA-Z0-9_]*)') | ||
|
|
||
| # Matches any character that is not valid in a Swift identifier. | ||
| _NON_IDENTIFIER_RE = re.compile(r'[^a-zA-Z0-9_]') | ||
|
|
||
|
|
||
| def _normalize_key(key: str) -> str: | ||
| """Normalize a ``.strings`` key for comparison against a SwiftGen identifier. | ||
|
|
||
| SwiftGen strips characters that are not valid in Swift identifiers when | ||
| generating property names (e.g. ``"NeedSomeInspiration?"`` becomes | ||
| ``needSomeInspiration``). This function applies the same stripping and then | ||
| lowercases the result, matching the treatment applied to identifiers found | ||
| in Swift source via ``find_used_keys``. | ||
|
|
||
| Args: | ||
| key: A raw ``.strings`` key, possibly containing trailing punctuation. | ||
|
|
||
| Returns: | ||
| The normalized, lowercased key suitable for comparison. | ||
| """ | ||
| return _NON_IDENTIFIER_RE.sub('', key).lower() | ||
|
|
||
|
|
||
| def find_used_keys(swift_sources: list[str]) -> set[str]: | ||
| """Scan Swift file contents for ``Localizations.X`` references. | ||
|
|
||
| Returns a set of identifiers found in the sources, converted to lowercase | ||
| for comparison with the keys from the strings file. While this does mean | ||
| that keys differing only in case (e.g. ``"OK"`` vs. ``"Ok"``) will be | ||
| treated as the same key, in practice we're not likely to have keys that | ||
| only differ by case. | ||
|
|
||
| The internal helper ``Localizations.tr(...)`` is excluded. | ||
|
|
||
| Args: | ||
| swift_sources: A list of strings, each being the full text of a Swift | ||
| source file. | ||
|
|
||
| Returns: | ||
| A set of lowercased identifiers referenced in the given sources, | ||
| e.g. ``{"about", "ok", "valuehasbeencopied"}``. | ||
| """ | ||
| result: set[str] = set() | ||
| for content in swift_sources: | ||
| for identifier in _LOCALIZATIONS_RE.findall(content): | ||
| if identifier == "tr": | ||
| continue | ||
| result.add(identifier.lower()) | ||
| return result | ||
|
|
||
|
|
||
| def delete_unused_content( | ||
| strings_content: str, used_keys: set[str] | ||
| ) -> tuple[str, list[str]]: | ||
| """Remove unused key entries from Localizable.strings content. | ||
|
|
||
| Processes content line by line. Any key not present in ``used_keys`` is | ||
| removed. Any comment block (``/* */`` or ``//``) immediately preceding a | ||
| removed entry β with no intervening blank lines β is also removed. | ||
|
|
||
| Args: | ||
| strings_content: The full text of the ``.strings`` file. | ||
| used_keys: The set of lowercased identifiers (as returned by | ||
| ``find_used_keys``) that are considered in-use. Each key from the | ||
| strings file is lowercased before lookup to match. | ||
|
|
||
| Returns: | ||
| A tuple of ``(new_content, removed_keys)`` where ``new_content`` is the | ||
| filtered file text and ``removed_keys`` is a list of keys that were | ||
| removed, in file order. | ||
| """ | ||
| return filter_entries(strings_content, lambda key: _normalize_key(key) in used_keys) | ||
|
|
||
|
|
||
| def delete_unused(strings_path: str, swift_dirs: list[str]) -> list[str]: | ||
| """Remove unused entries from a Localizable.strings file in place. | ||
|
|
||
| Walks each directory in ``swift_dirs`` recursively for ``.swift`` files, | ||
| reads them, determines which keys are referenced, then removes any | ||
| unreferenced keys from the strings file. | ||
|
|
||
| Args: | ||
| strings_path: Path to the ``.strings`` file to process. | ||
| swift_dirs: List of directory paths to search recursively for Swift | ||
| source files. | ||
|
|
||
| Returns: | ||
| A list of keys that were removed, in file order. Returns an empty list | ||
| if no unused keys were found. | ||
| """ | ||
| swift_sources: list[str] = [] | ||
| for swift_dir in swift_dirs: | ||
| for dirpath, _, filenames in os.walk(swift_dir): | ||
| for filename in filenames: | ||
| if filename.endswith(".swift"): | ||
| filepath = os.path.join(dirpath, filename) | ||
| with open(filepath, encoding="utf-8") as f: | ||
| swift_sources.append(f.read()) | ||
|
|
||
| used_keys = find_used_keys(swift_sources) | ||
|
|
||
| with open(strings_path, encoding="utf-8") as f: | ||
| content = f.read() | ||
|
|
||
| new_content, removed = delete_unused_content(content, used_keys) | ||
|
|
||
| if removed: | ||
| with open(strings_path, "w", encoding="utf-8") as f: | ||
| f.write(new_content) | ||
|
|
||
| return removed | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,12 +8,18 @@ | |
| python Scripts/fix-localizable-strings/main.py delete-duplicates \\ | ||
| --strings <path/to/Localizable.strings> \\ | ||
| [--dry-run] | ||
|
|
||
| python Scripts/fix-localizable-strings/main.py delete-unused \\ | ||
| --strings <path/to/Localizable.strings> \\ | ||
| --swift-source <dir> [--swift-source <dir> ...] \\ | ||
| [--dry-run] | ||
| """ | ||
|
|
||
| import argparse | ||
| import sys | ||
|
|
||
| from delete_duplicate_strings import delete_duplicates, deduplicate | ||
| from delete_unused_strings import delete_unused, delete_unused_content, find_used_keys | ||
|
|
||
|
|
||
| def _pluralize(count: int, singular: str, plural: str) -> str: | ||
|
|
@@ -45,6 +51,40 @@ def cmd_delete_duplicates(args: argparse.Namespace) -> None: | |
| print(f" {key}") | ||
|
|
||
|
|
||
| def cmd_delete_unused(args: argparse.Namespace) -> None: | ||
| if args.dry_run: | ||
| with open(args.strings, encoding="utf-8") as f: | ||
| content = f.read() | ||
| import os | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. π¨ suggestion - moving inline imports to the top of the scripts, makes it easier to know in advance what the script is using. There's another in the |
||
| swift_sources = [] | ||
| for swift_dir in args.swift_sources: | ||
| for dirpath, _, filenames in os.walk(swift_dir): | ||
| for filename in filenames: | ||
| if filename.endswith(".swift"): | ||
| with open(os.path.join(dirpath, filename), encoding="utf-8") as f: | ||
| swift_sources.append(f.read()) | ||
| used_keys = find_used_keys(swift_sources) | ||
| _, removed = delete_unused_content(content, used_keys) | ||
| if not removed: | ||
| print(" No unused strings found.") | ||
| return | ||
| noun = _pluralize(len(removed), "key", "keys") | ||
| print(f" Found {len(removed)} unused {noun}:") | ||
| for key in removed: | ||
| print(f" {key}") | ||
| print("\n Dry run β no changes written.") | ||
| return | ||
|
|
||
| removed = delete_unused(args.strings, args.swift_sources) | ||
| if not removed: | ||
| print(" No unused strings found.") | ||
| return | ||
| noun = _pluralize(len(removed), "key", "keys") | ||
| print(f" Removed {len(removed)} unused {noun}:") | ||
| for key in removed: | ||
| print(f" {key}") | ||
|
|
||
|
|
||
| def build_parser(): | ||
| parser = argparse.ArgumentParser( | ||
| description="Tools for maintaining Localizable.strings files." | ||
|
|
@@ -67,6 +107,30 @@ def build_parser(): | |
| help="Report duplicates without modifying the strings file.", | ||
| ) | ||
|
|
||
| unused_parser = subparsers.add_parser( | ||
| "delete-unused", | ||
| help="Remove string keys that are never referenced in Swift source code.", | ||
| ) | ||
| unused_parser.add_argument( | ||
| "--strings", | ||
| required=True, | ||
| metavar="PATH", | ||
| help="Path to the Localizable.strings file to process.", | ||
| ) | ||
| unused_parser.add_argument( | ||
| "--swift-source", | ||
| required=True, | ||
| action="append", | ||
| dest="swift_sources", | ||
| metavar="DIR", | ||
| help="Directory to search recursively for Swift source files. May be repeated.", | ||
| ) | ||
| unused_parser.add_argument( | ||
| "--dry-run", | ||
| action="store_true", | ||
| help="Report unused keys without modifying the strings file.", | ||
| ) | ||
|
|
||
| return parser | ||
|
|
||
|
|
||
|
|
@@ -76,6 +140,8 @@ def main(): | |
|
|
||
| if args.command == "delete-duplicates": | ||
| cmd_delete_duplicates(args) | ||
| elif args.command == "delete-unused": | ||
| cmd_delete_unused(args) | ||
| else: | ||
| parser.print_help() | ||
| sys.exit(1) | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π Very personal take - given these scripts aren't for public distribution, these docstrings are blowing up line count without adding much, method name and the 3 comments above the regexps were enough for me at least.