Installation • Configuration • Usage • Build Script • Donation • Migration Guides • Issues • Contributing • License
:sparkles: Important Notice :sparkles:
Apple introduced String Catalogs in Xcode 15 which implements many aspects of BartyCrouch like the incremental auto-extraction, or warning against empty translations. It's also fully backward-compatible with all iOS versions. Migrating is as simple as right-clicking a
.strings
file and choosing "Migrate to String Catalog...". I wrote a detailed FAQ about String Catalogs if you want to learn more. It's really awesome, everybody should migrate to it!The only feature it's missing is machine translation, but I wrote an app to fill the gap and it supports even more translation services than BartyCrouch. Use TranslateKit in the future by simply drag & dropping the String Catalog file and letting it handle the translation, it's really easy.
Note that TranslateKit is being actively worked on. In comparison, BartyCrouch is kept up-to-date only by volunteers in the community.
BartyCrouch incrementally updates your Strings files from your Code and from Interface Builder files. "Incrementally" means that BartyCrouch will by default keep both your already translated values and even your altered comments. Additionally you can also use BartyCrouch for machine translating from one language to 60+ other languages. Using BartyCrouch is as easy as running a few simple commands from the command line what can even be automated using a build script within your project.
Checkout this blog post to learn how you can effectively use BartyCrouch in your projects.
To configure BartyCrouch for your project, first create a configuration file within your projects root directory. BartyCrouch can do this for you:
bartycrouch init
Now you should have a file named .bartycrouch.toml
with the following contents:
[update]
tasks = ["interfaces", "code", "transform", "normalize"]
[update.interfaces]
paths = ["."]
subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"]
defaultToBase = false
ignoreEmptyStrings = false
unstripped = false
ignoreKeys = ["#bartycrouch-ignore!", "#bc-ignore!", "#i!"]
[update.code]
codePaths = ["."]
subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"]
localizablePaths = ["."]
defaultToKeys = false
additive = true
unstripped = false
ignoreKeys = ["#bartycrouch-ignore!", "#bc-ignore!", "#i!"]
[update.transform]
codePaths = ["."]
subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"]
localizablePaths = ["."]
transformer = "foundation"
supportedLanguageEnumPath = "."
typeName = "BartyCrouch"
translateMethodName = "translate"
[update.normalize]
paths = ["."]
subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"]
sourceLocale = "en"
harmonizeWithSource = true
sortByKeys = true
[lint]
paths = ["."]
subpathsToIgnore = [".git", "carthage", "pods", "build", ".build", "docs"]
duplicateKeys = true
emptyValues = true
This is the default configuration of BartyCrouch and should work for most projects as is. In order to use BartyCrouch to its extent, it is recommended though to consider making the following changes:
path
if possible (especially in the update.transform
section, e.g. ["App/Sources"]
for codePaths
or ["App/Supporting Files"]
for supportedLanguageEnumPaths
).code
task if your project is Swift-only and you use the new transform
update task.structured-swift4
template, you will probably want to use the transform
task and change its transformer
option to swiftgenStructured
.transform
task, create a new file in your project (e.g. under SupportingFiles
) named BartyCrouch.swift
and copy the following code:// This file is required in order for the `transform` task of the translation helper tool BartyCrouch to work.
// See here for more details: https://github.com/FlineDev/BartyCrouch
import Foundation
enum BartyCrouch {
enum SupportedLanguage: String {
// TODO: remove unsupported languages from the following cases list & add any missing languages
case arabic = "ar"
case chineseSimplified = "zh-Hans"
case chineseTraditional = "zh-Hant"
case english = "en"
case french = "fr"
case german = "de"
case hindi = "hi"
case italian = "it"
case japanese = "ja"
case korean = "ko"
case malay = "ms"
case portuguese = "pt-BR"
case russian = "ru"
case spanish = "es"
case turkish = "tr"
}
static func translate(key: String, translations: [SupportedLanguage: String], comment: String? = nil) -> String {
let typeName = String(describing: BartyCrouch.self)
let methodName = #function
print(
"Warning: [BartyCrouch]",
"Untransformed \(typeName).\(methodName) method call found with key '\(key)' and base translations '\(translations)'.",
"Please ensure that BartyCrouch is installed and configured correctly."
)
// fall back in case something goes wrong with BartyCrouch transformation
return "BC: TRANSFORMATION FAILED!"
}
}
sourceLocale
of the normalize
task.translate
to the tasks list at the top and copy the following section into the configuration file with secret
replaced by your Microsoft Translator Text API Subscription Key:[update.translate]
paths = "."
translator = "microsoftTranslator"
secret = "<#Subscription Key#>"
sourceLocale = "en"
Before using BartyCrouch please make sure you have committed your code. Also, we highly recommend using the build script method described below.
bartycrouch
accepts one of the following sub commands:
update
: Updates your .strings
file contents according to your configuration.lint
: Checks your .strings
file contents for empty values & duplicate keys.Also the following command line options can be provided:
-v
, --verbose
: Prints more detailed information about the executed command.-x
, --xcode-output
: Prints warnings & errors in Xcode compatible format.-w
, --fail-on-warnings
: Returns a failed status code if any warning is encountered.-p
, --path
: Specifies a different path than current to run BartyCrouch from there.update
subcommandThe update subcommand can be run with one or multiple of the following tasks:
interfaces
: Updates .strings
files of Storyboards & XIBs.code
: Updates Localizable.strings
file from NSLocalizedString
entries in code.transform
: A mode where BartyCrouch replaces a specific method call to provide translations in multiple languages in a single line. Only supports Swift files.translate
: Updates missing translations in other languages than the source language.normalize
: Sorts & cleans up .strings
files.In order to configure which tasks are executed, edit this section in the config file:
[update]
tasks = ["interfaces", "code", "transform", "normalize"]
interfaces
code
transform
translate
normalize
lint
subcommandThe lint subcommand was designed to analyze a project for typical translation issues. The current checks include:
duplicateKeys
: Finds duplicate keys within the same file.emptyValues
: Finds empty values for any language.Note that the lint
command can be used both on CI and within Xcode via the build script method:
-x
or --xcode-output
command line argument should be used to get warnings which point you directly to the found issue.-w
or --fail-on-warnings
argument to make sure BartyCrouch fails if any warnings are encountered.transform
When the transform
update task is configured (see recommended step 4 in the Configuration section above) and you are using the build script method, you can use the following simplified process for writing localized code during development:
NSLocalizedString
calls you can use BartyCrouch.translate
and specify a key, translations (if any) and optionally a comment. For example:self.title = BartyCrouch.translate(key: "onboarding.first-page.header-title", translations: [.english: "Welcome!"])
Localizable.strings
files and add the provided translations as values for the provided languages.BartyCrouch.translate
with the proper translation call, depending on your transformer
option setting.The resulting code depends on your transformer
option setting:
When set to foundation
, the above code will transform to:
self.title = NSLocalizedString("onboarding.first-page.header-title", comment: "")
When set to swiftgenStructured
it will transform to:
self.title = L10n.Onboarding.FirstPage.headerTitle
Advantages of transform
over the code
task:
NSLocalizedString
with L10n
calls manually after running BartyCrouch.Disadvantages of transform
over the code
task:
code
since SwiftSyntax currently isn't particularly fast. (But this should improve over time!)NOTE: As of version 4.x of BartyCrouch formatted localized Strings are not supported by this automatic feature.
LocalizableStringResource
type (AppIntents, ...)Historically, Apple platforms used CFCopyLocalizedString
, and NSLocalizedString
macros and their variants, to mark strings used in code to be localized, and to load their localized versions during runtime from Localizable.strings
file.
Since introduction of the AppIntents framework, the localized strings in code can also be typed as LocalizedStringResource
, and are no longer marked explicitly.
Let's examine this snippet of AppIntents code:
struct ExportAllTransactionsIntent: AppIntent {
static var title: LocalizedStringResource = "Export all transactions"
static var description =
IntentDescription("Exports your transaction history as CSV data.")
}
In the example above, both the "Export all transactions"
, and "Exports your transaction history as CSV data."
are actually StaticString
instances that will be converted during compilation into LocalizedStringResource
instances, and will lookup their respective localizations during runtime from Localized.strings
file the same way as when using NSLocalizedString
in the past. The only exception being that such strings are not marked explicitly, and require swift compiler to parse and extract such strings for localization. This is what Xcode does from version 13 when using Product -> Export Localizations...
option.
In order to continue translating these strings with bartycrouch
it is required to mark them explicitely with LocalizedStringResource(_: String, comment: String)
call, and specify customFunction="LocalizedStringResource"
in code
task options.
The example AppIntents code that can be localized with bartycrouch
will look like this:
struct ExportAllTransactionsIntent: AppIntent {
static var title = LocalizedStringResource("Export all transactions", comment: "")
static var description =
IntentDescription(LocalizedStringResource("Exports your transaction history as CSV data.", comment: ""))
}
Note that you must use the full form of LocalizedStringResource(_: StaticString, comment: StaticString)
for the bartycrouch
, or more specifically for the extractLocStrings
(see xcrun extractLocStrings
) to properly parse the strings.
In order to truly profit from BartyCrouch's ability to update & lint your .strings
files you can make it a natural part of your development workflow within Xcode. In order to do this select your target, choose the Build Phases
tab and click the + button on the top left corner of that pane. Select New Run Script Phase
and copy the following into the text box below the Shell: /bin/sh
of your new run script phase:
export PATH="$PATH:/opt/homebrew/bin"
if which bartycrouch > /dev/null; then
bartycrouch update -x
bartycrouch lint -x
else
echo "warning: BartyCrouch not installed, download it from https://github.com/FlineDev/BartyCrouch"
fi
Next, make sure the BartyCrouch script runs before the steps Compiling Sources
(and SwiftGen
if used) by moving it per drag & drop, for example right after Target Dependencies
.
Now BartyCrouch will be run on each build and you won't need to call it manually ever (again). Additionally, all your co-workers who don't have BartyCrouch installed will see a warning with a hint on how to install it.
Note: Please make sure you commit your code using source control regularly when using the build script method.
Sometimes you may want to ignore some specific views containing localizable texts e.g. because their values are going to be set programmatically.
For these cases you can simply include #bartycrouch-ignore!
or the shorthand #bc-ignore!
into your value within your base localized Storyboard/XIB file. Alternatively you can add #bc-ignore!
into the field "Comment For Localizer" box in the utilities pane.
This will tell BartyCrouch to ignore this specific view when updating your .strings
files.
Here's an example of how a base localized view in a XIB file with partly ignored strings might look like:
Here's an example with the alternative comment variant:
You can also use #bc-ignore!
in your NSLocalizedString
macros comment part to ignore them so they are not added to your Localizable.strings
. This might be helpful when you are using a .stringsdict
file to handle pluralization (see docs).
For example you can do something like this:
func updateTimeLabel(minutes: Int) {
String.localizedStringWithFormat(NSLocalizedString("%d minute(s) ago", comment: "pluralized and localized minutes #bc-ignore!"), minutes)
}
The %d minute(s) ago
key will be taken from Localizable.stringsdict file, not from Localizable.strings, that's why it should be ignored by BartyCrouch.
BartyCrouch was brought to you by Cihat Gündüz in his free time. If you want to thank me and support the development of this project, please make a small donation on PayPal. In case you also like my other open source contributions and articles, please consider motivating me by becoming a sponsor on GitHub or a patron on Patreon.
Thank you very much for any donation, it really helps out a lot! 💯
See the file MIGRATION_GUIDES.md.
Contributions are welcome. Feel free to open an issue on GitHub with your ideas or implement an idea yourself and post a pull request. If you want to contribute code, please try to follow the same syntax and semantic in your commit messages (see rationale here). Also, please make sure to add an entry to the CHANGELOG.md
file which explains your change.
In order for the tests to run build issues, you need to run – also add an API key in the new file to run the translations tests, too:
cp Tests/BartyCrouchTranslatorTests/Secrets/secrets.json.sample Tests/BartyCrouchTranslatorTests/Secrets/secrets.json
After Release Checklist:
make portable_zip
to generate .build/release/portable_bartycrouch.zip
CHANGELOG.md
section & attach portable_bartycrouch.zip
as binarypod trunk push
to make a new release known to CocoaPodstag
and revision
in Formula/bartycrouch.rb
, commit & push changebrew bump-formula-pr bartycrouch --tag=<tag> --revision=<revision>
This library is released under the MIT License. See LICENSE for details.