├── .github └── workflows │ ├── go.yml │ └── lsif.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── codecov.yml ├── go.mod ├── go.sum ├── i18n.go ├── i18n_test.go ├── testdata └── locale_en-US.ini └── ui18n ├── sync.go └── ui18n.go /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | on: 3 | push: 4 | branches: [ master ] 5 | paths: 6 | - '**.go' 7 | - 'go.mod' 8 | - '.golangci.yml' 9 | - '.github/workflows/go.yml' 10 | pull_request: 11 | paths: 12 | - '**.go' 13 | - 'go.mod' 14 | - '.golangci.yml' 15 | - '.github/workflows/go.yml' 16 | env: 17 | GOPROXY: "https://proxy.golang.org" 18 | 19 | jobs: 20 | lint: 21 | name: Lint 22 | runs-on: ubuntu-latest 23 | steps: 24 | - name: Checkout code 25 | uses: actions/checkout@v2 26 | - name: Run golangci-lint 27 | uses: golangci/golangci-lint-action@v2 28 | with: 29 | version: latest 30 | args: --timeout=30m 31 | 32 | test: 33 | name: Test 34 | strategy: 35 | matrix: 36 | go-version: [ 1.15.x, 1.16.x, 1.17.x ] 37 | platform: [ ubuntu-latest, macos-latest, windows-latest ] 38 | runs-on: ${{ matrix.platform }} 39 | steps: 40 | - name: Install Go 41 | uses: actions/setup-go@v2 42 | with: 43 | go-version: ${{ matrix.go-version }} 44 | - name: Checkout code 45 | uses: actions/checkout@v2 46 | - name: Run tests with coverage 47 | run: go test -v -race -coverprofile=coverage -covermode=atomic ./... 48 | - name: Upload coverage report to Codecov 49 | uses: codecov/codecov-action@v1.5.0 50 | with: 51 | file: ./coverage 52 | flags: unittests 53 | -------------------------------------------------------------------------------- /.github/workflows/lsif.yml: -------------------------------------------------------------------------------- 1 | name: LSIF 2 | on: 3 | push: 4 | paths: 5 | - '**.go' 6 | - 'go.mod' 7 | - '.github/workflows/lsif.yml' 8 | env: 9 | GOPROXY: "https://proxy.golang.org" 10 | 11 | jobs: 12 | lsif-go: 13 | if: github.repository == 'unknwon/i18n' 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Generate LSIF data 18 | uses: sourcegraph/lsif-go-action@master 19 | - name: Upload LSIF data to sourcegraph.com 20 | continue-on-error: true 21 | uses: docker://sourcegraph/src-cli:latest 22 | with: 23 | args: lsif upload -github-token=${{ secrets.GITHUB_TOKEN }} 24 | - name: Upload LSIF data to sourcegraph.unknwon.cn 25 | continue-on-error: true 26 | uses: docker://sourcegraph/src-cli:latest 27 | with: 28 | args: -endpoint=https://sourcegraph.unknwon.cn lsif upload -github-token=${{ secrets.GITHUB_TOKEN }} 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build test bench vet 2 | 3 | build: vet bench 4 | 5 | test: 6 | go test -v -cover 7 | 8 | bench: 9 | go test -v -cover -test.bench=. -test.benchmem 10 | 11 | vet: 12 | go vet -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # i18n 2 | 3 | [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/unknwon/i18n/Go?logo=github&style=for-the-badge)](https://github.com/unknwon/i18n/actions?query=workflow%3AGo) 4 | [![codecov](https://img.shields.io/codecov/c/github/unknwon/i18n/master?logo=codecov&style=for-the-badge)](https://codecov.io/gh/unknwon/i18n) 5 | [![GoDoc](https://img.shields.io/badge/GoDoc-Reference-blue?style=for-the-badge&logo=go)](https://pkg.go.dev/github.com/unknwon/i18n?tab=doc) 6 | [![Sourcegraph](https://img.shields.io/badge/view%20on-Sourcegraph-brightgreen.svg?style=for-the-badge&logo=sourcegraph)](https://sourcegraph.com/github.com/unknwon/i18n) 7 | 8 | Package i18n is for app Internationalization and Localization. 9 | 10 | ## Introduction 11 | 12 | This package provides multiple-language options to improve user experience. Sites like [Go Walker](http://gowalker.org) and [gogs.io](http://gogs.io) are using this module to implement Chinese and English user interfaces. 13 | 14 | You can use following command to install this module: 15 | 16 | go get github.com/unknwon/i18n 17 | 18 | ## Usage 19 | 20 | First of all, you have to import this package: 21 | 22 | ```go 23 | import "github.com/unknwon/i18n" 24 | ``` 25 | 26 | The format of locale files is very like INI format configuration file, which is basically key-value pairs. But this module has some improvements. Every language corresponding to a locale file, for example, suppose there are two files called `locale_en-US.ini` and `locale_zh-CN.ini`. 27 | 28 | The name and extensions of locale files can be anything, but we strongly recommend you to follow the style of gogsweb. 29 | 30 | ## Minimal example 31 | 32 | Here are two simplest locale file examples: 33 | 34 | File `locale_en-US.ini`: 35 | 36 | ```ini 37 | hi = hello, %s 38 | bye = goodbye 39 | ``` 40 | 41 | File `locale_zh-CN.ini`: 42 | 43 | ```ini 44 | hi = 您好,%s 45 | bye = 再见 46 | ``` 47 | 48 | ### Do Translation 49 | 50 | There are two ways to do translation depends on which way is the best fit for your application or framework. 51 | 52 | Directly use package function to translate: 53 | 54 | ```go 55 | i18n.Tr("en-US", "hi", "Unknwon") 56 | i18n.Tr("en-US", "bye") 57 | ``` 58 | 59 | Or create a struct and embed it: 60 | 61 | ```go 62 | type MyController struct{ 63 | // ...other fields 64 | i18n.Locale 65 | } 66 | 67 | //... 68 | 69 | func ... { 70 | c := &MyController{ 71 | Locale: i18n.Locale{"en-US"}, 72 | } 73 | _ = c.Tr("hi", "Unknwon") 74 | _ = c.Tr("bye") 75 | } 76 | ``` 77 | 78 | Code above will produce correspondingly: 79 | 80 | - English `en-US`:`hello, Unknwon`, `goodbye` 81 | - Chinese `zh-CN`:`您好,Unknwon`, `再见` 82 | 83 | ## Section 84 | 85 | For different pages, one key may map to different values. Therefore, i18n module also uses the section feature of INI format configuration to achieve section. 86 | 87 | For example, the key name is `about`, and we want to show `About` in the home page and `About Us` in about page. Then you can do following: 88 | 89 | Content in locale file: 90 | 91 | ```ini 92 | about = About 93 | 94 | [about] 95 | about = About Us 96 | ``` 97 | 98 | Get `about` in home page: 99 | 100 | ```go 101 | i18n.Tr("en-US", "about") 102 | ``` 103 | 104 | Get `about` in about page: 105 | 106 | ```go 107 | i18n.Tr("en-US", "about.about") 108 | ``` 109 | 110 | ### Ambiguity 111 | 112 | Because dot `.` is sign of section in both [INI parser](https://github.com/go-ini/ini) and locale files, so when your key name contains `.` will cause ambiguity. At this point, you just need to add one more `.` in front of the key. 113 | 114 | For example, the key name is `about.`, then we can use: 115 | 116 | ```go 117 | i18n.Tr("en-US", ".about.") 118 | ``` 119 | 120 | to get expect result. 121 | 122 | ## Helper tool 123 | 124 | Module i18n provides a command line helper tool beei18n for simplify steps of your development. You can install it as follows: 125 | 126 | go get github.com/unknwon/i18n/ui18n 127 | 128 | ### Sync locale files 129 | 130 | Command `sync` allows you use a exist local file as the template to create or sync other locale files: 131 | 132 | ui18n sync source_file.ini other1.ini other2.ini 133 | 134 | This command can operate 1 or more files in one command. 135 | 136 | ## More information 137 | 138 | - The first locale you load to the module is considered as **default locale**. 139 | - When matching non-default locale and didn't find the string, i18n will have a second try on default locale. 140 | - If i18n still cannot find string in the default locale, raw string will be returned. For instance, when the string is `hi` and it does not exist in locale file, simply return `hi` as output. 141 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | coverage: 2 | range: "60...95" 3 | status: 4 | project: 5 | default: 6 | threshold: 1% 7 | 8 | comment: 9 | layout: 'diff, files' 10 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/unknwon/i18n 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 // indirect 7 | github.com/unknwon/com v0.0.0-20190804042917-757f69c95f3e 8 | gopkg.in/ini.v1 v1.46.0 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= 2 | github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= 3 | github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= 4 | github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= 5 | github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= 6 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= 7 | github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= 8 | github.com/smartystreets/assertions v0.0.0-20190116191733-b6c0e53d7304 h1:Jpy1PXuP99tXNrhbq2BaPz9B+jNAvH1JPQQpG/9GCXY= 9 | github.com/smartystreets/assertions v0.0.0-20190116191733-b6c0e53d7304/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= 10 | github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s= 11 | github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 h1:WN9BUFbdyOsSH/XohnWpXOlq9NBD5sGAB2FciQMUEe8= 12 | github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= 13 | github.com/unknwon/com v0.0.0-20190804042917-757f69c95f3e h1:GSGeB9EAKY2spCABz6xOX5DbxZEXolK+nBSvmsQwRjM= 14 | github.com/unknwon/com v0.0.0-20190804042917-757f69c95f3e/go.mod h1:tOOxU81rwgoCLoOVVPHb6T/wt8HZygqH5id+GNnlCXM= 15 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 16 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 17 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 18 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 19 | golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 20 | gopkg.in/ini.v1 v1.46.0 h1:VeDZbLYGaupuvIrsYCEOe/L/2Pcs5n7hdO1ZTjporag= 21 | gopkg.in/ini.v1 v1.46.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= 22 | -------------------------------------------------------------------------------- /i18n.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Unknwon 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | // License for the specific language governing permissions and limitations 13 | // under the License. 14 | 15 | // Package i18n is for app Internationalization and Localization. 16 | package i18n 17 | 18 | import ( 19 | "errors" 20 | "fmt" 21 | "reflect" 22 | "strings" 23 | 24 | "gopkg.in/ini.v1" 25 | ) 26 | 27 | var ( 28 | ErrLangAlreadyExist = errors.New("Lang already exists") 29 | 30 | locales = &localeStore{store: make(map[string]*locale)} 31 | ) 32 | 33 | type locale struct { 34 | id int 35 | lang string 36 | langDesc string 37 | message *ini.File 38 | } 39 | 40 | type localeStore struct { 41 | langs []string 42 | langDescs []string 43 | store map[string]*locale 44 | defaultLang string 45 | } 46 | 47 | // Get target language string 48 | func (d *localeStore) Get(lang, section, format string) (string, bool) { 49 | if locale, ok := d.store[lang]; ok { 50 | if key, err := locale.message.Section(section).GetKey(format); err == nil { 51 | return key.Value(), true 52 | } 53 | } 54 | 55 | if len(d.defaultLang) > 0 && lang != d.defaultLang { 56 | return d.Get(d.defaultLang, section, format) 57 | } 58 | 59 | return "", false 60 | } 61 | 62 | func (d *localeStore) Add(lc *locale) bool { 63 | if _, ok := d.store[lc.lang]; ok { 64 | return false 65 | } 66 | 67 | lc.id = len(d.langs) 68 | d.langs = append(d.langs, lc.lang) 69 | d.langDescs = append(d.langDescs, lc.langDesc) 70 | d.store[lc.lang] = lc 71 | 72 | return true 73 | } 74 | 75 | func (d *localeStore) Reload(langs ...string) (err error) { 76 | if len(langs) == 0 { 77 | for _, lc := range d.store { 78 | if err = lc.message.Reload(); err != nil { 79 | return err 80 | } 81 | } 82 | } else { 83 | for _, lang := range langs { 84 | if lc, ok := d.store[lang]; ok { 85 | if err = lc.message.Reload(); err != nil { 86 | return err 87 | } 88 | } 89 | } 90 | } 91 | return nil 92 | } 93 | 94 | // SetDefaultLang sets default language which is a indicator that 95 | // when target language is not found, try find in default language again. 96 | func SetDefaultLang(lang string) { 97 | locales.defaultLang = lang 98 | } 99 | 100 | // ReloadLangs reloads locale files. 101 | func ReloadLangs(langs ...string) error { 102 | return locales.Reload(langs...) 103 | } 104 | 105 | // Count returns number of languages that are registered. 106 | func Count() int { 107 | return len(locales.langs) 108 | } 109 | 110 | // ListLangs returns list of all locale languages. 111 | func ListLangs() []string { 112 | langs := make([]string, len(locales.langs)) 113 | copy(langs, locales.langs) 114 | return langs 115 | } 116 | 117 | func ListLangDescs() []string { 118 | langDescs := make([]string, len(locales.langDescs)) 119 | copy(langDescs, locales.langDescs) 120 | return langDescs 121 | } 122 | 123 | // IsExist returns true if given language locale exists. 124 | func IsExist(lang string) bool { 125 | _, ok := locales.store[lang] 126 | return ok 127 | } 128 | 129 | // IndexLang returns index of language locale, 130 | // it returns -1 if locale not exists. 131 | func IndexLang(lang string) int { 132 | if lc, ok := locales.store[lang]; ok { 133 | return lc.id 134 | } 135 | return -1 136 | } 137 | 138 | // GetLangByIndex return language by given index. 139 | func GetLangByIndex(index int) string { 140 | if index < 0 || index >= len(locales.langs) { 141 | return "" 142 | } 143 | return locales.langs[index] 144 | } 145 | 146 | func GetDescriptionByIndex(index int) string { 147 | if index < 0 || index >= len(locales.langDescs) { 148 | return "" 149 | } 150 | 151 | return locales.langDescs[index] 152 | } 153 | 154 | func GetDescriptionByLang(lang string) string { 155 | return GetDescriptionByIndex(IndexLang(lang)) 156 | } 157 | 158 | func SetMessageWithDesc(lang, langDesc string, localeFile interface{}, otherLocaleFiles ...interface{}) error { 159 | message, err := ini.LoadSources(ini.LoadOptions{ 160 | IgnoreInlineComment: true, 161 | UnescapeValueCommentSymbols: true, 162 | }, localeFile, otherLocaleFiles...) 163 | if err == nil { 164 | message.BlockMode = false 165 | lc := new(locale) 166 | lc.lang = lang 167 | lc.langDesc = langDesc 168 | lc.message = message 169 | 170 | if !locales.Add(lc) { 171 | return ErrLangAlreadyExist 172 | } 173 | } 174 | return err 175 | } 176 | 177 | // Reset resets locale store. 178 | func Reset() { 179 | locales = &localeStore{store: make(map[string]*locale)} 180 | } 181 | 182 | // SetMessage sets the message file for localization. 183 | func SetMessage(lang string, localeFile interface{}, otherLocaleFiles ...interface{}) error { 184 | return SetMessageWithDesc(lang, lang, localeFile, otherLocaleFiles...) 185 | } 186 | 187 | // Locale represents the information of localization. 188 | type Locale struct { 189 | Lang string 190 | } 191 | 192 | // Tr translates content to target language. 193 | func (l Locale) Tr(format string, args ...interface{}) string { 194 | return Tr(l.Lang, format, args...) 195 | } 196 | 197 | // Index returns lang index of LangStore. 198 | func (l Locale) Index() int { 199 | return IndexLang(l.Lang) 200 | } 201 | 202 | // Tr translates content to target language. 203 | func Tr(lang, format string, args ...interface{}) string { 204 | var section string 205 | 206 | idx := strings.IndexByte(format, '.') 207 | if idx > 0 { 208 | section = format[:idx] 209 | format = format[idx+1:] 210 | } 211 | 212 | value, ok := locales.Get(lang, section, format) 213 | if ok { 214 | format = value 215 | } 216 | 217 | if len(args) > 0 { 218 | params := make([]interface{}, 0, len(args)) 219 | for _, arg := range args { 220 | if arg == nil { 221 | continue 222 | } 223 | 224 | val := reflect.ValueOf(arg) 225 | if val.Kind() == reflect.Slice { 226 | for i := 0; i < val.Len(); i++ { 227 | params = append(params, val.Index(i).Interface()) 228 | } 229 | } else { 230 | params = append(params, arg) 231 | } 232 | } 233 | return fmt.Sprintf(format, params...) 234 | } 235 | return format 236 | } 237 | -------------------------------------------------------------------------------- /i18n_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Unknwon 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | // License for the specific language governing permissions and limitations 13 | // under the License. 14 | 15 | package i18n 16 | 17 | import ( 18 | "testing" 19 | ) 20 | 21 | func Test_Tr(t *testing.T) { 22 | _ = SetMessage("en-US", "testdata/locale_en-US.ini") 23 | result := Tr("en-US", "NAME") 24 | if result != "English" { 25 | t.Errorf("expect 'English', got '%s'", result) 26 | } 27 | 28 | result = Tr("en-US", "section.NAME") 29 | if result != "Chinese" { 30 | t.Errorf("expect 'Chinese', got '%s'", result) 31 | } 32 | 33 | result = Tr("en-US", "SECONDS", 10) 34 | if result != "10 seconds" { 35 | t.Errorf("expect '10 seconds', got '%s'", result) 36 | } 37 | 38 | result = Tr("en-US", ".BAD.NAME") 39 | if result != "Bad Name" { 40 | t.Errorf("expect 'Bad Name', got '%s'", result) 41 | } 42 | 43 | result = Tr("en-US", "section.COMMENT_SYMBOL") 44 | if result != `test value more text` { 45 | t.Errorf(`expect 'test value more text', got '%s'`, result) 46 | } 47 | 48 | langs := ListLangs() 49 | if len(langs) != 1 { 50 | t.Errorf("expect '1', got '%d'", len(langs)) 51 | } else if langs[0] != "en-US" { 52 | t.Errorf("expect 'en-US', got '%s'", langs[0]) 53 | } 54 | 55 | Reset() 56 | 57 | langs = ListLangs() 58 | if len(langs) != 0 { 59 | t.Errorf("expect '0', got '%d'", len(langs)) 60 | } 61 | } 62 | 63 | func Benchmark_Tr(b *testing.B) { 64 | _ = SetMessage("en-US", "testdata/locale_en-US.ini") 65 | for i := 0; i < b.N; i++ { 66 | Tr("en-US", "NAME") 67 | } 68 | } 69 | 70 | func Benchmark_TrWithSection(b *testing.B) { 71 | _ = SetMessage("en-US", "testdata/locale_en-US.ini") 72 | for i := 0; i < b.N; i++ { 73 | Tr("en-US", "section.NAME") 74 | } 75 | } 76 | 77 | func Benchmark_TrWithFormat(b *testing.B) { 78 | _ = SetMessage("en-US", "testdata/locale_en-US.ini") 79 | for i := 0; i < b.N; i++ { 80 | Tr("en-US", "SECONDS", 10) 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /testdata/locale_en-US.ini: -------------------------------------------------------------------------------- 1 | NAME = English 2 | SECONDS = %d seconds 3 | .BAD.NAME = Bad Name 4 | 5 | [section] 6 | NAME = Chinese 7 | COMMENT_SYMBOL = test value more text -------------------------------------------------------------------------------- /ui18n/sync.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Unknwon 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | // License for the specific language governing permissions and limitations 13 | // under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "log" 19 | "os" 20 | 21 | "github.com/unknwon/com" 22 | "gopkg.in/ini.v1" 23 | ) 24 | 25 | var cmdSync = &Command{ 26 | UsageLine: "sync [source file] [target files]", 27 | Short: "sync keys for locale files", 28 | Long: `to quickly sync keys for one or more locale files 29 | based on the one you already have 30 | `, 31 | } 32 | 33 | func init() { 34 | cmdSync.Run = syncLocales 35 | } 36 | 37 | func syncLocales(cmd *Command, args []string) { 38 | switch len(args) { 39 | case 0: 40 | log.Fatalln("No source locale file is specified") 41 | case 1: 42 | log.Fatalln("No target locale file is specified") 43 | } 44 | 45 | srcLocale, err := ini.Load(args[0]) 46 | if err != nil { 47 | log.Fatalln(err) 48 | } 49 | 50 | // Load or create target locales. 51 | targets := args[1:] 52 | targetLocales := make([]*ini.File, len(targets)) 53 | for i, target := range targets { 54 | if !com.IsExist(target) { 55 | _, err = os.Create(target) 56 | if err != nil { 57 | log.Fatalln(err) 58 | } 59 | } 60 | 61 | targetLocales[i], err = ini.Load(target) 62 | if err != nil { 63 | log.Fatalln(err) 64 | } 65 | } 66 | 67 | for _, secName := range srcLocale.SectionStrings() { 68 | keyList := srcLocale.Section(secName).KeyStrings() 69 | for _, target := range targetLocales { 70 | sec, err := target.GetSection(secName) 71 | if err != nil { 72 | if sec, err = target.NewSection(secName); err != nil { 73 | log.Fatalln(err) 74 | } 75 | } 76 | for _, k := range keyList { 77 | if _, err = sec.GetKey(k); err != nil { 78 | _, err = sec.NewKey(k, "") 79 | if err != nil { 80 | log.Fatalln(err) 81 | } 82 | } 83 | } 84 | } 85 | } 86 | 87 | for i, target := range targetLocales { 88 | if err = target.SaveTo(targets[i]); err != nil { 89 | log.Fatalln(err) 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /ui18n/ui18n.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 Unknwon 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 | // not use this file except in compliance with the License. You may obtain 5 | // a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | // License for the specific language governing permissions and limitations 13 | // under the License. 14 | 15 | // ui18n is a helper tool for Unknwon/i18n package. 16 | package main 17 | 18 | import ( 19 | "flag" 20 | "fmt" 21 | "html/template" 22 | "io" 23 | "log" 24 | "os" 25 | "strings" 26 | ) 27 | 28 | type Command struct { 29 | // Run runs the command. 30 | // The args are the arguments after the command name. 31 | Run func(cmd *Command, args []string) 32 | 33 | // UsageLine is the one-line usage message. 34 | // The first word in the line is taken to be the command name. 35 | UsageLine string 36 | 37 | // Short is the short description shown in the 'go help' output. 38 | Short string 39 | 40 | // Long is the long message shown in the 'go help ' output. 41 | Long string 42 | 43 | // Flag is a set of flags specific to this command. 44 | Flag flag.FlagSet 45 | 46 | // CustomFlags indicates that the command will do its own 47 | // flag parsing. 48 | CustomFlags bool 49 | } 50 | 51 | // Name returns the command's name: the first word in the usage line. 52 | func (c *Command) Name() string { 53 | name := c.UsageLine 54 | i := strings.Index(name, " ") 55 | if i >= 0 { 56 | name = name[:i] 57 | } 58 | return name 59 | } 60 | 61 | func (c *Command) Usage() { 62 | fmt.Fprintf(os.Stderr, "usage: %s\n\n", c.UsageLine) 63 | fmt.Fprintf(os.Stderr, "%s\n", strings.TrimSpace(c.Long)) 64 | os.Exit(2) 65 | } 66 | 67 | // Runnable reports whether the command can be run; otherwise 68 | // it is a documentation pseudo-command such as importpath. 69 | func (c *Command) Runnable() bool { 70 | return c.Run != nil 71 | } 72 | 73 | var commands = []*Command{ 74 | cmdSync, 75 | } 76 | 77 | func main() { 78 | flag.Usage = usage 79 | flag.Parse() 80 | log.SetFlags(0) 81 | 82 | args := flag.Args() 83 | if len(args) < 1 { 84 | usage() 85 | } 86 | 87 | if args[0] == "help" { 88 | help(args[1:]) 89 | return 90 | } 91 | 92 | for _, cmd := range commands { 93 | if cmd.Name() == args[0] && cmd.Run != nil { 94 | cmd.Flag.Usage = func() { cmd.Usage() } 95 | if cmd.CustomFlags { 96 | args = args[1:] 97 | } else { 98 | _ = cmd.Flag.Parse(args[1:]) 99 | args = cmd.Flag.Args() 100 | } 101 | cmd.Run(cmd, args) 102 | os.Exit(2) 103 | return 104 | } 105 | } 106 | 107 | fmt.Fprintf(os.Stderr, "ui18n: unknown subcommand %q\nRun 'bee help' for usage.\n", args[0]) 108 | os.Exit(2) 109 | } 110 | 111 | var usageTemplate = `ui18n is a helper tool for beego/i18n package. 112 | 113 | Usage: 114 | 115 | ui18n command [arguments] 116 | 117 | The commands are: 118 | {{range .}}{{if .Runnable}} 119 | {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}} 120 | 121 | Use "ui18n help [command]" for more information about a command. 122 | ` 123 | 124 | var helpTemplate = `{{if .Runnable}}usage: ui18n {{.UsageLine}} 125 | 126 | {{end}}{{.Long | trim}} 127 | ` 128 | 129 | func usage() { 130 | tmpl(os.Stdout, usageTemplate, commands) 131 | os.Exit(2) 132 | } 133 | 134 | func tmpl(w io.Writer, text string, data interface{}) { 135 | t := template.New("top") 136 | t.Funcs(template.FuncMap{"trim": strings.TrimSpace}) 137 | template.Must(t.Parse(text)) 138 | if err := t.Execute(w, data); err != nil { 139 | panic(err) 140 | } 141 | } 142 | 143 | func help(args []string) { 144 | if len(args) == 0 { 145 | usage() 146 | // not exit 2: succeeded at 'go help'. 147 | return 148 | } 149 | if len(args) != 1 { 150 | fmt.Fprintf(os.Stdout, "usage: ui18n help command\n\nToo many arguments given.\n") 151 | os.Exit(2) // failed at 'bee help' 152 | } 153 | 154 | arg := args[0] 155 | 156 | for _, cmd := range commands { 157 | if cmd.Name() == arg { 158 | tmpl(os.Stdout, helpTemplate, cmd) 159 | // not exit 2: succeeded at 'go help cmd'. 160 | return 161 | } 162 | } 163 | 164 | fmt.Fprintf(os.Stdout, "Unknown help topic %#q. Run 'ui18n help'.\n", arg) 165 | os.Exit(2) // failed at 'bee help cmd' 166 | } 167 | --------------------------------------------------------------------------------