Localization/I18n: Incrementally update/translate your Strings files from .swift, .h, .m(m), .storyboard or .xib files.
Installation • Configuration • Usage • Build Script • Donation • Migration Guides • Issues • Contributing • License
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 install Bartycrouch the first time, simply run the command:
brew install bartycrouch
To update to the newest version of BartyCrouch when you have an old version already installed run:
brew upgrade bartycrouch
To install or update to the latest version of BartyCrouch simply run this command:
mint install Flinesoft/BartyCrouch
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.tomlwith the following contents:
[update] tasks = ["interfaces", "code", "transform", "normalize"][update.interfaces] paths = ["."] defaultToBase = false ignoreEmptyStrings = false unstripped = false
[update.code] codePaths = ["."] localizablePaths = ["."] defaultToKeys = false additive = true unstripped = false
[update.transform] codePaths = ["."] localizablePaths = ["."] transformer = "foundation" supportedLanguageEnumPath = "." typeName = "BartyCrouch" translateMethodName = "translate"
[update.normalize] paths = ["."] sourceLocale = "en" harmonizeWithSource = true sortByKeys = true
[lint] paths = ["."] 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:
pathif possible (especially in the
update.transformsection, e.g.
["App/Sources"]for
codePathsor
["App/Supporting Files"]for
supportedLanguageEnumPaths).
codetask if your project is Swift-only and you use the new
transformupdate task.
structured-swift4template, you will probably want to use the
transformtask and change its
transformeroption to
swiftgenStructured.
transformtask, create a new file in your project (e.g. under
SupportingFiles) named
BartyCrouch.swiftand 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/Flinesoft/BartyCrouchimport 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!" }
}
sourceLocaleof the
normalizetask.
translateto the tasks list at the top and copy the following section into the configuration file with
secretreplaced by your Microsoft Translator Text API Subscription Key:
[update.translate] paths = "." secret = "" sourceLocale = "en"
Before using BartyCrouch please make sure you have committed your code. Also, we highly recommend using the build script method described below.
bartycrouchaccepts one of the following sub commands:
update: Updates your
.stringsfile contents according to your configuration.
lint: Checks your
.stringsfile 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.
updatesubcommand
The update subcommand can be run with one or multiple of the following tasks:
interfaces: Updates
.stringsfiles of Storyboards & XIBs.
code: Updates
Localizable.stringsfile from
NSLocalizedStringentries 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
.stringsfiles.
In order to configure which tasks are executed, edit this section in the config file:
[update] tasks = ["interfaces", "code", "transform", "normalize"]
interfaces
paths
: The directory / directories to search for Storyboards & XIB files.defaultToBase
: Add Base translation as value to new keys.ignoreEmptyStrings
: Doesn't add views with empty values.unstripped
: Keeps whitespaces at beginning & end of Strings files.code
codePaths
: The directory / directories to search for Swift code files.localizablePaths
: The enclosing path(s) containing the localized Localizable.strings
files.defaultToKeys
: Add new keys both as key and value.additive
: Prevents cleaning up keys not found in code.customFunction
: Use alternative name to NSLocalizedString
.customLocalizableName
: Use alternative name for Localizable.strings
.unstripped
: Keeps whitespaces at beginning & end of Strings files.plistArguments
: Use a plist file to store all the code files for the ExtractLocStrings tool. (Recommended for large projects.)transform
codePaths
: The directory / directories to search for Swift code files.localizablePaths
: The enclosing path(s) containing the localized Localizable.strings
files.transformer
: Specifies the replacement code. Use foundation
for NSLocalizedString
or swiftgenStructured
for L10n
entries.supportedLanguageEnumPath
: The enclosing path containing the SupportedLanguage
enum.typeName
: The name of the type enclosing the SupportedLanguage
enum and translate method.translateMethodName
: The name of the translate method to be replaced.customLocalizableName
: Use alternative name for Localizable.strings
.translate
paths
: The directory / directories to search for Strings files.translator
: Specifies the translation API. Use microsoftTranslator
or deepL
.secret
: Your Microsoft Translator Text API Subscription Key or Authentication Key for DeepL API.sourceLocale
: The source language to translate from.normalize
paths
: The directory / directories to search for Strings files.sourceLocale
: The source language to harmonize keys of other languages with.harmonizeWithSource
: Synchronizes keys with source language.sortByKeys
: Alphabetically sorts translations by their keys.lintsubcommand
The 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
lintcommand can be used both on CI and within Xcode via the build script method:
-xor
--xcode-outputcommand line argument should be used to get warnings which point you directly to the found issue.
-wor
--fail-on-warningsargument to make sure BartyCrouch fails if any warnings are encountered.
transform
When the
transformupdate 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:
NSLocalizedStringcalls you can use
BartyCrouch.translateand 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.stringsfiles and add the provided translations as values for the provided languages.
BartyCrouch.translatewith the proper translation call, depending on your
transformeroption setting.
The resulting code depends on your
transformeroption setting:
When set to
foundation, the above code will transform to:
self.title = NSLocalizedString("onboarding.first-page.header-title", comment: "")
When set to
swiftgenStructuredit will transform to:
self.title = L10n.Onboarding.FirstPage.headerTitle
Advantages of
transformover the
codetask: * You can provide translations for keys without switching to the Strings files. * In case you use SwiftGen, you don't need to replace calls to
NSLocalizedStringwith
L10ncalls manually after running BartyCrouch. * Can be combined with the machine translation feature to provide a source language translation in code and let BartyCrouch translate it to all supported languages in a single line & without ever leaving the code.
Disadvantages of
transformover the
codetask: * Only works for Swift Code. No support for Objective-C. (You can use both methods simultaneously though.) * Xcode will mark the freshly transformed code as errors (but build will succeed anyways) until next build. * Not as fast as
codesince 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.
In order to truly profit from BartyCrouch's ability to update & lint your
.stringsfiles you can make it a natural part of your development workflow within Xcode. In order to do this select your target, choose the
Build Phasestab and click the + button on the top left corner of that pane. Select
New Run Script Phaseand copy the following into the text box below the
Shell: /bin/shof your new run script phase:
if which bartycrouch > /dev/null; then bartycrouch update -x bartycrouch lint -x else echo "warning: BartyCrouch not installed, download it from https://github.com/Flinesoft/BartyCrouch" fi
Next, make sure the BartyCrouch script runs before the steps
Compiling Sources(and
SwiftGenif 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
.stringsfiles.
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
NSLocalizedStringmacros comment part to ignore them so they are not added to your
Localizable.strings. This might be helpful when you are using a
.stringsdictfile 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) agokey 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.mdfile which explains your change.
After Release Checklist:
make portable_zipto generate
.build/release/portable_bartycrouch.zip
CHANGELOG.mdsection & attach
portable_bartycrouch.zipas binary
pod trunk pushto make a new release known to CocoaPods
tagand
revisionin
Formula/bartycrouch.rb, commit & push change
brew bump-formula-pr bartycrouch --tag= --revision=
This library is released under the MIT License. See LICENSE for details.