poesie 1.3.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 8f8bff2658b4d9825300ecb79bd1836dec4aa4cb
4
+ data.tar.gz: c8a17bc54ad8bcc73bf98c5edaede5aafcba2a4c
5
+ SHA512:
6
+ metadata.gz: 31faa35c132decdc0bcc018eca372d767dbe951b5b3ad09c03180f6cb41a3c1fc0fc1d1d6960e39dc1adb716f746a2f51690f77663b174072ff1aeb8b83e0e1b
7
+ data.tar.gz: 4d54dbbbc8abbdd960fd4e3af1074d862469e4d0e57cc10788b82882190e8c06e1baff590c88e286f10877b1506b75485484e98bceffaeeb554164d0ec485d78
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,178 @@
1
+ # Poesie
2
+
3
+ Poesie is the **POE**ditor **S**tring **I**nternationalization **E**xtractor.
4
+
5
+ ![Poesie Logo](logo.png)
6
+
7
+ _("poésie" also happens to be the French word for "poetry")_
8
+
9
+ ---
10
+
11
+ This repository contains a script to generate `iOS`' and `Android`'s localized strings files extracted from a [poeditor.com](https://poeditor.com) project:
12
+
13
+ Using [poeditor.com](https://poeditor.com), you will typically enter all your terms to translate, then all the translations for each language for those terms, using the web interface of the tool.
14
+
15
+ This tool can then automate the extraction / export of those translations to generate `Localizable.strings` and `Localizable.stringsdict` files for iOS, and `strings.xml` files for Android.
16
+
17
+ ## Advantages
18
+
19
+ Even though POEditor's web interface allows you to export the strings in those format already, the script has the following advantages:
20
+
21
+ * It **automates the process**, which can be very welcome if you update your localized strings quite often (instead of having to download the file for each language and each platform, then move the downloaded files from your Downloads folder to the correct location in your project, etc)
22
+ * It **post-processes** the exported files, including:
23
+ * Sorting the terms **alphabetically**
24
+ * **Filtering** out terms ending with `_ios` when exporting for Android, and filtering out terms ending with `_android` when exporting for iOS
25
+ * **Normalize the string placeholder** so you can use `%s` everywhere in your POEditor strings in the web interface — the script will automatically replace `%s` and `%n$s` with `%@` and `%n$@` when exporting to iOS, so no need to have different translations for those for each platform
26
+ * Allowing you to provide **text substitutions**, like replacing `"..."` with `"…"` and similar for all your translations (useful when your translator isn't always consistent with those typographical rules for example)
27
+ * Allows you to extract the **context strings** in a JSON file if you want to use them for whatever use case in your app
28
+
29
+
30
+ ## Installation
31
+
32
+ <details>
33
+ <summary>Solution 1: Clone the repo</summary>
34
+
35
+ * `git clone` the project on you computer
36
+ * Install `bundler` using `gem install bundler` if you don't have it already
37
+ * Install `poesie`'s dependencies by running `bundle install` from the directory where you cloned the repository
38
+ * Invoke the tool using its full path `<path/where/you/cloned/Poesie>/bin/poesie`.
39
+
40
+ You could also add the `<path/where/you/cloned/Poesie>/bin/` path to your `PATH` environment variable if you prefer.
41
+
42
+ </details>
43
+
44
+ <details>
45
+ <summary>Solution 2: Build and install it as a gem</summary>
46
+
47
+ * `git clone` the project on you computer
48
+ * Run `gem build poesie.gemspec` to build the gem
49
+ * Run `gem install poesie-*.gem` to install the gem you just built (`*` will be the version of the gem)
50
+ * Now that it's installed in your system, you can invoke the tool using `poesie` from anywhere
51
+
52
+ </details>
53
+
54
+
55
+ ## Using POEditor properly
56
+
57
+ ### Add your terms in POEditor's web interface
58
+
59
+ * If you don't have a project in POEditor, start by creating one.
60
+ * Then add some terms to translate. You can also indicate for each term if it will have a plural form or not (using the "P" button in POEditor web interface)
61
+ * Then add at least a language, and translate your terms for that language in the POEditor web interface
62
+
63
+ Of course, only list in POEditor the strings that needs a translation (user-facing strings), not JSON keys or constants, etc!
64
+
65
+ 💡 **Tip**: When adding a string to translate, be sure it doesn't already exist and hasn't already been added by another teammate (maybe using a different key) for example, by searching the text to translate in the POEditor web interface. This is especially worth checking because POEditor is typically limiting the maximum number of terms by a quota depending on your plan, so better not duplicate those terms!
66
+
67
+
68
+ ### Naming your terms
69
+
70
+ * Find a name for your term that is consistent with existing keys
71
+ * As a convention, for Niji projects, we structure the name of terms in a reverse-dns hierarchical text, using `_` as a separator. For example `home_banner_text` and `home_weather_temperature` (use `_` and not `.` because `.` causes issues in Android)
72
+ * If a key should only be exported for Android, use the `_android` suffix. If a key should only be exported for iOS, use the `_ios` suffix.
73
+
74
+ ### Using `%…` placeholders
75
+
76
+ * For keys that use string placeholders, use `%s` and not `%@`. Android doesn't know about `%@` (which is an iOS/macOS-only placeholder) and `%s` placeholders will be translated to `%@` automatically by this script
77
+ * Use positional placeholders like `%n$s`, instead of just `%s`, whenever possible.
78
+
79
+ > **Note**
80
+ >
81
+ > The `%n$s` syntax allows you to indicate the index of the parameter to use. This allows you to invert the order of the parameters in the translation, which can sometimes be needed for some languages (e.g. In English you'll use `%1$s's %2$d phones` to have "John's 3 phones", but in French you'll use `Les %2$d téléphones de %1$s` to have "Les 3 téléphones de John", where the number of phones comes before the person's name).
82
+ >
83
+ > If you don't specify the `n$` position number (but only e.g. `%s`), the parameters will be consumed in order.
84
+ > It's recommended to use the `n$` positional placeholders though, even if they are in order, so that the order is explict and not implicit.
85
+
86
+ ### Handling plurals
87
+
88
+ There's an oddity in POEditor when handling plurals: for a term to be marked to support plurals, you must activate the "P" round button next to the term… which will then display a field to enter the name of the term… when used for the plural variants.
89
+
90
+ I haven't seen any point of having a different term for the pluralized term and the singular term. Using a different name for the term and the plural term doesn't make sense to me.
91
+
92
+ Therefore, and given how the script interprets those terms, for terms with plurals, you should **always use the same name for the "term" and the "plural term"** when declaring them in the POEditor web interface:
93
+
94
+ ![Plurals example](plurals_example.png)
95
+
96
+ ### Handling newlines
97
+
98
+ * You can add newlines, either using actual newlines or using `\n`, in the translations in the web interface. Both (literal or escaped) should be interpreted and translated correctly by the script
99
+
100
+
101
+ ## Executing the script
102
+
103
+ Multiple options can be used when invoking the tool from the commandline:
104
+
105
+ ```
106
+ $ poesie -h
107
+ Usage: poesie [options]
108
+ -t, --token API_TOKEN Your POEditor API token
109
+ -p, --project PROJECT_ID Your POEditor project identifier
110
+ -l, --lang LANGUAGE The POEditor project language code to extract
111
+ -i, --ios PATH Path of the iOS Localizable.strings[dict] file to generate
112
+ -a, --android PATH Path of the Android strings.xml file path to generate
113
+ -c, --context PATH Path of the *.json file to generate for contexts
114
+ -d, --date Generate the current date in file headers
115
+ -r, --replacements FILE Path to a YAML file listing all replacements
116
+ -h, --help Show this message
117
+ -v, --version Show version
118
+ ```
119
+
120
+ * You'll typically always need to provide a token (`--token`) and a project ID (`--project`). Those can be found [here on the POEditor web interface](https://poeditor.com/account/api)
121
+
122
+ * You'll also always need to provide the language (`--lang`) you wish to extract and for which you want to generate the files. You can invoke the `poesie` script multiple times, one for each language you need to extract, if needed.
123
+
124
+ * Depending if you want to generate the localization files for Android (`strings.xml`) or iOS (`Localizable.strings` & `Localizable.stringsdict`), you'll use either `--ios PATH` or `--android PATH`. _(Note: for iOS, you give the path and name of the `Localizable.strings` file to generate, and the script will deduce itself the path for the `Localizable.stringsdict` to generate next to it)_
125
+
126
+ **Exemples** :
127
+
128
+ ```
129
+ $ poesie -t abcd1234efab5678abcd1234efab5678 -p 12345 -l fr -a /Users/me/Documents/Dev/MyApp/app/src/main/res/values/strings.xml
130
+ ```
131
+
132
+ ```
133
+ $ poesie -t abcd1234efab5678abcd1234efab5678 -p 12345 -l fr -i /Users/me/Documents/Dev/MyApp/Resources/Localizable.strings
134
+ ```
135
+
136
+
137
+ ## Using the --context flag
138
+
139
+ When running the `poesie` script using the `--context FILE` option, it will generate a JSON file at the provided path, containing all the terms for which you provided a "Context" (the "C" round button) in the POEditor web interface.
140
+
141
+ ```
142
+ $ poesie --token "..." --project "..." --lang fr --ios .../localizable.strings --context .../context.json
143
+ ```
144
+
145
+ This can be useful:
146
+
147
+ * Either to use that JSON file directly in your project to do whatever you want with the contexts (e.g. parsing the JSON file at runtime using `JSONSerialization`, and use it as you please)
148
+ * Or use that JSON file with a template engine (like [Liquid](https://github.com/Shopify/liquid)) to generate code specific to your needs. See the example script in `examples/gen-context-with-liquid.rb`.
149
+
150
+ ## Providing text replacements
151
+
152
+ In case you need replacements to be applied to your translations, you can use the `--replacements` flag (`-r` for short) to provide a YAML file listing all replacements to be applied.
153
+
154
+ ```
155
+ $ poesie --token "..." --project "..." --lang fr --ios .../localizable.strings -r replacements.yaml
156
+ ```
157
+
158
+ This can be useful:
159
+
160
+ * To replace standard spaces with non-breaking spaces before punctuation characters
161
+ * To replace "..." with "…" and similar
162
+ * To replace smiley strings like ";-)" with actual emoji characters like 😉
163
+ * To ensure proper capitalization and orthography of your brand name every time it's spelled in the translations
164
+ * etc.
165
+
166
+ The YAML file provided must be of the form of a single Hash of String pairs, for example:
167
+
168
+ ```yaml
169
+ " :": "\u00A0:"
170
+ " ;": "\u00A0;"
171
+ " !": "\u00A0!"
172
+ " ?": "\u00A0?"
173
+ "...": "…"
174
+ ```
175
+
176
+ _Note: given that the JSON format is a subset of the YAML format, using a JSON file is also possible, as long as it still represents a dictionary with Strings as keys and as values._
177
+
178
+ You can find an example of a YAML file in `examples/replacements.yaml` in this repository.
data/bin/poesie ADDED
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ if RUBY_VERSION < '2.0.0'
4
+ abort 'error: poesie requires Ruby 2 or higher.'
5
+ end
6
+
7
+ if $0 == __FILE__
8
+ $:.unshift File.expand_path('../lib', File.dirname(__FILE__))
9
+ end
10
+
11
+ begin
12
+ require 'optparse'
13
+ require 'yaml'
14
+ require 'poesie'
15
+ rescue LoadError => e
16
+ abort 'error: missing some dependencies for poesie. Be sure to install it using `gem install` or to run `bundle installl` to install dependencies - ' + e.message
17
+ end
18
+
19
+ options = {
20
+ :api_token => 'fc1881292605d21bc5531c6ffcf3e410',
21
+ :project_id => nil,
22
+ :lang => nil,
23
+ :localizable_strings => nil,
24
+ :strings_xml => nil,
25
+ :context_file => nil,
26
+ :print_date => false,
27
+ :replacements => nil
28
+ }
29
+
30
+ opts = OptionParser.new do |opts|
31
+ opts.banner = 'Usage: poesie [options]'
32
+ opts.on('-t API_TOKEN', '--token API_TOKEN', %q(Your POEditor API token)) do |api_token|
33
+ options[:api_token] = api_token
34
+ end
35
+ opts.on('-p PROJECT_ID', '--project PROJECT_ID', %q(Your POEditor project identifier)) do |project_id|
36
+ options[:project_id] = project_id
37
+ end
38
+ opts.on('-l LANGUAGE', '--lang LANGUAGE', %q(The POEditor project language code to extract)) do |lang|
39
+ options[:lang] = lang
40
+ end
41
+ opts.on('-i PATH', '--ios PATH', %q(Path of the iOS Localizable.strings[dict] file to generate)) do |path|
42
+ options[:localizable_strings] = path
43
+ end
44
+ opts.on('-a PATH', '--android PATH', %q(Path of the Android strings.xml file path to generate)) do |path|
45
+ options[:strings_xml] = path
46
+ end
47
+ opts.on('-c PATH', '--context PATH', %q(Path of the *.json file to generate for contexts)) do |path|
48
+ options[:context_file] = path
49
+ end
50
+ opts.on('-d', '--date', %q(Generate the current date in file headers)) do
51
+ options[:print_date] = true
52
+ end
53
+ opts.on('-r FILE', '--replacements FILE', %q(Path to a YAML file listing all replacements)) do |path|
54
+ Poesie.exit_with_error("The replacements file #{path} was not found") unless File.exists?(path)
55
+ begin
56
+ dict = YAML.load_file(path)
57
+ rescue Psych::SyntaxError => e
58
+ Poesie.exit_with_error("Invalid YAML file #{e.message}")
59
+ end
60
+ valid = dict.keys.all? { |k| k.is_a?(String) } && dict.values.all? { |k| k.is_a?(String) }
61
+ Poesie.exit_with_error("The provided replacements file #{path} should only contain a Dictionary with String keys and values") unless valid
62
+ options[:replacements] = dict
63
+ end
64
+ opts.on_tail('-h', '--help', %q(Show this message)) { puts opts; exit 1 }
65
+ opts.on_tail('-v', '--version', 'Show version') { puts Poesie::VERSION; exit }
66
+ end
67
+
68
+ begin
69
+ opts.parse!
70
+ rescue OptionParser::InvalidOption => error
71
+ puts error
72
+ puts opts
73
+ exit 1
74
+ end
75
+
76
+ ### Main ###
77
+
78
+ Poesie.exit_with_error('You need to specify your POEditor project identifier using --project option (see --help for more info)') if options[:project_id].nil?
79
+ exporter = Poesie::Exporter.new(options[:api_token], options[:project_id])
80
+ Poesie.exit_with_error('You need to specify your POEditor project language using --lang option (see --help for more info)') if options[:lang].nil?
81
+
82
+ # iOS
83
+ unless options[:localizable_strings].nil?
84
+ Log::title('== iOS ==')
85
+ exporter.run(options[:lang]) do |terms|
86
+ # Localizable.strings
87
+ Log::subtitle("== Language #{options[:lang]} ==")
88
+ Poesie::AppleFormatter::write_strings_file(
89
+ terms,
90
+ options[:localizable_strings],
91
+ replacements: options[:replacements],
92
+ print_date: options[:print_date]
93
+ )
94
+
95
+ # Localizable.stringsdict
96
+ strings_dict_path = options[:localizable_strings].gsub(/\.strings$/,'.stringsdict')
97
+ Poesie::AppleFormatter::write_stringsdict_file(
98
+ terms,
99
+ strings_dict_path,
100
+ replacements: options[:replacements],
101
+ print_date: options[:print_date]
102
+ )
103
+
104
+ # Context.json (if specified)
105
+ if options[:context_file]
106
+ Log::subtitle("== Context #{options[:context_file]} ==")
107
+ Poesie::AppleFormatter::write_context_json(terms, options[:context_file])
108
+ end
109
+ end
110
+ end
111
+
112
+ # Android
113
+ unless options[:strings_xml].nil?
114
+ Log::title('== Android ==')
115
+ exporter.run(options[:lang]) do |terms|
116
+ # Strings.xml
117
+ Log::subtitle("== Language #{options[:lang]} ==")
118
+ Poesie::AndroidFormatter::write_strings_xml(
119
+ terms,
120
+ options[:strings_xml],
121
+ replacements: options[:replacements],
122
+ print_date: options[:print_date]
123
+ )
124
+ end
125
+ end
@@ -0,0 +1,51 @@
1
+ require 'builder'
2
+
3
+ module Poesie
4
+ module AndroidFormatter
5
+
6
+ # Write the strings.xml output file
7
+ #
8
+ # @param [Hash] terms
9
+ # The json parsed terms exported by POEditor and sorted alphabetically
10
+ # @param [String] file
11
+ # The path to the file to write the content to
12
+ # @param [Hash<String,String>] replacements
13
+ # The list of replacements to apply to the translations
14
+ # @param [Bool] print_date
15
+ # Should we print the date in the header of the generated file
16
+ #
17
+ def self.write_strings_xml(terms, file, replacements: nil, print_date: false)
18
+ Log::info(" - Save to file: #{file}")
19
+ fh = File.open(file, "w")
20
+ begin
21
+ xml_builder = Builder::XmlMarkup.new(:target => fh, :indent => 4)
22
+ xml_builder.instruct!
23
+ xml_builder.comment!("Exported from POEditor ")
24
+ xml_builder.comment!(Time.now) if print_date
25
+ xml_builder.comment!("see https://poeditor.com ")
26
+ xml_builder.resources do |resources_node|
27
+ terms.each do |term|
28
+ (term, definition, plurals, comment, context) = ['term', 'definition', 'term_plural', 'comment', 'context'].map { |k| term[k] }
29
+ # Skip ugly cases if POEditor is buggy for some entries
30
+ next if term.nil? || term.empty? || definition.nil?
31
+ next if term =~ /_ios$/
32
+ xml_builder.comment!(context) unless context.empty?
33
+ if plurals.empty?
34
+ definition = Poesie::process(definition, replacements).gsub('"', '\\"')
35
+ resources_node.string("\"#{definition}\"", :name => term)
36
+ else
37
+ resources_node.plurals(:name => plurals) do |plurals_node|
38
+ definition.each do |plural_quantity, plural_value|
39
+ plural_value = Poesie::process(plural_value, replacements).gsub('"', '\\"')
40
+ plurals_node.item("\"#{plural_value}\"", :quantity => plural_quantity)
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
46
+ ensure
47
+ fh.close
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,173 @@
1
+ require 'builder'
2
+
3
+ module Poesie
4
+ module AppleFormatter
5
+
6
+ # Write the Localizable.strings output file
7
+ #
8
+ # @param [Array<Hash<String, Any>>] terms
9
+ # JSON returned by the POEditor API
10
+ # @param [String] file
11
+ # The path of the file to write
12
+ # @param [Hash<String,String>] replacements
13
+ # The list of replacements to apply to the translations
14
+ # @param [Bool] print_date
15
+ # Should we print the date in the header of the generated file
16
+ #
17
+ def self.write_strings_file(terms, file, replacements: nil, print_date: false)
18
+ out_lines = ['/'+'*'*79, ' * Exported from POEditor - https://poeditor.com']
19
+ out_lines << " * #{Time.now}" if print_date
20
+ out_lines += [' '+'*'*79+'/', '']
21
+ last_prefix = ''
22
+ stats = { :android => 0, :nil => 0, :count => 0 }
23
+
24
+ terms.each do |term|
25
+ (term, definition, comment, context) = ['term', 'definition', 'comment', 'context'].map { |k| term[k] }
26
+
27
+ # Filter terms and update stats
28
+ next if (term.nil? || term.empty? || definition.nil? || definition.empty?) && stats[:nil] += 1
29
+ next if (term =~ /_android$/) && stats[:android] += 1 # Remove android-specific strings
30
+ stats[:count] += 1
31
+
32
+ # Generate MARK from prefixes
33
+ prefix = %r(([^_]*)_.*).match(term)
34
+ if prefix && prefix[1] != last_prefix
35
+ last_prefix = prefix[1]
36
+ mark = last_prefix[0].upcase + last_prefix[1..-1].downcase
37
+ out_lines += ['', '/'*80, "// MARK: #{mark}"]
38
+ end
39
+
40
+ # If plural, use the text for the "one" (singular) entry
41
+ if definition.is_a? Hash
42
+ definition = definition["one"]
43
+ end
44
+
45
+ definition = Poesie::process(definition, replacements)
46
+ .gsub("\u2028", '') # Sometimes inserted by the POEditor exporter
47
+ .gsub("\n", '\n') # Replace actual CRLF with '\n'
48
+ .gsub('"', '\\"') # Escape quotes
49
+ .gsub(/%(\d+\$)?s/, '%\1@') # replace %s with %@ for iOS
50
+ out_lines << %Q(// CONTEXT: #{context.gsub("\n", '\n')}) unless context.empty?
51
+ out_lines << %Q("#{term}" = "#{definition}";)
52
+ end
53
+
54
+ content = out_lines.join("\n") + "\n"
55
+
56
+
57
+ Log::info(" [Stats] #{stats[:count]} strings processed (Filtered out #{stats[:android]} android strings, #{stats[:nil]} nil entries)")
58
+ Log::info(" - Save to file: #{file}")
59
+ File.open(file, "w") do |fh|
60
+ fh.write(content)
61
+ end
62
+ end
63
+
64
+ # Write the Localizable.stringsdict output file
65
+ #
66
+ # @param [Array<Hash<String, Any>>] terms
67
+ # JSON returned by the POEditor API
68
+ # @param [String] file
69
+ # The path of the file to write
70
+ # @param [Hash<String,String>] replacements
71
+ # The list of replacements to apply to the translations
72
+ # @param [Bool] print_date
73
+ # Should we print the date in the header of the generated file
74
+ #
75
+ def self.write_stringsdict_file(terms, file, replacements: nil, print_date: false)
76
+ stats = { :android => 0, :nil => 0, :count => 0 }
77
+
78
+ Log::info(" - Save to file: #{file}")
79
+ fh = File.open(file, "w")
80
+ begin
81
+ xml_builder = Builder::XmlMarkup.new(:target => fh, :indent => 4)
82
+ xml_builder.instruct!
83
+ xml_builder.comment!("Exported from POEditor ")
84
+ xml_builder.comment!(Time.now) if print_date
85
+ xml_builder.comment!("see https://poeditor.com ")
86
+ xml_builder.plist(:version => '1.0') do |plist_node|
87
+ plist_node.dict do |root_node|
88
+ terms.each do |term|
89
+ (term, term_plural, definition) = ['term', 'term_plural', 'definition'].map { |k| term[k] }
90
+
91
+ # Filter terms and update stats
92
+ next if (term.nil? || term.empty? || definition.nil?) && stats[:nil] += 1
93
+ next if (term =~ /_android$/) && stats[:android] += 1 # Remove android-specific strings
94
+ next unless definition.is_a? Hash
95
+ stats[:count] += 1
96
+
97
+ key = term_plural || term
98
+
99
+
100
+ root_node.key(key)
101
+ root_node.dict do |dict_node|
102
+ dict_node.key('NSStringLocalizedFormatKey')
103
+ dict_node.string('%#@format@')
104
+ dict_node.key('format')
105
+ dict_node.dict do |format_node|
106
+ format_node.key('NSStringFormatSpecTypeKey')
107
+ format_node.string('NSStringPluralRuleType')
108
+ format_node.key('NSStringFormatValueTypeKey')
109
+ format_node.string('d')
110
+
111
+ definition.each do |(quantity, text)|
112
+ text = Poesie::process(text, replacements)
113
+ .gsub("\u2028", '') # Sometimes inserted by the POEditor exporter
114
+ .gsub('\n', "\n") # Replace '\n' with actual CRLF
115
+ .gsub(/%(\d+\$)?s/, '%\1@') # replace %s with %@ for iOS
116
+ format_node.key(quantity)
117
+ format_node.string(text)
118
+ end
119
+ end
120
+ end
121
+ end
122
+ end
123
+ end
124
+ ensure
125
+ fh.close
126
+ end
127
+ end
128
+
129
+ # Write the JSON output file containing all context keys
130
+ #
131
+ # @param [Array<Hash<String, Any>>] terms
132
+ # JSON returned by the POEditor API
133
+ # @param [String] file
134
+ # The path of the file to write
135
+ #
136
+ def self.write_context_json(terms, file)
137
+ json_hash = { "date" => "#{Time.now}" }
138
+
139
+ stats = { :android => 0, :nil => 0, :count => 0 }
140
+
141
+ #switch on term / context
142
+ array_context = Array.new
143
+ terms.each do |term|
144
+ (term, definition, comment, context) = ['term', 'definition', 'comment', 'context'].map { |k| term[k] }
145
+
146
+ # Filter terms and update stats
147
+ next if (term.nil? || term.empty? || context.nil? || context.empty?) && stats[:nil] += 1
148
+ next if (term =~ /_android$/) && stats[:android] += 1 # Remove android-specific strings
149
+ stats[:count] += 1
150
+
151
+ # Escape some chars
152
+ context = context
153
+ .gsub("\u2028", '') # Sometimes inserted by the POEditor exporter
154
+ .gsub("\\", "\\\\\\") # Replace actual \ with \\
155
+ .gsub('\\\\"', '\\"') # Replace actual \\" with \"
156
+ .gsub(/%(\d+\$)?s/, '%\1@') # replace %s with %@ for iOS
157
+
158
+ array_context << { "term" => "#{term}", "context" => "#{context}" }
159
+ end
160
+
161
+ json_hash[:"contexts"] = array_context
162
+
163
+ context_json = JSON.pretty_generate(json_hash)
164
+
165
+ Log::info(" [Stats] #{stats[:count]} contexts processed (Filtered out #{stats[:android]} android entries, #{stats[:nil]} nil contexts)")
166
+ Log::info(" - Save to file: #{file}")
167
+ File.open(file, "w") do |fh|
168
+ fh.write(context_json)
169
+ end
170
+ end
171
+
172
+ end
173
+ end
data/lib/exporter.rb ADDED
@@ -0,0 +1,56 @@
1
+ require 'net/http'
2
+
3
+ module Poesie
4
+ class Exporter
5
+ # @param [String] api_token
6
+ # POEditor API Token
7
+ # @param [String] project_id
8
+ # ID of the project in your POEditor Dashboard
9
+ #
10
+ def initialize(api_token, project_id)
11
+ @api_token = api_token
12
+ @project_id = project_id
13
+ end
14
+
15
+ # Use the POEditor API to download the terms for a given language, then call a block
16
+ # to post-process those terms (exported as a JSON structure)
17
+ #
18
+ # @param [String] lang
19
+ # The language to export
20
+ # @block [[JSON] -> Void]
21
+ # The action to do with the exported terms
22
+ # Typically call one of AppleFormatter::… or AndroidFormatter::… methods here
23
+ #
24
+ def run(lang)
25
+ Log::info(' - Generating export...')
26
+ uri = generate_export_uri(lang)
27
+ Log::info(' - Downloading exported file...')
28
+ json_string = Net::HTTP.get(URI(uri))
29
+ json = JSON.parse(json_string)
30
+ terms = json.sort { |item1, item2| item1['term'] <=> item2['term'] }
31
+ if block_given?
32
+ Log::info(' - Processing generated strings...')
33
+ yield terms
34
+ end
35
+ end
36
+
37
+ private
38
+
39
+ # @param [String] lang
40
+ # Language code, like 'fr', 'en', etc
41
+ # @return [String] URL of the exported file ready to be downloaded
42
+ #
43
+ def generate_export_uri(lang)
44
+ uri = URI('https://poeditor.com/api/')
45
+ res = Net::HTTP.post_form(uri, 'api_token' => @api_token, 'action' => 'export', 'id' => @project_id, 'type' => 'json', 'language' => lang)
46
+ json = JSON.parse(res.body)
47
+ if json['response']['status'] != 'success'
48
+ r = json['response']
49
+ puts "Error #{r['code']} (#{r['status']})\n#{r['message']}"
50
+ exit 1
51
+ else
52
+ json['item']
53
+ end
54
+ end
55
+ end
56
+ end
data/lib/poesie.rb ADDED
@@ -0,0 +1,30 @@
1
+ require File.expand_path('utils/log', File.dirname(__FILE__))
2
+
3
+ require File.expand_path('exporter', File.dirname(__FILE__))
4
+ require File.expand_path('android_formatter', File.dirname(__FILE__))
5
+ require File.expand_path('apple_formatter', File.dirname(__FILE__))
6
+
7
+ require 'json'
8
+
9
+ module Poesie
10
+ def self.exit_with_error(message)
11
+ Log::error message
12
+ exit 1
13
+ end
14
+
15
+ # Apply the list of text replacements to the given string
16
+ #
17
+ # @param [String] text
18
+ # The text to process
19
+ # @param [Hash<String,String>] replacements
20
+ # The replacements to apply
21
+ #
22
+ def self.process(text, replacements)
23
+ return text if replacements.nil?
24
+ replaced = text.dup
25
+ replacements.each do |k,v|
26
+ replaced.gsub!(k, v)
27
+ end
28
+ replaced
29
+ end
30
+ end
data/lib/utils/log.rb ADDED
@@ -0,0 +1,23 @@
1
+ module Log
2
+ @@quiet = false
3
+ def self.quiet=(value)
4
+ @@quiet = value
5
+ end
6
+
7
+ def self.title(str) # bg yellow
8
+ puts "\e[44;37m#{str}\e[0m" unless @@quiet
9
+ end
10
+
11
+ def self.error(str)
12
+ puts "\e[1;31m! #{str}\e[0m" unless @@quiet
13
+ end
14
+
15
+ def self.info(str)
16
+ puts "\e[1;32m√ #{str}\e[0m" unless @@quiet
17
+ end
18
+
19
+ def self.subtitle(str)
20
+ puts "\e[1;33m√ #{str}\e[0m" unless @@quiet
21
+ end
22
+
23
+ end
data/lib/version.rb ADDED
@@ -0,0 +1,3 @@
1
+ module Poesie
2
+ VERSION = '1.3.0'
3
+ end
metadata ADDED
@@ -0,0 +1,98 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: poesie
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.3.0
5
+ platform: ruby
6
+ authors:
7
+ - Olivier Halligon
8
+ - NijiDigital
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2017-02-07 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: net
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - ~>
19
+ - !ruby/object:Gem::Version
20
+ version: '0.3'
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ~>
26
+ - !ruby/object:Gem::Version
27
+ version: '0.3'
28
+ - !ruby/object:Gem::Dependency
29
+ name: activesupport
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - ~>
33
+ - !ruby/object:Gem::Version
34
+ version: '4.2'
35
+ type: :runtime
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ~>
40
+ - !ruby/object:Gem::Version
41
+ version: '4.2'
42
+ - !ruby/object:Gem::Dependency
43
+ name: builder
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ~>
47
+ - !ruby/object:Gem::Version
48
+ version: '3.0'
49
+ type: :runtime
50
+ prerelease: false
51
+ version_requirements: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ~>
54
+ - !ruby/object:Gem::Version
55
+ version: '3.0'
56
+ description: This script automates the export of POEditor strings to iOS and Android
57
+ files
58
+ email: devs-ios@niji.fr
59
+ executables:
60
+ - poesie
61
+ extensions: []
62
+ extra_rdoc_files: []
63
+ files:
64
+ - LICENSE
65
+ - README.md
66
+ - bin/poesie
67
+ - lib/android_formatter.rb
68
+ - lib/apple_formatter.rb
69
+ - lib/exporter.rb
70
+ - lib/poesie.rb
71
+ - lib/utils/log.rb
72
+ - lib/version.rb
73
+ homepage: https://github.com/NijiDigital/poesie
74
+ licenses:
75
+ - Apache-2.0
76
+ metadata: {}
77
+ post_install_message:
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - '>='
84
+ - !ruby/object:Gem::Version
85
+ version: 2.0.0
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - '>='
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubyforge_project:
93
+ rubygems_version: 2.4.7
94
+ signing_key:
95
+ specification_version: 4
96
+ summary: Automate and post-process the export of POEditor strings
97
+ test_files: []
98
+ has_rdoc: